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

import UIKit

enum YHFormTitleItemEditType:Int {
    case none = 1
    case canEdit = 2
    case canCancel = 3
}

class YHFamilyMemberFormVC: YHBaseViewController {

    let familyRequest:YHFamilyRequest = YHFamilyRequest()
    var familyMemberInfo: YHFamilyMemberGroupInfo?
    var isChildsEditMode: YHFormTitleItemEditType = .none
    var isBrothersEditMode: YHFormTitleItemEditType = .none
    
    var items:[[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)
        return tableView
    }()
    
    lazy var submitBtn:UIButton = {
        
        let btn = UIButton()
        btn.setTitle("提交".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor(hexString:"#4388FF")
        btn.layer.cornerRadius = 8.0
        btn.addTarget(self, action: #selector(didClickSubmitBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var bottomView:UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(submitBtn)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "家庭成员信息填写".local
        view.backgroundColor = UIColor(hexString:"#F8F8F8")
        createUI()
        loadData()
        
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        view.addSubview(bottomView)
        
        let submitBtnHeight = 48.0
        let gap = 8.0
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view)
            make.height.equalTo(submitBtnHeight+gap*2+k_Height_safeAreaInsetsBottom())
        }
        submitBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48)
            make.top.equalTo(8)
        }
        
        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)
        }
    }
    
    @objc func didClickSubmitBtn() {
        
    }
    
    func loadData() {
        
        self.familyRequest.getFamilyInfo(params: ["orderId": 133971]) { success, error in
            
        }
        
        let dic = [
            "father": [
                "id": 0,
                "deceased": 0,
                "custody": 100,
                "nationality": "",
                "order_id": 0,
                "relation": 0,
                "has_degree": 0,
                "has_degree_json": [],
                "follow": 0,
                "statement": 0,
                "subset_name": "",
                "subset_name_pinyin": "",
                "used_name": "",
                "birthday": "",
                "birth_place_aboard": 0,
                "birth_place": [],
                "occupation": "",
                "occupation_name": "",
                "operator_ame": "",
                "child_has_hk_id": [],
                "hk_identity_card": "",
                "sex": 0,
                "married": 0,
                "nows": 0,
                "address": [
                    "area": ["广东省", "深圳市"],
                    "country": "中国-China",
                    "details": "大新地铁站",
                    "foreign": ""
                ],
                "child_stepchild": [],
                "child_in_hk": [],
                "country_identity": [],
                "hk_identity": "",
                "hk_identity_other": "",
                "live_country": "",
                "is_handled": 0,
                "finish_follow": 0,
                "step": 0,
                "not_fill_num": 7,
                "certificates": [],
                "is_live_oversea_year": 0
            ],
            "mother": [
                "id": 0,
                "deceased": 0,
                "custody": 100,
                "nationality": "",
                "order_id": 0,
                "relation": 0,
                "has_degree": 0,
                "has_degree_json": [],
                "follow": 0,
                "statement": 0,
                "subset_name": "",
                "subset_name_pinyin": "",
                "used_name": "",
                "birthday": "",
                "birth_place_aboard": 0,
                "birth_place": [],
                "occupation": "",
                "occupation_name": "",
                "operator_ame": "",
                "child_has_hk_id": [],
                "hk_identity_card": "",
                "sex": 0,
                "married": 0,
                "nows": 0,
                "address": [
                    "area": ["广东省", "深圳市"],
                    "country": "中国-China",
                    "details": "大新地铁站",
                    "foreign": ""
                ],
                "child_stepchild": [],
                "child_in_hk": [],
                "country_identity": [],
                "hk_identity": "",
                "hk_identity_other": "",
                "live_country": "",
                "is_handled": 0,
                "finish_follow": 0,
                "step": 0,
                "not_fill_num": 5,
                "certificates": [],
                "is_live_oversea_year": 0
            ],
            "spouse": [
                "id": 68416,
                "deceased": 0,
                "custody": 100,
                "nationality": "中国-China",
                "order_id": 133971,
                "relation": "3",
                "has_degree": "1",
                "has_degree_json": [[
                    "degree": "1",
                    "address": "1"
                ]],
                "follow": 1,
                "statement": 0,
                "subset_name": "林源芳",
                "subset_name_pinyin": [
                    "family_name": "LIN",
                    "given_name": "YUANFANG"
                ],
                "used_name": "",
                "birthday": "2012-01-01",
                "birth_place_aboard": 0,
                "birth_place": [
                    "area": ["广东省", "深圳市"],
                    "country": "",
                    "details": "",
                    "foreign": ""
                ],
                "occupation": "在职",
                "occupation_name": "工程师",
                "operator_ame": "",
                "child_has_hk_id": [
                    "has": "N"
                ],
                "hk_identity_card": "",
                "sex": 2,
                "married": "未婚",
                "nows": 0,
                "address": [
                    "area": ["广东省", "深圳市"],
                    "country": "",
                    "details": "大新地铁站",
                    "foreign": ""
                ],
                "child_stepchild": [
                    "has": "",
                    "info": ""
                ],
                "child_in_hk": [
                    "has": "N"
                ],
                "country_identity": [],
                "hk_identity": "",
                "hk_identity_other": "",
                "live_country": "",
                "is_handled": 0,
                "finish_follow": 0,
                "step": 3,
                "not_fill_num": 0,
                "is_live_oversea_year": 0,
                "surname": "",
                "certificates": [
                    "cnIdentityCard": [
                        "id": 116871,
                        "number": "421087199005010811",
                        "issue_at": "深圳",
                        "issue_date_start_at": "2017-01-01",
                        "issue_date_end_at": "2029-01-01",
                        "img_front": "",
                        "img_back": ""
                    ],
                    "passport": [
                        "id": 116872,
                        "number": "",
                        "issue_at": "",
                        "issue_date_start_at": "",
                        "issue_date_end_at": "",
                        "img_front": "",
                        "img_back": "",
                        "passport_type": 11
                    ]
                ]
            ]
        ] as [String : Any]

        familyMemberInfo = YHFamilyMemberGroupInfo.deserialize(dict: dic)
        loadFamilyMember()
        
    }
    
    func loadFamilyMember() {
        
        items.removeAll()
        
        // 配偶section
        if let sponse = familyMemberInfo?.spouse {
            // 信息未填写时服务器返回的relation=0
            sponse.relation = String(format: "%d", YHFamilyMemberType.spouse.rawValue)
            let sponseArray:[YHFormItemProtocol] = [YHFormTitleItem(type: .sponse), sponse]
            items.append(sponseArray)
        }
        
        // 父母section
        var parents = [YHFormItemProtocol]()
        if let father = familyMemberInfo?.father {
            // 信息未填写时服务器返回的relation=0
            father.relation = String(format: "%d", YHFamilyMemberType.father.rawValue)
            parents.append(father)
        }
        if let mother = familyMemberInfo?.mother {
            // 信息未填写时服务器返回的relation=0
            mother.relation = String(format: "%d", YHFamilyMemberType.mother.rawValue)
            parents.append(mother)
        }
        if !parents.isEmpty {
            let item0 = YHFormTitleItem(type: .parent)
            parents.insert(item0, at: 0)
            items.append(parents)
        }

        // 子女section
        var childArr:[YHFormItemProtocol] = [YHFormTitleItem(type: .child), YHFormAddItem(type: .addChild)]
        if let childs = familyMemberInfo?.child, !childs.isEmpty {
            childArr.insert(contentsOf: childs, at:1)
        }
        items.append(childArr)
        
        // 兄妹section
        var brotherArr:[YHFormItemProtocol] = [YHFormTitleItem(type: .brother), YHFormAddItem(type: .addBrother)]
        if let brothers = familyMemberInfo?.brother, !brothers.isEmpty {
            for brother in brothers {
                // 信息未填写时服务器返回的relation=0
                brother.relation = String(format: "%d", YHFamilyMemberType.brother.rawValue)
            }
            brotherArr.insert(contentsOf: brothers, at:1)
        }
        items.append(brotherArr)
        
        let childCount = familyMemberInfo?.child?.count ?? 0
        if isChildsEditMode == .none && childCount > 0 {
            isChildsEditMode = .canEdit
        }
        
        let brotherCount = familyMemberInfo?.brother?.count ?? 0
        if isBrothersEditMode == .none && brotherCount > 0 {
            isBrothersEditMode = .canEdit
        }
        tableView.reloadData()
    }
}

