//
//  YHFamilyInfoUpdateViewController.swift
//  galaxy
//
//  Created by edy on 2024/8/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

enum YHFamilyMemberRelationType: Int {
    case none = 0
    case mainApplicant = 1
    case spouse = 2
    case child = 3
}

class YHFamilyInfoUpdateViewController: YHBaseViewController {
    
    var orderId: Int = 0
    var detailMember: YHApplicantInfoModel = YHApplicantInfoModel()

    let viewModel = YHFamilyInfoConfirmViewModel()
    
    var relation: YHFamilyMemberRelationType = .mainApplicant
    var isInfoEditing: Bool = false
    
    var items: [[YHFamilyInfoItem]] = []
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8F9FB)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHIFamilyInfoListCell.self, forCellReuseIdentifier: YHIFamilyInfoListCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        
        let cancelBtn = UIButton()
        cancelBtn.backgroundColor = UIColor.init(hex: 0xF8F9FB)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.setTitleColor(.init(hex: 0x222222), for: .normal)
        cancelBtn.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        cancelBtn.addTarget(self, action: #selector(didCancelBtnClicked), for: .touchUpInside)
        cancelBtn.layer.cornerRadius = kCornerRadius3
        view.addSubview(cancelBtn)
        
        let confirmBtn = UIButton()
        confirmBtn.backgroundColor = .brandMainColor
        confirmBtn.setTitle("确认", for: .normal)
        confirmBtn.setTitleColor(.white, for: .normal)
        confirmBtn.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        confirmBtn.addTarget(self, action: #selector(didConfirmBtnClicked), for: .touchUpInside)
        confirmBtn.layer.cornerRadius = kCornerRadius3
        view.addSubview(confirmBtn)
        
        cancelBtn.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(16)
            make.height.equalTo(44)
            make.width.equalTo(86)
        }
        
        confirmBtn.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.right.equalTo(-16)
            make.height.equalTo(44)
            make.left.equalTo(cancelBtn.snp.right).offset(10)
        }
        
        return view
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        self.gk_navTitle = "家庭信息确认"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+16)
            make.bottom.equalTo(self.bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
        self.updateData()
    }
    
    // 展示挽留弹窗
    func  showRetainAlertView() {
        YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
            self.navigationController?.popViewController()
        } callBack: {
            
        }
    }
    
    @objc func didCancelBtnClicked() {
        if self.isInfoEditing {
            showRetainAlertView()
            return
        }
        self.navigationController?.popViewController()
    }
    
    func checkInfo() -> Bool {
        if let arr1 = items.first {
            for item in arr1 {
                if !item.tips.isEmpty {
                    return false
                }
            }
        }
        return true
    }
    
    @objc func didConfirmBtnClicked() {
        self.detailMember.info.isCheck = true
        self.updateData()
        
        if !checkInfo() {
            return
        }
        
        if let detaiParams = self.detailMember.info.toDictionary() {
            
            var relation = ""
            if self.detailMember.info.relation == YHFamilyMemberRelationType.mainApplicant.rawValue {
                relation = "main"
                
            } else if self.detailMember.info.relation == YHFamilyMemberRelationType.spouse.rawValue {
                relation = "spouse"
            
            } else if self.detailMember.info.relation == YHFamilyMemberRelationType.child.rawValue {
                relation = "children"
            }
            
            let param: [String: Any] = ["orderId": orderId,
                                        relation: detaiParams]
            YHHUD.show(.progress(message: "提交中..."))
            viewModel.submitFamilyUpdate(param: param) {
                [weak self] success, error in
                YHHUD.hide()
                guard let self = self else { return }
                if success {
                    YHHUD.flash(message: "提交成功")
                    self.navigationController?.popViewController()
                    return
                }
                
                let msg = error?.errorMsg ?? "提交失败"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    func updateData() {
        
        items.removeAll()
        
        // arr1 信息核实
        let arr1 = viewModel.getInfoConfirm(self.detailMember, isEditMode: self.isInfoEditing)
        items.append(arr1)
        
        // arr2 递交证件信息
        if let _ = self.detailMember.info.identity {
            let arr2 = viewModel.getCertificateInfo(self.detailMember)
            items.append(arr2)
        }
                
        self.tableView.reloadData()
    }
    
    override func backItemClick(_ sender: Any) {
        self.view.endEditing(true)
        if self.isInfoEditing {
            showRetainAlertView()
            return
        }
        self.navigationController?.popViewController()
    }
    
    // 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
        self.view.endEditing(true)
        if self.isInfoEditing {
            showRetainAlertView()
            return false
        }
        return true
    }
}

extension YHFamilyInfoUpdateViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHIFamilyInfoListCell.cellReuseIdentifier, for: indexPath) as? YHIFamilyInfoListCell else { return UITableViewCell() }
        
        if indexPath.row == 0 {
            // 标题
            let title: ASAttributedString = .init("信息核实", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
            cell.titleLabel.attributed.text = title
            cell.modifyBtn.isHidden = false
            cell.isEditState = self.isInfoEditing
            cell.familyInfo = self.detailMember.info
            // 更改编辑状态
            cell.editBlock = {
                [weak self] isEdit in
                guard let self = self else { return }
                if !isEdit {
                    if !checkInfo() {
                        // 检查信息错误
                        self.isInfoEditing = true
                        self.detailMember.info.isCheck = true
                        self.updateData()
                        return
                    }
                }
                self.isInfoEditing = isEdit
                self.updateData()
                
            }
            // 选择出生国家/地区
            cell.selectBirthNation = {
                [weak self] _ in
                guard let self = self else { return }
                self.updateData()
            }
            
        } else {
            
            let title: ASAttributedString = .init("递交证件信息", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
            let subtitle: ASAttributedString = .init("(如需更换，请联系您的生活管家)", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
            cell.titleLabel.attributed.text = title + subtitle
            cell.modifyBtn.isHidden = true

        }
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let arr = items[indexPath.row]
            cell.updateItems(arr)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 16.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}
