//
//  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 {

    var orderId:Int
    let familyRequest:YHFamilyRequestViewModel = YHFamilyRequestViewModel()
    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()
        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() {
        
    }
    
    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 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 YHFamilyMemberFormVC {
    
    // 请求家庭成员信息
    func requestFamilyInfo() {
        
        self.familyRequest.getFamilyInfo(params: ["orderId": self.orderId]) { [weak self] success, error in
            guard let self = self else { return }
            if success {
                familyMemberInfo = self.familyRequest.familyInfo
            }
            loadFamilyMember()
        }
    }
    
    // 添加兄弟姐妹子女
    func addFamilyMember(_ type:YHFamilyMemberType) {
        
        let dict:[String: Any] = ["orderId":self.orderId,
                                  "relation":String(type.rawValue),
                                  "step":0,
                                  "next":false,
                                  "info":["subset_name":"",
                                          "not_fill_num":"",
                                          "follow":0]]
        
        self.familyRequest.addFamilyMember(params: dict) { [weak self] success, error in
            guard let self = self else { return }
            if success {
                self.requestFamilyInfo()
            }
        }
    }
    
    // 添加兄弟姐妹子女
    func deleteFamilyMember(orderId:Int, memberId:Int, callBack:((Bool)->Void)?) {
        if orderId > 0 && memberId > 0 {
            let dict = ["id":memberId, "orderId": orderId]
            self.familyRequest.deleteFamilyMember(params: dict) { [weak self] success, error in
                
                guard let self = self else { return }
                if let callBack = callBack {
                    callBack(success)
                }
            }
        }
    }
}

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
                
                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.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
                    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 }
                        let msg = String(format: "确定要删除子女%d(%@)吗?".local, indexPath.row, "XXX")

                        YHTwoOptionAlertView.showAlertView(message:msg) { sure in
                            
                            if !sure { return }
                            
                            self.deleteFamilyMember(orderId: self.orderId, memberId:child.id) {
                                [weak self] success in
                                guard let self = self else { return }

                                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 }
                        let msg = String(format: "确定要删除兄弟%d(%@)吗?".local, indexPath.row, "XXX")
                        YHTwoOptionAlertView.showAlertView(message: msg) { sure in
                            
                            if !sure { return }
                            
                            self.deleteFamilyMember(orderId: self.orderId, memberId:brother.id) {
                                [weak self] success in
                                guard let self = self else { return }
                                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.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 {
        
        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
        }
    }
}

