//
//  YHGCFamilyMemberInfoListVC.swift
//  galaxy
//
//  Created by Dufet on 2024/12/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//


import UIKit

class YHGCFamilyMemberInfoListVC: YHBaseViewController {

    var orderId:Int
    let familyRequest:YHFamilyRequestViewModel = YHFamilyRequestViewModel()
    var familyMemberInfo: YHFamilyMemberGroupInfo?
    var isChildsEditMode: YHFormTitleItemEditType = .none
    var isBrothersEditMode: YHFormTitleItemEditType = .none
    // 是否显示未填写错误提示
    var isNeedShowError = false
    var items:[[YHFormItemProtocol]] = []
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        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(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.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        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
        gk_navigationBar.backgroundColor = .white
        view.backgroundColor = UIColor(hexString:"#F8F8F8")
        createUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestFamilyInfo()
    }
    
     init(orderId: Int) {
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    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() {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        self.tableView .reloadData()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return
        }
        submit()
    }
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        if let sponse = familyMemberInfo?.spouse, sponse.notFillNumber != 0 {
          return false
        }
        
//        if let father = familyMemberInfo?.father, father.notFillNumber != 0 {
//            return false
//        }
//
//        if let mother = familyMemberInfo?.mother, mother.notFillNumber != 0 {
//            return false
//        }
        
        if let childs = familyMemberInfo?.child, !childs.isEmpty {
            for child in childs {
                if child.notFillNumber != 0 {
                    return false
                }
            }
        }
        
//        if let brothers = familyMemberInfo?.brother, !brothers.isEmpty {
//            for brother in brothers {
//                if brother.notFillNumber != 0 {
//                    return false
//                }
//            }
//        }
        return true
    }
    
    func loadFamilyMember() {
        
        items.removeAll()
        
        // 配偶section
        if let sponse = familyMemberInfo?.spouse {
            // 信息未填写时服务器返回的relation=0
            sponse.relationType = .spouse
            let sponseArray:[YHFormItemProtocol] = [YHFormTitleItem(type: .sponse), sponse]
            items.append(sponseArray)
        }
        
        // 子女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 parents = [YHFormItemProtocol]()
//        let item0 = YHFormTitleItem(type: .parent)
//        parents.append(item0)
//
//        if let father = familyMemberInfo?.father {
//            // 信息未填写时服务器返回的relation=0
//            father.relationType = .father
//            parents.append(father)
//        }
//
//        if let mother = familyMemberInfo?.mother {
//            // 信息未填写时服务器返回的relation=0
//            mother.relationType = .mother
//            parents.append(mother)
//        }
//        items.append(parents)
    
        
        // 兄妹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 childCount <= 0 {
            isChildsEditMode = .none
        } else {
            if isChildsEditMode == .none {
                isChildsEditMode = .canEdit
            }
        }
        
//        let brotherCount = familyMemberInfo?.brother?.count ?? 0
//        if brotherCount <= 0 {
//            isBrothersEditMode = .none
//        } else {
//            if  isBrothersEditMode == .none {
//                isBrothersEditMode = .canEdit
//            }
//        }
        tableView.reloadData()
    }
}

extension YHGCFamilyMemberInfoListVC {
    
    // 请求家庭成员信息
    func requestFamilyInfo() {
        
        self.familyRequest.getFamilyInfoList(orderId:orderId) { [weak self] detail, error in
            guard let self = self else { return }
            if let detail = detail {
                familyMemberInfo = detail
            }
            loadFamilyMember()
        }
    }
    
    // 添加兄弟姐妹子女
    func addFamilyMember(_ type:YHFamilyMemberType) {
        
        let dict:[String: Any] = ["order_id":self.orderId,
                                  "relation":String(type.rawValue),
                                  "step":0,
                                  "next":false,
                                  "info":["subset_name":"",
                                          "not_fill_number":-1,
                                          "have_permanent_residency":2,
                                          "nows":1,
                                          "follow":0]]
        
        self.familyRequest.addOrSaveFamilyMember(params: dict) { [weak self] success, error in
            guard let self = self else { return }
            if success {
                self.requestFamilyInfo()
            } else {
                var errorMsg = "添加失败"
                if let errMsg = error?.errorMsg, errMsg.count > 0 {
                    errorMsg = errMsg
                }
                YHHUD.flash(message: errorMsg)
            }
        }
    }
    
    // 添加兄弟姐妹子女
    func deleteFamilyMember(orderId:Int, memberId:Int, callBack:((Bool)->Void)?) {
        if orderId > 0 && memberId > 0 {
            let dict = ["id":memberId, "order_id": orderId]
            self.familyRequest.deleteFamilyMember(params: dict) {
                success, error in
                if success {
                    YHHUD.flash(message: "删除成功".local)
                } else {
                    var errorMsg = "删除失败"
                    if let errMsg = error?.errorMsg, errMsg.count > 0 {
                        errorMsg = errMsg
                    }
                    YHHUD.flash(message: errorMsg)
                }
                if let callBack = callBack {
                    callBack(success)
                }
            }
        }
    }
    
    func submit() {
        self.familyRequest.submitAllFamilyInfo(orderId: self.orderId) {
            success, error in
            if success {
                YHHUD.flash(message: "提交成功")
                self.navigationController?.popViewController()

            } else {
                var errorMsg = "提交失败"
                if let errMsg = error?.errorMsg, errMsg.count > 0 {
                    errorMsg = errMsg
                }
                YHHUD.flash(message: errorMsg, duration:3)
            }
        }
    }
}

