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

import UIKit

class YHParentInfoVC: YHBaseViewController {
    
    var parentInfo: YHFamilyMember?
    
    var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.plain)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        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(YHFormItemOnlyDoubleChoiceCell.self, forCellReuseIdentifier: YHFormItemOnlyDoubleChoiceCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "父母信息填写".local
        createUI()
        loadBasicInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview().offset(-100)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        loadBasicInfo()

    }
    
    func loadBasicInfo() {
        
        guard let parentInfo = parentInfo else { return }

        items.removeAll()
        
        // 基本信息
        let title0:YHFormItemProtocol = YHFormTitleItem(type: .basicInfo)
        let item00:YHFormItemProtocol = YHFormDetailItem(type: .onlyDoubleChoice)
        let arr0:[YHFormItemProtocol] = [title0, item00]


        // 父母亲信息
        var arr1 = [YHFormItemProtocol]()
        if parentInfo.relationType == .father { // 父亲
            let title1:YHFormItemProtocol = YHFormTitleItem(type: .fatherInfo)
            let item10:YHFormItemProtocol = YHFormDetailItem(type: .fatherName)
            arr1.append(contentsOf: [title1, item10])
        } else { // 母亲
            let title1:YHFormItemProtocol = YHFormTitleItem(type: .motherInfo)
            let item10:YHFormItemProtocol = YHFormDetailItem(type: .motherName)
            arr1.append(contentsOf: [title1, item10])
        }
        
        let item11:YHFormItemProtocol = YHFormDetailItem(type: .birthday)
        let item12:YHFormItemProtocol = YHFormDetailItem(type: .birthNation)
        let item13:YHFormItemProtocol = YHFormDetailItem(type: .birthCity)
        arr1.append(contentsOf: [item11, item12, item13])
        
        if parentInfo.deceased != 1 { // 健在
            let item14:YHFormItemProtocol = YHFormDetailItem(type: .marriageState)
            arr1.append(item14)
        }
        
        // 职业信息
        let title2:YHFormItemProtocol = YHFormTitleItem(type: .occupationInfo)
        let item20:YHFormItemProtocol = YHFormDetailItem(type: .occupation)
        let arr2:[YHFormItemProtocol] = [title2, item20]
        
        // 居住信息
        let title3:YHFormItemProtocol = YHFormTitleItem(type: .liveInfo)
        let item30:YHFormItemProtocol = YHFormDetailItem(type: .liveNationOrArea)
        let arr3:[YHFormItemProtocol] = [title3, item30]
        
        // 香港身份证
        let title4:YHFormItemProtocol = YHFormTitleItem(type: .hkIdentityCardInfo)
        let item40:YHFormItemProtocol = YHFormDetailItem(type: .isHaveHkIdentityCard)
        let item41:YHFormItemProtocol = YHFormDetailItem(type: .hkIdentityCardNumber)
        let arr4:[YHFormItemProtocol] = [title4, item40, item41]
        
        items.append(contentsOf: [arr0, arr1, arr2, arr3, arr4])
        tableView.reloadData()
    
    }
    
    func getCellType(_ item: Any) ->HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            if detailItem.type == .fatherName
               || detailItem.type == .motherName
               || detailItem.type == .nationOrArea
               || detailItem.type == .hkIdentityCardNumber
            {
                return .inputText
            }
            if detailItem.type == .birthday
                || detailItem.type == .birthCity
                || detailItem.type == .marriageState
                || detailItem.type == .occupation
                || detailItem.type == .liveNationOrArea
            {
                return .selectSheet
            }
            if detailItem.type == .birthNation
                || detailItem.type == .isHaveHkIdentityCard
            {
                return .twoChoice
            }
            if detailItem.type == .onlyDoubleChoice
            {
                return .onlyTwoChoice
            }
        }
        return .defaultType
    }
    
}

extension YHParentInfoVC : 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]
        
        let cellType = getCellType(item)
        
        if cellType == .title { // 标题
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.titleLabel.text = item.getTitle()
            return cell
        }
        
        if cellType == .inputText { // 输入文字cell
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as! YHFormItemInputTextCell
            cell.titleLabel.text = item.getTitle()
            return cell
        }
        
        if cellType == .selectSheet { // 点击选择列表cell
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
            cell.title = item.getTitle()
            return cell
        }
        
        if cellType == .twoChoice { // 问答双项选择cell
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
            cell.title = item.getTitle()
            cell.answerArr = nil
            
            if item is YHFormDetailItem {
                let detailItem = item as! YHFormDetailItem
                if detailItem.type == .birthNation {
                    let answers = [YHFormChoiceItem(title: "国内".local, isSelect: true),
                                   YHFormChoiceItem(title: "国外".local, isSelect: false)]
                    cell.answerArr = answers
                } else if detailItem.type == .isHaveHkIdentityCard {
                    
                    let answers = [YHFormChoiceItem(title: "是".local, isSelect: true),
                                   YHFormChoiceItem(title: "否".local, isSelect: false)]
                    cell.answerArr = answers
                }
            }
            
            return cell
        }
        
        if cellType == .onlyTwoChoice { // 仅有双项选择cell
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemOnlyDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemOnlyDoubleChoiceCell
            
            var isDead = 0
            if let dead = parentInfo?.deceased, dead == 1 { // 已故
                isDead = 1
            }
            let answers = [YHFormChoiceItem(title: "健在".local, isSelect: isDead != 1),
                           YHFormChoiceItem(title: "已故".local, isSelect: isDead == 1)]
            cell.answerArr = answers
            cell.answerBlock = { [weak self]
                (arr, selectIndex) in
                let selectItem:YHFormChoiceItem = arr[selectIndex]
                self?.parentInfo?.deceased = (selectItem.title == "已故" ? 1 : 0)
                self?.loadBasicInfo()
            }
            return cell
        }
        
        if cellType == .addItem { // 新增item cell
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemAddCell.cellReuseIdentifier, for: indexPath) as! YHFormItemAddCell
            cell.title = item.getTitle()
            return cell
        }
        
        if cellType == .degreeDetailInfo { // 学位cell
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDegreeInfoCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDegreeInfoCell
            cell.title = item.getTitle()
            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 YHFormAddItem {
            return 70.0
        }
        
        if item is YHFormDetailItem {
            return UITableView.automaticDimension
        }
        return 52.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
        
    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
        }
    }
}
