//
//  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 {

    var familyMember:YHFamilyMember?
    weak var delegate:YHSpouseInfoVCProtocol?

    var certificates:YHCertificates = YHCertificates()
        
    var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    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 = .clear
        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_navTitle = "证件信息填写".local
        createUI()
        loadCertificateInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        let topHeight = k_Height_NavigationtBarAndStatuBar+YHStepView.height
        let bottomHeight = k_Height_safeAreaInsetsBottom() + YHSaveAndSubmitView.height
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(topHeight)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-bottomHeight)
        }
        
        guard let familyMember = familyMember else { return }
        
        if let cer = familyMember.certificates {
            certificates = cer
        } else {
            certificates.cnIdentityCard = YHCNIdentityCard()
            certificates.passport = YHCNIdentityCard()
            if familyMember.isHandled == 1 { // 要办理港澳通行证
                certificates.hkMacaoPass = YHCNIdentityCard()
            }
        }
        loadCertificateInfo()
    }
    
    func loadCertificateInfo() {
    
        guard let familyMember = familyMember else { return }
        items.removeAll()
        
        // 中国身份证 信息必有
        let title0 = YHFormTitleItem(type: .chinaIdCardInfo)
        let item01 = YHFormDetailItem(type: .chinaIdentityCardNumber)
        let item02 = YHFormDetailItem(type: .certificateSignPlace)
        let item03 = YHFormDetailItem(type: .certificateSignDate)
        let item04 = YHFormDetailItem(type: .certificateValidDate)
        let arr0:[YHFormItemProtocol] = [title0, item01, item02, item03, item04]
        items.append(arr0)
        if  let cnIdentityCard = certificates.cnIdentityCard {
            item01.value = cnIdentityCard.number
            item02.value = cnIdentityCard.issueAt
            item03.value = cnIdentityCard.issueDateStartAt
            item04.value = cnIdentityCard.issueDateEndAt
        }
            
        // 港澳通行证 非必须
        if certificates.hkMacaoPass != nil {
            let title1 = YHFormTitleItem(type: .hkAndMacaoPassport)
            let item10 = YHFormDetailItem(type: .traverlPassportNumber)
            let item11 = YHFormDetailItem(type: .certificateSignPlace)
            let item12 = YHFormDetailItem(type: .certificateSignDate)
            let item13 = YHFormDetailItem(type: .certificateValidDate)
            let arr1:[YHFormItemProtocol] = [title1, item10, item11, item12, item13]
            items.append(arr1)
            if  let hkMacaoPass = certificates.hkMacaoPass {
                item10.value = hkMacaoPass.number
                item11.value = hkMacaoPass.issueAt
                item12.value = hkMacaoPass.issueDateStartAt
                item13.value = hkMacaoPass.issueDateEndAt
            }
        }
        
        // 护照及其他旅行证件 信息必有
        let title2 = YHFormTitleItem(type: .passPortOrTravelInfo)
        let item20 = YHFormDetailItem(type: .certificateType, isNeed: false)
        let item21 = YHFormDetailItem(type: .certificateNumber, isNeed: false)
        let item22 = YHFormDetailItem(type: .certificateSignPlace, isNeed: false)
        let item23 = YHFormDetailItem(type: .certificateSignDate, isNeed: false)
        let item24 = YHFormDetailItem(type: .certificateValidDate, isNeed: false)
        let arr2:[YHFormItemProtocol] = [title2, item20, item21, item22, item23, item24]
        items.append(arr2)
        if  let passport = certificates.passport {
            item20.value = String(passport.passportType)
            item21.value = passport.number
            item22.value = passport.issueAt
            item23.value = passport.issueDateStartAt
            item24.value = passport.issueDateEndAt
        }
        
        // 证件类别名称
        var selectType:YHFormPickerViewSubType = .certificate(.passport)
        if let passPortType = self.familyMember?.certificates?.passport?.passportType,
           let subType = YHPickerViewCertificateType(rawValue: passPortType)
        {
            selectType = YHFormPickerViewSubType.certificate(subType)
        }
        item20.value = selectType.title
        
        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 cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.titleLabel.text = item.getTitle()
            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
                cell.isShowBottomLine = indexPath.row != arr.count-1
                
                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.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.isShowBottomLine = indexPath.row != arr.count-1
                return cell
            }
            
            if detailItem.type == .certificateValidDate {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemExpireDateCell.cellReuseIdentifier, for: indexPath) as! YHFormItemExpireDateCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                cell.isShowBottomLine = indexPath.row != arr.count-1
                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 {
        
        if indexPath.section >= items.count { return 0.0 }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return 0.0 }
        
        let item = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 标题
            return 52.0
        }
        
        if item is YHFormDetailItem {
            return UITableView.automaticDimension
        }
        return 52.0
    }
    
    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 title = arr[0] as! YHFormTitleItem
            if detailItem.type == .certificateValidDate ||
               detailItem.type == .certificateSignDate { // 届满日期 签发日期
     
                self.view?.endEditing(true)
                YHDatePickView.show(type: .yyyymmdd) { [weak self] date  in
                    let dataArr = date.components(separatedBy: YHDatePickView.separator)
                    print(dataArr)
                    guard let self = self else { return }
                    guard let familyMember = self.familyMember else { return }
                    
                    var certificate = familyMember.certificates?.cnIdentityCard
                    if title.type == .chinaIdCardInfo {
                        certificate = familyMember.certificates?.cnIdentityCard
                        
                    } else if title.type == .hkAndMacaoPassport {
                        certificate = familyMember.certificates?.hkMacaoPass
                        
                    } else if title.type == .passPortOrTravelInfo {
                        certificate = familyMember.certificates?.passport
                    }
                    changeCertificateDate(certificate, type: detailItem.type, date: date)
                    self.loadCertificateInfo()
                    save()
                }
            } else if detailItem.type == .certificateType { // 选择证件类别
                
                var selectType:YHFormPickerViewSubType = .certificate(.passport)
                if let passPortType = self.familyMember?.certificates?.passport?.passportType,
                   let subType = YHPickerViewCertificateType(rawValue: passPortType)
                {
                    selectType = YHFormPickerViewSubType.certificate(subType)
                }
                
                YHFormPickerView.show(type: .certificate, selectType:selectType) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    self.familyMember?.certificates?.passport?.passportType = selectType.index
                    self.loadCertificateInfo()
                    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.saveInfo?()
        }
    }
}