extension YHGCFamilyMemberInfoListVC : 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.setTitleAndSubTitle(title:formItem.getTitle(), subTitle: 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
                
                guard let self = self else { return }
                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.isNeedTopLineNoGap = (indexPath.row == 1)
            cell.title = detailItem.getTitle()
//            cell.detailLabel.textColor = (isNeedShowError && detailItem.notFillNumber != 0 ? .failColor : .labelTextColor2)

            var tips = ""
            if detailItem.notFillNumber > 0 {
                tips  = String(format: "有%d项未填写".local, detailItem.notFillNumber)
            } else if detailItem.notFillNumber == 0 {
                tips = "已填完".local
            } else {
                tips = "还未开始填写".local
            }
            cell.detailLabel.text = tips
            cell.setTips(tips, isShow: (isNeedShowError && detailItem.notFillNumber != 0))
            
            if isEmptyString(detailItem.subsetName) { // 姓名为空
                if detailItem.relationType == .child {
                    cell.title = String(format: "子女%d".local, indexPath.row)
                } else if detailItem.relationType == .brother {
                    cell.title = String(format: "兄弟姐妹%d".local, indexPath.row)
                }
            } else {
                var name = ""
                if detailItem.relationType == .father {
                    name = "父亲"
                } else if detailItem.relationType == .mother {
                    name = "母亲"
                } else if detailItem.relationType == .spouse {
                    name = "配偶"
                } else if detailItem.relationType == .child {
                    name = "子女"
                } else if detailItem.relationType == .brother {
                    name = "兄弟姐妹"
                }
                name += "-"
                name += detailItem.subsetName
                cell.title = name
            }

            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
                    guard let self = self else { return }
                    
                    if detailItem.relationType == .child {
                        
                        let childCount = self.familyMemberInfo?.child?.count ?? 0
                        // 因为子女兄妹section第一行都是标题所以row-1
                        if (indexPath.row-1 >= childCount) { return }
                        guard let child = self.familyMemberInfo?.child?[indexPath.row-1] else { return }
                        var name = String(format: "子女%d", indexPath.row)
                        if !detailItem.subsetName.isEmpty {
                            name += "(\(detailItem.subsetName))"
                        }
                        let msg = String(format: "确定要删除%@吗?".local, name)

                        YHTwoOptionAlertView.showAlertView(message:msg) { sure in
                            
                            if !sure { return }
                            
                            self.deleteFamilyMember(orderId: self.orderId, memberId:child.detailId) {
                                [weak self] success in
                                guard let self = self else { return }
                                
                                if success {
                                    self.isChildsEditMode = .none
                                    self.isBrothersEditMode = .none
                                    self.requestFamilyInfo()
                                }
                            }
                        }
                        
                    } else if detailItem.relationType == .brother {
                        
                        let brotherCount = self.familyMemberInfo?.brother?.count ?? 0
                        // 因为子女兄妹section第一行都是标题所以row-1
                        if (indexPath.row-1 >= brotherCount) { return }
                        guard let brother = self.familyMemberInfo?.brother?[indexPath.row-1] else { return }
                        var name = String(format: "兄弟姐妹%d", indexPath.row)
                        if !detailItem.subsetName.isEmpty {
                            name += "(\(detailItem.subsetName))"
                        }
                        
                        let msg = String(format: "确定要删除%@吗?".local, name)
                        YHTwoOptionAlertView.showAlertView(message: msg) { sure in
                            
                            if !sure { return }
                            
                            self.deleteFamilyMember(orderId: self.orderId, memberId:brother.detailId) {
                                [weak self] success in
                                guard let self = self else { return }
                                
                                if success {
                                    self.isChildsEditMode = .none
                                    self.isBrothersEditMode = .none
                                    self.requestFamilyInfo()
                                }
                            }
                        }
                    }
                }
            }
            
            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.title = formItem.getTitle()
                cell.isNeedTopLineNoGap = true
                
                if formItem.type == .addChild {
                    var hiddenTopLine = false
                    if let childs = familyMemberInfo?.child, !childs.isEmpty {
                       hiddenTopLine = true
                    }
                    cell.isHiddenTopLine = hiddenTopLine
                    
                } else if formItem.type == .addBrother {
                    var hiddenTopLine = false
                    if let brothers = familyMemberInfo?.brother, !brothers.isEmpty {
                       hiddenTopLine = true
                    }
                    cell.isHiddenTopLine = hiddenTopLine
                }
                
                cell.clickBlock = { [weak self] in
                    guard let self = self else { return }
                    if formItem.type == .addBrother {
                        self.addFamilyMember(.brother)
                    } else if formItem.type == .addChild {
                        self.addFamilyMember(.child)
                    }
                 }
                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 {
        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) {
        
        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 == .spouse {
                 let vc = YHGCSpouseInfoContainerVC()
                 vc.spouse = detailItem
                 vc.mainApplicantInfo = self.familyMemberInfo?.applicant
                 vc.orderId = orderId
                 self.navigationController?.pushViewController(vc)
                 return
             }
             
             // 父母
             if detailItem.relationType == .father || detailItem.relationType == .mother {
                 let vc = YHParentInfoVC()
                 vc.parentInfo = detailItem
                 vc.orderId = orderId
                 self.navigationController?.pushViewController(vc)
                 return
             }
             
             // 子女
             if detailItem.relationType == .child {
                 let vc = YHGCChildInfoContainerVC()
                 vc.child = detailItem
                 vc.mainApplicantInfo = self.familyMemberInfo?.applicant
                 vc.orderId = orderId
                 self.navigationController?.pushViewController(vc)
                 return
             }
             
             // 兄弟姐妹
             if detailItem.relationType == .brother {
                 let vc = YHBrotherInfoVC()
                 vc.orderId = orderId
                 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
        }
    }
}