extension YHFamilyMemberFormVC {
    func addBrother() {
        
        let dict = [
            "id": 68470,
            "deceased": 0,
            "custody": 100,
            "nationality": "",
            "order_id": 133971,
            "relation": "5",
            "has_degree": "100",
            "has_degree_json": [],
            "follow": 0,
            "statement": 0,
            "subset_name": "",
            "subset_name_pinyin": [
                "family_name": "",
                "given_name": ""
            ],
            "used_name": "",
            "birthday": "",
            "birth_place_aboard": 100,
            "birth_place": [
                "area": [],
                "country": "",
                "details": "",
                "foreign": ""
            ],
            "occupation": "",
            "occupation_name": "",
            "operator_ame": "",
            "child_has_hk_id": [
                "has": "",
                "info": ""
            ],
            "hk_identity_card": "",
            "sex": 0,
            "married": "未婚",
            "nows": 100,
            "address": [
                "area": [],
                "country": "",
                "details": "",
                "foreign": ""
            ],
            "child_stepchild": [
                "has": "",
                "info": ""
            ],
            "child_in_hk": [
                "has": "",
                "info": ""
            ],
            "country_identity": [],
            "hk_identity": "",
            "hk_identity_other": "",
            "live_country": "",
            "is_handled": 100,
            "finish_follow": 0,
            "step": 0,
            "not_fill_num": 9,
            "is_live_oversea_year": 0,
            "surname": "",
            "certificates": []
        ] as [String : Any]
        
        let brother:YHFamilyMember = YHFamilyMember.deserialize(dict: dict)!
        
        if var brothers = familyMemberInfo?.brother {
            brothers.append(brother)
            familyMemberInfo!.brother = brothers
        } else {
            familyMemberInfo?.brother = [brother]
        }
        loadFamilyMember()
    }
    
