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

import UIKit

class YHChildPrimaryInfoVC: YHBaseViewController {

    var child:YHFamilyMember?
    weak var delegate:YHSpouseInfoVCProtocol?
    
    lazy var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.plain)

        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(YHFormItemQuestionsCell.self, forCellReuseIdentifier: YHFormItemQuestionsCell.cellReuseIdentifier)
        tableView.register(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "子女信息填写".local
        createUI()
        loadChildInfo()
    }
    
    func loadChildInfo() {
                        
        guard let child = child else { return }
        
        items.removeAll()

        // 随行
        let title0 = YHFormTitleItem(type: .accompany)
        let item00 = YHFormDetailItem(type: .ownCustody)
        item00.value = String(child.isOwnCustody())
        let item01 = YHFormDetailItem(type: .birthday)
        item01.value = child.birthday
        let item02 = YHFormDetailItem(type: .isAccompanyToHK)
        item02.value = String(child.isFollow())
        let arr0:[YHFormItemProtocol] = [title0, item00, item01, item02]
        items.append(arr0)
        
        if child.isFollow() { // 随行才加后面的信息
            // 国籍
            let title1 = YHFormTitleItem(type: .nationality)
            let item10 = YHFormDetailItem(type: .nationOrArea)
            item10.value = child.nationality
            item10.placeHolder = "请选择".local
            let arr1:[YHFormItemProtocol] = [title1, item10]
            
            // 居住信息
            var arr2 = [YHFormItemProtocol]()
            let title2 = YHFormTitleItem(type: .liveInfo)
            let item20 = YHFormDetailItem(type: .isLiveTother)
            item20.value = String(child.isLiveTother())
            arr2.append(title2)
            arr2.append(item20)
            
            if !child.isLiveTother() { // 不同住 才需填写国家/地区
                let item21 = YHFormDetailItem(type: .nationOrArea)
                item21.value = child.address?.country
                item21.placeHolder = "请选择".local
                arr2.append(item21)
                
                // 国家/地区已填写 才显示现居住城市和详细地址两行
                
                if let address = child.address {
                    if  let country = address.country, !country.isEmpty {
                        
                        // 居住信息中选择中国才会显示现居住城市
                        let isLiveInChina = country.contains("中国".local)
                        if isLiveInChina {
                            let item22 = YHFormDetailItem(type: .liveCity)
                            if let area = address.area {
                                item22.value = area.joined(separator: "/")
                            }
                            item22.placeHolder = "请选择城市".local
                            arr2.append(item22)
                        }
                        
                        let item23 = YHFormDetailItem(type: .detailAddress)
                        item23.value = address.details
                        item23.placeHolder = (isLiveInChina ? "请填写小区、楼栋、单元室等".local : "请填写国外居住地".local)
                        arr2.append(item23)
                        
                        if !isLiveInChina {// 在国外
                            // 是否在海外居住满1年及以上
                            let item24 = YHFormDetailItem(type: .isLiveOverSeasMore1Year)
                            item24.value = String(child.isOverSeasOver1Year())
                            arr2.append(item24)
                        }
                    }
                }
            }
            
            // 港澳通信证
            let title3 = YHFormTitleItem(type: .hkAndMacaoPassport)
            let item30 = YHFormDetailItem(type: .isHandleHKPassPort)
            item30.value = String(child.isNeedHandleHKPassPort())
            let arr3:[YHFormItemProtocol] = [title3, item30]
            items.append(contentsOf:[arr1, arr2, arr3])
        }

        tableView.reloadData()
    }
    
    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)
        }
    }
    
    func getCellType(_ item: Any) ->HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .birthCity {
                var isBirthOverSeas = false
                if let child = child {
                    isBirthOverSeas = child.isBirthOverSeas()
                }
                if isBirthOverSeas {
                    return .inputText
                } else {
                    return .selectSheet
                }
            }
            
            if detailItem.type == .detailAddress {
                return .inputText
            }
            
            if detailItem.type == .nationOrArea
                || detailItem.type == .nationOrArea
                || detailItem.type == .liveCity
                || detailItem.type == .birthday
            {
                return .selectSheet
            }
            if detailItem.type == .isAccompanyToHK 
                || detailItem.type == .isHandleHKPassPort
                || detailItem.type == .isLiveTother
                || detailItem.type == .isLiveOverSeasMore1Year
                || detailItem.type == .ownCustody
            {
                return .twoChoice
            }
        }
        return .defaultType
    }
}


