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

import UIKit

class YHBrotherInfoVC: YHBaseViewController {
    
    var brotherInfo: YHFamilyMember?
    var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    let familyRequest:YHFamilyRequestViewModel = YHFamilyRequestViewModel()

    
    var bottomView: YHSaveAndSubmitView = {
        let view = YHSaveAndSubmitView.createView()
        view.isHiddenSubmit = true
        return view
    }()
    
    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);
        view.addSubview(bottomView)
        
        bottomView.saveBlock = {
            [weak self] in
            guard let self = self else { return }
            self.saveInfo()
            
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-k_Height_safeAreaInsetsBottom())
            make.height.equalTo(YHSaveAndSubmitView.height)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        loadBasicInfo()
    }
    
    func loadBasicInfo() {
        
        guard let brotherInfo = brotherInfo else { return }

        items.removeAll()
        

        // 兄弟姐妹信息
        let title1 = YHFormTitleItem(type: .brotherInfo)
        let item10 = YHFormDetailItem(type: .brotherName)
        item10.value = brotherInfo.subsetName
        let item11 = YHFormDetailItem(type: .birthday)
        item11.value = brotherInfo.birthday
        let item12 = YHFormDetailItem(type: .birthNation)
        item12.value = String(brotherInfo.isBirthOverSeas())
        
        let item13 = YHFormDetailItem(type: .birthCity)
        
        if brotherInfo.isBirthOverSeas() {
            item13.value = brotherInfo.birthPlace?.foreign
            item13.placeHolder = "请输入".local
        } else {
            item13.value = brotherInfo.birthPlace?.area?.joined(separator: ",")
            item13.placeHolder = "请选择".local
        }

        let item14 = YHFormDetailItem(type: .gender)
        item14.value = brotherInfo.sexName()
        
        let item15 = YHFormDetailItem(type: .marriageState)
        item15.value = brotherInfo.married
        
        let arr1:[YHFormItemProtocol] = [title1, item10, item11, item12, item13, item14, item15]

        
        // 职业信息
        let title2 = YHFormTitleItem(type: .occupationInfo)
        let item20 = YHFormDetailItem(type: .occupation)
        item20.value = brotherInfo.occupation
        item20.placeHolder = "请输入".local
        var arr2:[YHFormItemProtocol] = [title2, item20]
    
        
        // 居住信息
        let title3 = YHFormTitleItem(type: .liveInfo)
        let item30 = YHFormDetailItem(type: .liveNationOrArea)
        item30.value = brotherInfo.liveCountry
        let arr3:[YHFormItemProtocol] = [title3, item30]
        
        // 香港身份证
        let title4 = YHFormTitleItem(type: .hkIdentityCardInfo)
        let item40 = YHFormDetailItem(type: .isHaveHkIdentityCard)
        item40.value = String(brotherInfo.isHaveHKIdentityCard())
        var arr4:[YHFormItemProtocol] = [title4, item40]

        if brotherInfo.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            let item41 = YHFormDetailItem(type: .hkIdentityCardNumber)
            item41.value = brotherInfo.hkIdentityCard
            arr4.append(item41)
        }
        items.append(contentsOf: [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 == .birthCity {
                var isBirthOverSeas = false
                if let brotherInfo = brotherInfo {
                    isBirthOverSeas = brotherInfo.isBirthOverSeas()
                }
                if isBirthOverSeas {
                    return .inputText
                } else {
                    return .selectSheet
                }
            }
            
            if detailItem.type == .brotherName
                || detailItem.type == .occupationName
                || detailItem.type == .hkIdentityCardNumber
            {
                return .inputText
            }
            
            if detailItem.type == .birthday
                || detailItem.type == .marriageState
                || detailItem.type == .occupation
                || detailItem.type == .liveNationOrArea
                || detailItem.type == .gender
            {
                return .selectSheet
            }
            if detailItem.type == .birthNation || detailItem.type == .isHaveHkIdentityCard
            {
                return .twoChoice
            }
        }
        return .defaultType
    }
    
}