    func addChild() {
        let dict = [
            "id": 68493,
            "deceased": 0,
            "custody": 100,
            "nationality": "",
            "order_id": 133971,
            "relation": "4",
            "has_degree": "100",
            "has_degree_json": [],
            "follow": 0,
            "statement": 0,
            "subset_name": "",
            "subset_name_pinyin": [
                "family_name": "",
                "given_name": ""
            ],
            "used_name": "",
            "birthday": "",
            "birth_place_aboard": 100,
            "birth_place": [
                "area": [],
                "country": "",
                "details": "",
                "foreign": ""
            ],
            "occupation": "",
            "occupation_name": "",
            "operator_ame": "",
            "child_has_hk_id": [
                "has": "",
                "info": ""
            ],
            "hk_identity_card": "",
            "sex": 0,
            "married": "未婚",
            "nows": 100,
            "address": [
                "area": [],
                "country": "",
                "details": "",
                "foreign": ""
            ],
            "child_stepchild": [
                "has": "",
                "info": ""
            ],
            "child_in_hk": [
                "has": "",
                "info": ""
            ],
            "country_identity": [],
            "hk_identity": "",
            "hk_identity_other": "",
            "live_country": "",
            "is_handled": 100,
            "finish_follow": 0,
            "step": 0,
            "not_fill_num": 10,
            "is_live_oversea_year": 0,
            "surname": "",
            "certificates":[]
           ] as [String : Any]
        
        let child = YHFamilyMember.deserialize(dict: dict)!
        if var childs = familyMemberInfo?.child {
            childs.append(child)
            familyMemberInfo!.child = childs
        } else {
            familyMemberInfo?.child = [child]
        }
        loadFamilyMember()
    }
}

extension YHFamilyMemberFormVC : 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 {
        
        let arr = items[indexPath.section]
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 是标题
            
            let formItem = item as! YHFormTitleItem
            
            // 配偶父母子女兄妹title
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.titleLabel.text = formItem.getTitle()
            cell.subTitleLabel.text = formItem.getSubTitle()
            
            // 决定右边按钮显示样式
            cell.showEditType(type: .none)
            if formItem.type == .child {
                cell.showEditType(type: isChildsEditMode)
                
            } else if formItem.type == .brother {
                cell.showEditType(type: isBrothersEditMode)
            }
            
