//
//  YHResignInfoConfirmModifyViewController.swift
//  galaxy
//
//  Created by edy on 2024/10/14.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHResignInfoConfirmModifyViewController: YHBaseViewController {

    var detailMember = YHResignInfoConfirmFamilyModel()

    let viewModel = YHResignInfoConfirmViewModel()
    
    var isInfoEditing: Bool = false
    
    var items: [[YHResignFamilyInfoItem]] = []
    
    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(YHResignFamilyInfoListCell.self, forCellReuseIdentifier: YHResignFamilyInfoListCell.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)
        
        let topLineView = UIView()
        topLineView.backgroundColor = .init(hex: 0xF0F0F0)
        view.addSubview(topLineView)
        
        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)
        }
        
        topLineView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(0.5)
        }

        return view
    }()
    
    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
    }
    
    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.isNeedCheck = true
        self.updateData()
        
        if !checkInfo() {
            return
        }
        
        if let detaiParams = self.detailMember.toDictionary() {
            let param: [String: Any] = ["id": self.detailMember.id,
                                       "data": 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 requestNamePinYin() {
        YHHUD.hide()
        let pinyinIsEmpty = (self.detailMember.familyName.isEmpty || self.detailMember.givenName.isEmpty)
        if !self.detailMember.name.isEmpty, pinyinIsEmpty {
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.getPinYinFromName(self.detailMember.name) {
                [weak self] firstName, lastName in
                YHHUD.hide()
                guard let self = self else { return }
                self.detailMember.familyName = firstName
                self.detailMember.givenName = lastName
                self.updateData()
            }
        }
    }
}

extension YHResignInfoConfirmModifyViewController: 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: YHResignFamilyInfoListCell.cellReuseIdentifier, for: indexPath) as? YHResignFamilyInfoListCell else {
            return UITableViewCell()
        }
        cell.familyInfo = self.detailMember
        
        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.updateList = {
                [weak self]  in
                guard let self = self else { return }
                self.updateData()
            }
            // 更改编辑状态
            cell.editBlock = {
                [weak self] isEdit in
                guard let self = self else { return }
                if !isEdit {
                    if !checkInfo() {
                        // 检查信息错误
                        self.isInfoEditing = true
                        self.detailMember.isNeedCheck = true
                        self.updateData()
                        self.requestNamePinYin()
                        return
                    }
                }
                
                self.isInfoEditing = isEdit
                self.updateData()
                self.requestNamePinYin()
                
            }
            cell.updateNamePinYinBlock = {
                [weak self] in
                guard let self = self else { return }
                self.requestNamePinYin()
            }
            // 选择出生国家/地区
            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))
            cell.titleLabel.attributed.text = title
            cell.modifyBtn.isHidden = true
            cell.updateList = nil
            // 点击有效期不足去处理
            cell.clickUnvalidTime = {
                [weak self] in
                guard let self = self else { return }
                if let identity = self.detailMember.identity {
                     if identity.type == 2 { // 港澳通行证
                        
                        let vc = YHResignCertificateDetailHkViewController()
                        vc.cerId = identity.id
                        vc.updateBlock = {
                             [weak self] cerInfo in
                             guard let self = self else { return }
                             if let identity = self.detailMember.identity {
                                 identity.number = cerInfo.number
                                 identity.begin = cerInfo.issue_start
                                 identity.end = cerInfo.issue_end
                                 self.updateData()
                             }
                         }
                        self.navigationController?.pushViewController(vc)
                         
                     } else if identity.type == 3 { // 普通护照
                         let vc = YHResignCertificateDetailPassPortViewController()
                         vc.cerId = identity.id
                         vc.updateBlock = {
                              [weak self] cerInfo in
                              guard let self = self else { return }
                              if let identity = self.detailMember.identity {
                                  identity.number = cerInfo.number
                                  identity.begin = cerInfo.issue_start
                                  identity.end = cerInfo.issue_end
                                  self.updateData()
                              }
                          }
                         self.navigationController?.pushViewController(vc)
                     }
                }
            }
        }
        
        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
    }
}

extension YHResignInfoConfirmModifyViewController {
    
    func updateData() {
        
        items.removeAll()
        
        // arr1 信息核实
        let arr1 = viewModel.getInfoConfirm(self.detailMember, isEditMode: self.isInfoEditing)
        items.append(arr1)
        
        // arr2 递交证件信息
        if let _ = self.detailMember.identity {
            let arr2 = viewModel.getCertificateInfo(self.detailMember)
            items.append(arr2)
        }
                
        self.tableView.reloadData()
    }
}
