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

import UIKit
import SmartCodable
import SwifterSwift

class YHSpousePrimaryInfoVC: YHBaseViewController, YHFamilyMemberProtol {
    
    var spouse: YHFamilyMember?
    var mainApplicantInfo: YHMyMainApplicantInfoModel?

    weak var delegate: YHSpouseInfoVCProtocol?
    var isNeedShowError = false
    lazy var items: [[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 52.0
        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(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        tableView.register(YHFormItemTitleCell.self, forCellReuseIdentifier: YHFormItemTitleCell.cellReuseIdentifier)
        tableView.register(YHFormItemAddCell.self, forCellReuseIdentifier: YHFormItemAddCell.cellReuseIdentifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor(hexString: "#F8F8F8")
        createUI()
        loadInfo()
    }
    
    func loadInfo() {
                        
        guard let spouse = spouse else { return }
        
        items.removeAll()

        let title0 = YHFormTitleItem(type: .E)
        let item0 = YHFormDetailItem(type: .isAccompanyToHK)
        item0.value = String(spouse.isFollow())
        let arr0: [YHFormItemProtocol] = [title0, item0]
        items.append(arr0)
        
        if spouse.isFollow() {
            let title1 = YHFormTitleItem(type: .F)
            let item10 = YHFormDetailItem(type: .nationOrArea, value: spouse.nationality, placeHolder: "请选择".local, tips: "请选择国籍".local)
            let arr1: [YHFormItemProtocol] = [title1, item10]
            
            var arr2 = [YHFormItemProtocol]()
            let title2 = YHFormTitleItem(type: .G)
            let item20 = YHFormDetailItem(type: .isLiveTother, value: String(spouse.isLiveTother()))
            arr2.append(title2)
            arr2.append(item20)
            
            if !spouse.isLiveTother() {
                let item21 = YHFormDetailItem(type: .nationOrArea, value: spouse.address.country, placeHolder: "请选择".local, tips: "请选择国家/地区".local)
                arr2.append(item21)
                
                if !spouse.address.country.isEmpty {
                    
                    let isLiveInChina = spouse.address.country.contains("中国".local)
                    if isLiveInChina {
                        var value: String? = ""
                        if !spouse.address.area.isEmpty {
                            value = spouse.address.area.joined(separator: ",")
                        }
                        let item22 = YHFormDetailItem(type: .liveCity, value: value, tips: "请选择省市地区".local)
                        arr2.append(item22)
                    }
                    
                    let placeHolder = (isLiveInChina ? "请填写小区、楼栋、单元室等".local : "请填写国外居住地".local)
                    let tips = (isLiveInChina ? "请填写小区、楼栋、单元室等".local : "请填写国外居住地".local)
                    let detailAddress = isLiveInChina ? spouse.address.details : spouse.address.foreign
                    let item23 = YHFormDetailItem(type: .detailAddress, value: detailAddress, placeHolder: placeHolder, tips: tips)
                    arr2.append(item23)
                    
                    if !isLiveInChina {
                        let item24 = YHFormDetailItem(type: .isLiveOverSeasMore1Year)
                        item24.value = String(spouse.isOverSeasOver1Year())
                        arr2.append(item24)
                    }
                }
            }
            
            items.append(contentsOf: [arr1, arr2])

            var isHiddenHK = true
            let nationality = spouse.nationality
            var liveCountry = spouse.address.country
            var isLiveOverseaYear = spouse.isOverSeasOver1Year()
            
            if spouse.isLiveTother(), let mainApplicantInfo = mainApplicantInfo {
                liveCountry = mainApplicantInfo.applicant_address.country
                isLiveOverseaYear = mainApplicantInfo.isOverSeasOver1Year()

            }
            
            if nationality.contains("中国") {
                let isLiveInChina = liveCountry.contains("中国".local)
                if isLiveInChina || (!isLiveInChina && !isLiveOverseaYear) {
                    isHiddenHK = false
                }
            }
            
            if !isHiddenHK {
                let title3 = YHFormTitleItem(type: .hkAndMacaoPassport)
                let item30 = YHFormDetailItem(type: .isHandleHKPassPort)
                item30.value = String(spouse.isNeedHandleHKPassPort())
                let arr3: [YHFormItemProtocol] = [title3, item30]
                items.append(arr3)
            }
        }

        tableView.reloadData()
    }
    
    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)
        }
    }
}

