//
//  YHCertificateInfoController.swift
//  galaxy
//
//  Created by edy on 2024/1/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHCertificateInfoController: YHBaseViewController, YHFamilyMemberProtol {

    var familyMember:YHFamilyMember?
    weak var delegate:YHSpouseInfoVCProtocol?
    var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    // 是否显示未填写错误提示
    var isNeedShowError = false
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor(hexString:"#F8F8F8")
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHFormItemDoubleChoiceCell.self, forCellReuseIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier)
        tableView.register(YHFormItemInputTextCell.self, forCellReuseIdentifier: YHFormItemInputTextCell.cellReuseIdentifier)
        tableView.register(YHFormItemEnterDetailCell.self, forCellReuseIdentifier: YHFormItemEnterDetailCell.cellReuseIdentifier)
        tableView.register(YHFormItemTitleCell.self, forCellReuseIdentifier: YHFormItemTitleCell.cellReuseIdentifier)
        tableView.register(YHFormItemAddCell.self, forCellReuseIdentifier: YHFormItemAddCell.cellReuseIdentifier)
        tableView.register(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        tableView.register(YHFormItemExpireDateCell.self, forCellReuseIdentifier: YHFormItemExpireDateCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor(hexString:"#F8F8F8")
        createUI()
        loadInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        let topHeight = k_Height_NavigationtBarAndStatuBar+YHStepView.height
        let bottomHeight = YHSaveAndSubmitView.height
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(KScreenHeight-topHeight-bottomHeight)
        }
        
        guard let familyMember = familyMember else { return }
        loadInfo()
    }
    
    func loadInfo() {
    
        guard let familyMember = familyMember else { return }
        items.removeAll()
        
        // 中国身份证
        let isChinaCardMust = familyMember.isChinese() && familyMember.relationType != .child
        let title0 = YHFormTitleItem(type: .chinaIdCardInfo)
        
        let item01 = YHFormDetailItem(type: .chinaIdentityCardNumber, isNeed:isChinaCardMust, value:familyMember.certificates.cnIdentityCard.number, tips: "请输入正确的中国身份证号".local)
        let item02 = YHFormDetailItem(type: .certificateSignPlace, isNeed:isChinaCardMust, value:familyMember.certificates.cnIdentityCard.issueAt, tips: "请输入签发地".local)
        let item03 = YHFormDetailItem(type: .certificateSignDate, isNeed:isChinaCardMust, value:familyMember.certificates.cnIdentityCard.issueDateStartAt, tips: "请选择签发日期".local)
        let item04 = YHFormDetailItem(type: .certificateValidDate, isNeed:isChinaCardMust, value:familyMember.certificates.cnIdentityCard.issueDateEndAt, tips: "请选择签发日期".local)
        let arr0:[YHFormItemProtocol] = [title0, item01, item02, item03, item04]
        items.append(arr0)
        
                    
        // 港澳通行证 非必须
        if familyMember.isNeedHandleHKPassPort() {
            let title1 = YHFormTitleItem(type: .hkAndMacaoPassport)
            let item10 = YHFormDetailItem(type: .traverlPassportNumber, value: familyMember.certificates.hkMacaoPass.number, tips:"请输入证件号码".local)
            let item11 = YHFormDetailItem(type: .certificateSignPlace, value: familyMember.certificates.hkMacaoPass.issueAt, tips:"请输入签发地".local)
            let item12 = YHFormDetailItem(type: .certificateSignDate, value: familyMember.certificates.hkMacaoPass.issueDateStartAt, tips:"请选择签发日期".local)
            let item13 = YHFormDetailItem(type: .certificateValidDate, value: familyMember.certificates.hkMacaoPass.issueDateEndAt, tips:"请选择届满日期".local)
            let arr1:[YHFormItemProtocol] = [title1, item10, item11, item12, item13]
            items.append(arr1)
        }
        
        // 护照及其他旅行证件 信息必有
        let isPassPortMust = !familyMember.isChinese()
        let title2 = YHFormTitleItem(type: .passPortOrTravelInfo)
        
        // 证件类别名称
        var value = ""
        let passPortType = self.familyMember?.certificates.passport.passPortType ?? 0
        if let item = YHSheetPickerView.getItem(type:.certificate, index:passPortType) {
            value = item.title
        }
        let item20 = YHFormDetailItem(type: .certificateType, isNeed: isPassPortMust, value:value, tips:"请选择证件类别".local)
        let item21 = YHFormDetailItem(type: .certificateNumber, isNeed: isPassPortMust, value: familyMember.certificates.passport.number, tips: "请输入证件号码".local)
        let item22 = YHFormDetailItem(type: .certificateSignPlace, isNeed: isPassPortMust, value: familyMember.certificates.passport.issueAt, tips:"请输入签发地".local)
        let item23 = YHFormDetailItem(type: .certificateSignDate, isNeed: isPassPortMust, value:familyMember.certificates.passport.issueDateStartAt, tips:"请选择签发日期".local)
        let item24 = YHFormDetailItem(type: .certificateValidDate, isNeed: isPassPortMust, value:familyMember.certificates.passport.issueDateEndAt,tips:"请选择届满日期".local)
        let arr2:[YHFormItemProtocol] = [title2, item20, item21, item22, item23, item24]
        items.append(arr2)
        
        tableView.reloadData()
    }
}