extension YHChildPrimaryInfoVC : 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
            
        } else if item is YHFormDetailItem { // 具体信息
            
            let detailItem = item as! YHFormDetailItem
            let cellType = self.getCellType(detailItem)
            
            if cellType == .twoChoice {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.isShowBottomLine = indexPath.row != arr.count-1
                
                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
                    
                    let selectItem:YHFormChoiceItem = arr[selectIndex]
                    let option = (selectItem.title == "是".local ? true : false)

                    guard let self = self else { return }
                    if detailItem.type == .isAccompanyToHK { // 是否随行
                        
                        self.child?.setFollow(option)
                        if let delegate = self.delegate {
                            delegate.updateStepView?()
                        }
                        
                    } else if detailItem.type == .isHandleHKPassPort { // 是否办理港澳通行证
                        self.child?.setNeedHandleHKPassPort(option)
                        
                    } else if detailItem.type == .isLiveTother { // 是否与主申请人同住
                        self.child?.setLiveTother(option)
                        if option {
                            self.child?.address?.country = nil
                            self.child?.address?.details = nil
                            self.child?.address?.area = nil
                        }
                    } else if detailItem.type == .isLiveOverSeasMore1Year { // 是否在海外居住满1年及以上
                        self.child?.setOverSearsOver1Year(option)
                        
                    } else if detailItem.type == .ownCustody { // 抚养权
                        self.child?.setOwnCustody(option)
                    }
                    self.loadChildInfo()
                    if let delegate = delegate {
                        delegate.saveInfo?()
                    }
                }
                return cell
                
            } else if cellType == .selectSheet { // 选择列表面板
                
                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
                
            } else if cellType == .inputText { // 输入文字cell
                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 == .detailAddress {
                        self.child?.address?.details = text
                    }
                    
                    if isEditEnd {
                        self.loadChildInfo()
                        if let delegate = delegate {
                            delegate.saveInfo?()
                        }
                    }
                }
                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 {
            let detailItem = item as! YHFormDetailItem
            if detailItem.type == .isLiveTother ||
                detailItem.type == .isAccompanyToHK ||
                detailItem.type == .isHandleHKPassPort ||
                detailItem.type == .ownCustody ||
                detailItem.type == .isLiveOverSeasMore1Year
                
            {
                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 YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            // 选国籍/现居住城市/详细地址
            if detailItem.type == .nationOrArea {
               let vc = YHSelectCountryViewController()
                vc.backLocationStringController = {
                    [weak self] country in
                    guard let self = self else { return }
                    let title = arr[0] as! YHFormTitleItem
                    if title.type == .nationality {
                        self.child?.nationality = country

                    } else if title.type == .liveInfo {
                        self.child?.address?.country = country

                    }
                    self.loadChildInfo()
                }
                self.navigationController?.pushViewController(vc)
                
            } else if detailItem.type == .liveCity {
                
                let vc = YHAddressViewController()
                vc.backLocationStringController = {
                     [weak self] (string1, string2, string3, string4) in
                     guard let self = self else { return }
                     print("\(string1)\n\(string2)\n\(string3)\n\(string4)")
                     self.child?.address?.area = [string2, string3, string4]
                     self.loadChildInfo()
                 }
                self.present(vc, animated: true)

            } else if detailItem.type == .birthday  { // 出生日期
                YHDatePickView.show(type: .yyyymmdd) { [weak self] date in
                    guard let self = self else { return }
                    
                    if detailItem.type == .birthday {
                        self.child?.birthday = date
                    }
                    self.loadChildInfo()
                }
            }
        }
    }
        
    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
        }
    }
}