extension YHSpousePrimaryInfoVC: 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 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as? YHFormItemTitleCell else { return UITableViewCell() }
            cell.setTitleAndSubTitle(title: item.getTitle())
            return cell
            
        } else if item is YHFormDetailItem {
            
            guard let detailItem = item as? YHFormDetailItem else { return UITableViewCell() }
            
            if detailItem.type == .isAccompanyToHK || detailItem.type == .isHandleHKPassPort || detailItem.type == .isLiveTother || detailItem.type == .isLiveOverSeasMore1Year {
                
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as? YHFormItemDoubleChoiceCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
    
                var select = false
                if let value = detailItem.value {
                   select = Bool(value)!
                }
                let answers = [YHFormChoiceItem(title: "是".local, isSelect: select), YHFormChoiceItem(title: "否".local, isSelect: !select)]
                cell.answerArr = answers
                            
                cell.answerBlock = {
                    
                    [weak self]  (arr, selectIndex) in
                    
                    guard let self = self else { return }
                    
                    let selectItem: YHFormChoiceItem = arr[selectIndex]
                    let option = (selectItem.title == "是".local ? true : false)
                    if detailItem.type == .isAccompanyToHK {
                        
                        self.spouse?.setFollow(option)
                        self.loadInfo()
                        if let delegate = delegate, delegate.responds(to: #selector(YHSpouseInfoVCProtocol.updateStepView)) {
                            delegate.updateStepView()
                        }
                        
                    } else if detailItem.type == .isHandleHKPassPort {
                        self.spouse?.setNeedHandleHKPassPort(option)
                        self.loadInfo()
                        
                    } else if detailItem.type == .isLiveTother {
                        self.spouse?.setLiveTother(option)
                        if option {
                            self.spouse?.address.clearAddress()
                        }
                        self.loadInfo()
                        
                    } else if detailItem.type == .isLiveOverSeasMore1Year {
                        self.spouse?.setOverSearsOver1Year(option)
                        self.loadInfo()
                    }
                    save()
                }
                return cell
            }
                        
            if detailItem.type == .nationOrArea || detailItem.type == .liveCity {
                
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as? YHFormItemSelectSheetCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.placeHolder = detailItem.placeHolder
                cell.detail = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                return cell
            }
            
            if detailItem.type == .detailAddress {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as? YHFormItemInputTextCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                cell.placeHolder = detailItem.placeHolder
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                cell.textInputCondtion = {
                    textField in
                    if let textStr = textField.text {
                        let max = 100
                        textField.text = textStr.count > max ? textStr[safe: ..<max] : textStr
                    }
                    return true
                }
                cell.textChange = {
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    guard let spouse = spouse else { return }
                    
                    if detailItem.type == .detailAddress {
                        
                        if spouse.isLiveInChina() {
                            spouse.address.details = text ?? ""
                        } else {
                            spouse.address.foreign = text ?? ""
                        }
                    }
                    if isEditEnd {
                        self.loadInfo()
                        save()
                    }
                }
                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, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if section == items.count-1 {
            return 14.0
        }
        return 1.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 YHFormDetailItem {
            guard let detailItem = item as? YHFormDetailItem else { return }
            if detailItem.type == .nationOrArea {
               let vc = YHSelectCountryViewController()
                vc.backLocationStringController = {
                    [weak self] country in
                    guard let self = self else { return }
                    guard let title = arr[0] as? YHFormTitleItem else { return }
                    if title.type == .F {
                        self.spouse?.nationality = country

                    } else if title.type == .G {
                        self.spouse?.address.country = country
                        self.spouse?.address.area = []

                    }
                    self.loadInfo()
                    save()
                }
                self.navigationController?.pushViewController(vc)
                
            } else if detailItem.type == .liveCity {
                
                var provice = ""
                if let country = self.spouse?.address.country {
                    if country.contains("台湾") {
                        provice = "台湾省"
                    }
                    if country.contains("香港") {
                        provice = "香港特别行政区"
                    }
                    if country.contains("澳门") {
                        provice = "澳门特别行政区"
                    }
                }
                
                let addressPicker = YHAddressViewController(selectProvince: provice)
                addressPicker.backLocationStringController = { 
                    [weak self] (address, province, city, area) in
                    guard let self = self else { return }
                    print("\(address)\n\(province)\n\(city)\n\(area)")
                    var citys: [String] = []
                    if !isEmptyString(province) {
                        citys.append(province)
                    }
                    if !isEmptyString(city) {
                       citys.append(city)
                    }
                    self.spouse?.address.area = citys
                    self.loadInfo()
                    save()
                }
                UIViewController.current?.present(addressPicker, animated: true, completion: nil)

            } 
        }
    }
        
    func createCorner(cell: UITableViewCell, arr: [Any], indexPath: IndexPath) {
        cell.layer.mask = nil
        if indexPath.row == 0 {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else if indexPath.row == arr.count-1 {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
    
    func checkIntegrity() -> Bool {
       
        guard let spouse = spouse else { return false}
        if !spouse.isFollow() {
            return true
        }
        
        if isEmptyString(spouse.nationality) {
            return false
        }
        
        if !spouse.isLiveTother() {
            if isEmptyString(spouse.address.country) {
                return false
            }
            if spouse.isLiveInChina() {
                if isEmptyArray(spouse.address.area) {
                    return false
                }
                if isEmptyString(spouse.address.details) {
                    return false
                }
            } else { 
                if isEmptyString(spouse.address.foreign) {
                    return false
                }
            }
        }
        return true
    }
    
    func nextStep() -> Bool {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        loadInfo()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return false
        }
        return true
    }
    
    func save() {
        if let delegate = delegate, delegate.responds(to: #selector(YHSpouseInfoVCProtocol.saveInfoSilent)) {
            delegate.saveInfoSilent()
        }
    }

}