extension YHCertificateInfoController : UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section >= items.count { return 0 }
        let arr = items[section]
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section >= items.count { return createDefaultCell(indexPath) }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return createDefaultCell(indexPath) }
        
        
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 标题
            let titleItem = item as! YHFormTitleItem
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            
            var isNeedText = ""
            if titleItem.type == .chinaIdCardInfo {
                if let familyMember = familyMember {
                    let isChinaCardMust = familyMember.isChinese() && familyMember.relationType != .child
                    isNeedText = isChinaCardMust ? "(必填)" : "(选填)"
                }
                
            } else if titleItem.type == .hkAndMacaoPassport {
                if let familyMember = familyMember {
                    isNeedText = familyMember.isNeedHandleHKPassPort() ? "(必填)" : "(选填)"
                }
                
            } else if titleItem.type == .passPortOrTravelInfo {
                if let familyMember = familyMember {
                    let isPassPortMust = !familyMember.isChinese()
                    isNeedText = isPassPortMust ? "(必填)" : "(选填)"
                }
            }
            
            var title = ""
            if isNeedText.isEmpty {
                title = item.getTitle()
            } else {
                title = "\(item.getTitle())\(isNeedText)"
            }
            cell.setTitleAndSubTitle(title: title)
            return cell
        }
        
        if item is YHFormDetailItem {
            
            let detailItem = item as! YHFormDetailItem
            let title = arr[0] as! YHFormTitleItem
            
            if detailItem.type == .chinaIdentityCardNumber || detailItem.type == .certificateSignPlace || detailItem.type == .traverlPassportNumber || detailItem.type == .certificateNumber { // 证件号码和签发地需要填写
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as! YHFormItemInputTextCell
                cell.isMust = detailItem.isNeed
                cell.placeHolder = detailItem.placeHolder
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                if detailItem.type == .chinaIdentityCardNumber {
                    cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isNeed && detailItem.value?.count != 18)
                } else {
                    cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isNeed && detailItem.isShowTips)
                }
                
                cell.textInputCondtion = {
                    textField in
                    
                    var max = -1
                    if detailItem.type == .chinaIdentityCardNumber { // 身份证
                        max = 18
                    } else if detailItem.type == .certificateSignPlace { // 签发地
                        max = 50
                    } else if detailItem.type == .traverlPassportNumber ||
                              detailItem.type == .certificateNumber {
                        max = 50
                    }

                    if max > 0 {
                        if let textStr = textField.text {
                            textField.text = (textStr.count > max ? textStr[safe: ..<max] : textStr)
                        }
                    }
                    return true
                }
                cell.textChange = {
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    
                    if detailItem.type == .chinaIdentityCardNumber {
                        self.familyMember?.certificates.cnIdentityCard.number = text ?? ""
                        
                    } else if detailItem.type == .traverlPassportNumber {
                        self.familyMember?.certificates.hkMacaoPass.number = text ?? ""
                        
                    } else if detailItem.type == .certificateNumber {
                        self.familyMember?.certificates.passport.number = text ?? ""
                        
                    } else if detailItem.type == .certificateSignPlace { // 签发地
                        
                            if title.type == .chinaIdCardInfo {
                                self.familyMember?.certificates.cnIdentityCard.issueAt = text ?? ""
                                
                            } else if title.type == .hkAndMacaoPassport {
                                self.familyMember?.certificates.hkMacaoPass.issueAt = text ?? ""

                            } else if title.type == .passPortOrTravelInfo {
                                self.familyMember?.certificates.passport.issueAt = text ?? ""
                            }
                    }
                    if isEditEnd {
                        self.loadInfo()
                        self.save()
                    }
                }
                return cell
            }
            
            if detailItem.type == .certificateType || detailItem.type == .certificateSignDate {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isNeed && detailItem.isShowTips)
                return cell
            }
            
            if detailItem.type == .certificateValidDate { // 届满日期
                
                if title.type == .chinaIdCardInfo { // 身份证
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemExpireDateCell.cellReuseIdentifier, for: indexPath) as! YHFormItemExpireDateCell
                    cell.isMust = detailItem.isNeed
                    cell.title = detailItem.getTitle()
                    cell.detail = (detailItem.value == YHCNIdentityCard.longTime ? "" : detailItem.value)
                    cell.isLongTime = (detailItem.value == YHCNIdentityCard.longTime)
                    cell.clickBlock = {
                        [weak self] isLongTime in
                        guard let self = self else { return }
                        if title.type == .chinaIdCardInfo {
                            guard let familyMember = familyMember else { return }
                            familyMember.certificates.cnIdentityCard.issueDateEndAt = (isLongTime ? YHCNIdentityCard.longTime : familyMember.certificates.cnIdentityCard.lastIssueDateEndAt)
                            loadInfo()
                            save()
                        }
                    }
                    cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isNeed && detailItem.isShowTips)
                    return cell
                    
                }
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isNeed && detailItem.isShowTips)
                return cell
            }
        }
        
        return createDefaultCell(indexPath)
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.section >= items.count { return  }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return }
        createCorner(cell: cell, arr: arr, indexPath: indexPath)
    }
    
    func createDefaultCell(_ indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if !(0..<items.count).contains(indexPath.section) { return }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if !(0..<arr.count).contains(indexPath.row) {  return  }
        let item = arr[indexPath.row]
        
        if item is YHFormTitleItem {
            return
        }
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            let titleItem = arr[0] as! YHFormTitleItem
            
            if detailItem.type == .certificateValidDate ||
               detailItem.type == .certificateSignDate { // 届满日期 签发日期
                
                var title = ""
                var lastIsTaday = false
                if detailItem.type == .certificateValidDate {
                    title = "选择届满日期"
                    lastIsTaday = false
                } else if detailItem.type == .certificateSignDate {
                    title = "选择签发日期"
                    lastIsTaday = true
                }
                
                self.view?.endEditing(true)
                
                guard let familyMember = self.familyMember else { return }
                var timeString = ""
                var certificate = familyMember.certificates.cnIdentityCard
                if titleItem.type == .chinaIdCardInfo {
                    certificate = familyMember.certificates.cnIdentityCard
                    
                } else if titleItem.type == .hkAndMacaoPassport {
                    certificate = familyMember.certificates.hkMacaoPass
                    
                } else if titleItem.type == .passPortOrTravelInfo {
                    certificate = familyMember.certificates.passport
                }
                
                if detailItem.type == .certificateSignDate { // 选择签发日期
                    timeString = certificate.issueDateStartAt

                } else if detailItem.type == .certificateValidDate { // 届满日期
                    timeString = certificate.issueDateEndAt
                }
                
                YHDatePickView.show(type: .yyyymmdd, title: title, lastIsTaday: lastIsTaday, currentDay: timeString) {
                    [weak self] dateStr  in
                    
                    print(dateStr)
                    guard let self = self else { return }
                    
                    
                    let format = DateFormatter()
                    format.dateFormat = "yyyy-MM-dd"
                    if let selectDate = format.date(from:dateStr) {
                        let selectTimeInterval = selectDate.timeIntervalSince1970
                        let currentTimeInterval = Date().timeIntervalSince1970
                        if detailItem.type == .certificateSignDate { // 选择签发日期
                            // 签发日期须早于当前日期
                            if selectTimeInterval > currentTimeInterval {
                                YHHUD.flash(message: "签发日期不能晚于当前日期")
                                return
                            }
                            if !certificate.issueDateEndAt.isEmpty, let endDate = format.date(from:certificate.issueDateEndAt)  {
                                let endTimeInterval = endDate.timeIntervalSince1970

                                if selectTimeInterval > endTimeInterval {
                                    YHHUD.flash(message: "签发日期不能晚于届满日期")
                                    return
                                }
                            }
                        }
                        
                        if detailItem.type == .certificateValidDate { // 届满日期
        
                            if !certificate.issueDateStartAt.isEmpty, let startDate = format.date(from:certificate.issueDateStartAt)  {
                                let startTimeInterval = startDate.timeIntervalSince1970

                                if selectTimeInterval < startTimeInterval {
                                    YHHUD.flash(message: "届满日期不能早于签发日期")
                                    return
                                }
                            }
                        }
                    }
                    
                    changeCertificateDate(certificate, type: detailItem.type, date: dateStr)
                    self.loadInfo()
                    save()
                }
            } else if detailItem.type == .certificateType { // 选择证件类别
                
                let type = self.familyMember?.certificates.passport.passPortType ?? 3
                YHSheetPickerView.show(type: .certificate, selectIndex:type) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.familyMember?.certificates.passport.passPortType = selectItem.index
                    self.loadInfo()
                    self.save()
                }
            }
            return
        }
    }
    
    func changeCertificateDate(_ certificate:YHCNIdentityCard?, type:YHFormDetailItemType, date:String?) {
        if type == .certificateSignDate {
            certificate?.issueDateStartAt = date ?? ""
            
        } else if type == .certificateValidDate {
            certificate?.issueDateEndAt = date ?? ""
        }
    }
        
    func createCorner(cell:UITableViewCell, arr:Array<Any>, indexPath:IndexPath) {
        // 复用时需清理
        cell.layer.mask = nil
        // 设置每块section圆角
        if (indexPath.row == 0) {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else if (indexPath.row == arr.count-1) {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
    
    func save() {
        if let delegate = delegate, delegate.responds(to: #selector(YHSpouseInfoVCProtocol.saveInfoSilent)) {
            delegate.saveInfoSilent()
        }
    }
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        guard let familyMember = familyMember else { return false}
        
        let isChinaCardMust = familyMember.isChinese() && familyMember.relationType != .child
        if isChinaCardMust {
            if familyMember.certificates.cnIdentityCard.number.count != 18
                || familyMember.certificates.cnIdentityCard.issueAt.count <= 0
                || familyMember.certificates.cnIdentityCard.issueDateStartAt.count <= 0
                || familyMember.certificates.cnIdentityCard.issueDateEndAt.count <= 0
            {
                return false
            }
        }
        
        // 如果选了办理过港澳通行证，则需要验证港澳通行证
        if familyMember.isNeedHandleHKPassPort() {
            
            if familyMember.certificates.hkMacaoPass.number.count <= 0
                || familyMember.certificates.hkMacaoPass.issueAt.count <= 0
                || familyMember.certificates.hkMacaoPass.issueDateStartAt.count <= 0
                || familyMember.certificates.hkMacaoPass.issueDateEndAt.count <= 0
            {
                return false
            }
        }
        
        // 是老外需验证护照
        if !familyMember.isChinese() {
            if familyMember.certificates.passport.number.count <= 0
                || familyMember.certificates.passport.issueAt.count <= 0
                || familyMember.certificates.passport.issueDateStartAt.count <= 0
                || familyMember.certificates.passport.issueDateEndAt.count <= 0
                || familyMember.certificates.passport.passPortType == 0
            {
                return false
            }
            
        }
        return true
    }
    
    func nextStep() -> Bool {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        loadInfo()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return false
        }
        return true
    }
}