extension YHBrotherInfoVC : 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.setTitleAndSubTitle(title:item.getTitle())
            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 item is YHFormDetailItem {
            
            let detailItem = item as! YHFormDetailItem
            
            if cellType == .inputText { // 输入文字cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as! YHFormItemInputTextCell
                cell.isMust = detailItem.isNeed
                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 == .brotherName {
                        self.brotherInfo?.subsetName = text
    
                    } else if detailItem.type == .birthCity {
                        self.brotherInfo?.birthPlace?.foreign = text
                        
                    } else if detailItem.type == .occupationName {
                        self.brotherInfo?.occupationName = text
                        
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.brotherInfo?.hkIdentityCard = text
                    }
                    
                    if isEditEnd {
                        self.loadBasicInfo()
                        self.saveInfo()
                    }
                }
                return cell
            }
            
            if cellType == .selectSheet { // 点击选择列表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.isShowBottomLine = indexPath.row != arr.count-1
                return cell
            }
            
            if cellType == .twoChoice { // 问答双项选择cell
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
                cell.isMust = detailItem.isNeed
                cell.title = item.getTitle()
                cell.isShowBottomLine = indexPath.row != arr.count-1
                cell.answerArr = nil
                
                if detailItem.type == .birthNation { // 出生国家
                    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] (answers, index) in
                        guard let self = self else { return }
                         let selectItem = answers[index]
                        self.brotherInfo?.setBirthOverSeas(selectItem.title == "国外".local)
                        self.loadBasicInfo()
                        self.saveInfo()
                    }
                } else if detailItem.type == .isHaveHkIdentityCard { // 是否办理过香港身份证
                    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] (answers, index) in
                        guard let self = self else { return }
                         let selectItem = answers[index]
                         if detailItem.type == .isHaveHkIdentityCard {
                            self.brotherInfo?.setHaveHKIdentityCard(selectItem.title == "是".local)
                        }
                        self.loadBasicInfo()
                        self.saveInfo()
                    }
                }
                
                return cell
            }
            
            if cellType == .onlyTwoChoice { // 仅有双项选择cell
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemOnlyDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemOnlyDoubleChoiceCell
                
                var isDead = false
                if let brotherInfo = brotherInfo, brotherInfo.isDead() { // 已故
                    isDead = true
                }
                let answers = [YHFormChoiceItem(title: "健在".local, isSelect: !isDead),
                               YHFormChoiceItem(title: "已故".local, isSelect: isDead)]
                cell.answerArr = answers
                cell.answerBlock = { [weak self]
                    (arr, selectIndex) in
                    let selectItem:YHFormChoiceItem = arr[selectIndex]
                    self?.brotherInfo?.setIsDead(selectItem.title == "已故".local)
                    self?.loadBasicInfo()
                    self?.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 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) {

        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 == .birthday { // 出生日期
                YHDatePickView.show(type: .yyyymmdd) { [weak self] date in
                    guard let self = self else { return }
                    
                    if detailItem.type == .birthday {
                        self.brotherInfo?.birthday = date
                    }
                    self.loadBasicInfo()
                    self.saveInfo()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                var isBirthOverSeas = false
                if let brotherInfo = brotherInfo {
                    isBirthOverSeas = brotherInfo.isOverSeasOver1Year()
                }
                // 出生国外时 出生城市是输入框
                if isBirthOverSeas { return }
                
                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.brotherInfo?.birthPlace?.area = [string2, string3, string4]
                     self.loadBasicInfo()
                    self.saveInfo()
                 }
                self.present(vc, animated: true)
 
            } else if detailItem.type == .occupation { // 职业
                let occupation = self.brotherInfo?.occupation ?? ""
                YHFormPickerView.show(type: .profession, selectTitle:occupation ) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    self.brotherInfo?.occupation = selectType.title
                    self.loadBasicInfo()
                    self.saveInfo()
                }
                
            } else if detailItem.type == .marriageState { // 婚姻
                let marriage = self.brotherInfo?.married
                YHFormPickerView.show(type: .marriage, selectTitle:marriage) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    self.brotherInfo?.married = selectType.title
                    self.loadBasicInfo()
                    self.saveInfo()
                }
            } else if detailItem.type == .liveNationOrArea { // 现居住国家/地区
                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.brotherInfo?.liveCountry = string2
                     self.loadBasicInfo()
                     self.saveInfo()
                 }
                self.present(vc, animated: true)
            } else if detailItem.type == .gender { // 性别
                guard let brotherInfo = brotherInfo else { return }
                let isMale = brotherInfo.isMale()
                let selectType:YHFormPickerViewSubType = isMale ? .gender(.male) : .gender(.female)
                YHFormPickerView.show(type: .gender, selectType:selectType) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    let selectMale = (selectType.index == YHFormPickerViewSubType.gender(.male).index)
                    self.brotherInfo?.setMale(selectMale)
                    self.loadBasicInfo()
                    self.saveInfo()
                }
            }
        }
    }
        
    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
        }
    }
}

extension YHBrotherInfoVC {
    
    func saveInfo() {
        
        guard let brotherInfo = brotherInfo else { return }
        guard let info = brotherInfo.toDictionary() else { return }
        
        let dict:[String: Any] = ["orderId":brotherInfo.orderId,
                                  "relation":brotherInfo.relationType.rawValue,
                                  "step":brotherInfo.step,
                                  "next":false,
                                  "info":info]
        
        self.familyRequest.addOrSaveFamilyMember(params:dict) { success, error in
            if success {
                
            }
        }
    }
}