            // 右边按钮点击事件处理
            cell.rightClickBlock = { [weak self] type in
                if formItem.type == .child {
                    if self?.isChildsEditMode == .canCancel {
                        self?.isChildsEditMode = .canEdit
                    } else if self?.isChildsEditMode == .canEdit {
                        self?.isChildsEditMode = .canCancel
                    }
                }
                if formItem.type == .brother {
                    if self?.isBrothersEditMode == .canCancel {
                        self?.isBrothersEditMode = .canEdit
                    } else if self?.isBrothersEditMode == .canEdit {
                        self?.isBrothersEditMode = .canCancel
                    }
                }
                self?.loadFamilyMember()
            }
            return cell
        }
        
        // 配偶父母子女兄妹具体条目
        if item is YHFamilyMember {
            
            let detailItem = item as! YHFamilyMember
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemEnterDetailCell.cellReuseIdentifier, for: indexPath) as! YHFormItemEnterDetailCell
            cell.title = detailItem.getTitle()
            cell.detailLabel.text = String(format: "有%d项未填写".local, detailItem.notFillNum)
            cell.isShowDeleteBtn = false
            cell.deleteBlock = nil
            if detailItem.relationType == .child || detailItem.relationType == .brother {
                
                if detailItem.relationType == .child {
                    cell.isShowDeleteBtn = (isChildsEditMode == .canCancel)
                    
                } else if detailItem.relationType == .brother {
                    cell.isShowDeleteBtn = (isBrothersEditMode == .canCancel)
                }

                // 删除子女兄妹处理
                cell.deleteBlock = { [weak self] in
                    if detailItem.relationType == .child {
                        let childCount = self?.familyMemberInfo?.child?.count ?? 0
                        // 因为子女兄妹section第一行都是标题所以row-1
                        if (indexPath.row-1 < childCount) {
                            self?.familyMemberInfo?.child?.remove(at: indexPath.row-1)
                            self?.isChildsEditMode = .none
                            self?.isBrothersEditMode = .none
                        }
                    } else if detailItem.relationType == .brother {
                        
                            let brotherCount = self?.familyMemberInfo?.brother?.count ?? 0
                            // 因为子女兄妹section第一行都是标题所以row-1
                            if (indexPath.row-1 < brotherCount) {
                                self?.familyMemberInfo?.brother?.remove(at: indexPath.row-1)
                                self?.isChildsEditMode = .none
                                self?.isBrothersEditMode = .none
                            }
                    }
                    self?.loadFamilyMember()
                }
            }
            
            return cell
        }
        
        // 新增子女/兄弟姐妹
        if item is YHFormAddItem {
            let formItem = item as! YHFormAddItem
            if formItem.type == .addChild || formItem.type == .addBrother {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemAddCell.cellReuseIdentifier, for: indexPath) as! YHFormItemAddCell
                cell.clickBlock = { [weak self] in
                    if formItem.type == .addBrother {
                        self?.addBrother()
                    } else if formItem.type == .addChild {
                        self?.addChild()
                    }
                 }
                return cell
            }
        }
        

        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
    
    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 tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let arr = items[indexPath.section]
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 是标题
            return 52.0
        } else if item is YHFormAddItem { // 新增子女兄妹
            return 70.0
        }
        return 50.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) {
        
        let arr = items[indexPath.section]
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        // 标题
        if item is YHFormTitleItem {
            return
        }
        // 新增子女兄妹
        if item is YHFormAddItem {
            let detailItem = item as! YHFormAddItem
            if detailItem.type == .addChild {
                
            } else if detailItem.type == .addBrother {
                
            }
            return
        }
        
        if item is YHFamilyMember {
            let detailItem = item as! YHFamilyMember
            // 父母
            if detailItem.relationType == .father || detailItem.relationType == .mother {
                let vc = YHParentInfoVC()
                vc.parentInfo = detailItem
                self.navigationController?.pushViewController(vc)
                return
            }
            
            // 配偶
            if detailItem.relationType == .spouse {
                let vc = YHSpouseInfoVC()
                vc.spouse = detailItem
                self.navigationController?.pushViewController(vc)
                return
            }
            
            // 子女
            if detailItem.relationType == .child {
                let vc = YHChildInitialInfoVC()
                vc.child = detailItem
                self.navigationController?.pushViewController(vc)
                return
            }
            
            // 兄弟姐妹
            if detailItem.relationType == .brother {
                let vc = YHBrotherInfoVC()
                vc.brotherInfo = detailItem
                self.navigationController?.pushViewController(vc)
                return
            }
        }
    }
        
    func createCorner(cell:UITableViewCell, arr:Array<Any>, indexPath:IndexPath) {
        // 设置每块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
        }
    }
}

