//
//  YHTravelDocsPreparationDetailVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/28.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

enum YHTravelDocsType: Int {
    case unknown = -1 // 未知
    case HK = 0 //  港澳通行证
    case chinesePassPort = 1 // 中国护照
    case forignPassPort = 2  // 外国护照
    
}

enum YHTravelCerSectionType: Int {
    case tips = 0
    case certificate = 1
}

class YHTravelCerSectionItem {
    
    var type: YHTravelCerSectionType = .tips
    var tipsArr: [ASAttributedString] = []
    var cerDetailModel: YHTravelDocsPreparationDetailItemModel = YHTravelDocsPreparationDetailItemModel()
        
    init(type: YHTravelCerSectionType, tipsArr: [ASAttributedString]) {
        
        self.type = type
        self.tipsArr = tipsArr
    }
    
}

class YHTravelDocsPreparationDetailVC: YHBaseViewController {
    
    var type: YHTravelDocsType = .HK
    
    lazy var viewModel: YHTravelDocsPreparationViewModel = {
        let vm = YHTravelDocsPreparationViewModel()
        return vm
    }()
    
    // 上个界面传递过来的数据对象
    var dataModel: YHTravelDocsPreparationListModel = YHTravelDocsPreparationListModel()
    
    var orderId: Int = 0
    
    var sectionItems: [YHTravelCerSectionItem] = []
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 14.0
        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(YHTravelCertificateTipsCell.self, forCellReuseIdentifier: YHTravelCertificateTipsCell.cellReuseIdentifier)
        tableView.register(YHTravelCertificateUploadCell.self, forCellReuseIdentifier: YHTravelCertificateUploadCell.cellReuseIdentifier)
        return tableView
    }()
    
    let bottomViewHeight = 98.0
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.isHidden = true
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认，保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didSaveBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "旅行证件准备"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)
        
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0)
        }
        loadDetailInfo()
    }
    
    func updateData() {
        
        // travel_cert_type 证件类型 0-未知 1-护照 3-港澳通行证
        // nationality : Int = -1  国籍 1-中国 2-国外
        
        if dataModel.nationality == 2 { // 国籍为国外
            self.type = .forignPassPort
            
        } else { // 国籍为中国
            if dataModel.travel_cert_type == 1 { // 中国护照
                self.type = .chinesePassPort
                
            } else if dataModel.travel_cert_type == 3 { // 港澳通行证
                self.type = .HK
            }
        }
        
        // 头部提示
        let tipsArr = viewModel.getTipsWithType(self.type, date: self.viewModel.travelDetailModel?.latest_validaty_date ?? "")
        let item1 = YHTravelCerSectionItem(type: .tips, tipsArr: tipsArr)
        sectionItems.append(item1)
        
        var isCanEdit: Bool = false
        // 证件相关
        if let list = self.viewModel.travelDetailModel?.list, list.count > 0 {
            for model in list {
                let item2 = YHTravelCerSectionItem(type: .certificate, tipsArr: [])
                if let model = model {
                    item2.cerDetailModel = model
                    model.isCanEdit = (model.status == 2)
                    if model.status == 2 {
                        isCanEdit = true
                    }
                    sectionItems.append(item2)
                }
            }
            
        } else { // 没有上传过证件
            isCanEdit = true
            let age = self.viewModel.travelDetailModel?.age ?? 0
            var userId = 0
            if let uid = YHLoginManager.shared.userModel?.id {
                userId = Int(uid) ?? 0
            }
            
            if self.type == .HK || self.type == .chinesePassPort {
                
                let item = YHTravelCerSectionItem(type: .certificate, tipsArr: [])
                // 证件类型 1-护照 2-中国旅行证 3-港澳通行证 4-存款证明 5-其他
                var type = -1
                if self.type == .chinesePassPort {
                    type = 1
                } else if self.type == .HK {
                    type = 3
                }
                let cerModel1 = YHTravelDocsPreparationDetailItemModel(type: type, order_id: self.orderId, order_sn: "", img_back: "", img_front: "", status: 0, issue_start: "", issue_end: "", user_id: userId, user_type: dataModel.type, remark: "", nationality: "\(dataModel.nationality)", age: age)
                
                cerModel1.latest_validaty_date = self.viewModel.travelDetailModel?.latest_validaty_date ?? ""
                cerModel1.china_travel_latest_validaty_date = self.viewModel.travelDetailModel?.china_travel_latest_validaty_date ?? ""
                cerModel1.isCanEdit = true
                item.cerDetailModel = cerModel1
                sectionItems.append(item)
                
            } else if self.type == .forignPassPort { // 外国护照
                
                // 外国护照
                let item1 = YHTravelCerSectionItem(type: .certificate, tipsArr: [])
                let cerModel1 = YHTravelDocsPreparationDetailItemModel(type: 1, order_id: self.orderId, order_sn: "", img_back: "", img_front: "", status: 0, issue_start: "", issue_end: "", user_id: userId, user_type: dataModel.type, remark: "", nationality: "\(dataModel.nationality)", age: age)
                cerModel1.latest_validaty_date = self.viewModel.travelDetailModel?.latest_validaty_date ?? ""
                cerModel1.china_travel_latest_validaty_date = self.viewModel.travelDetailModel?.china_travel_latest_validaty_date ?? ""
                cerModel1.isCanEdit = true
                item1.cerDetailModel = cerModel1
                sectionItems.append(item1)
                
                // 中国居留许可签证
                let item2 = YHTravelCerSectionItem(type: .certificate, tipsArr: [])
                let cerModel2 = YHTravelDocsPreparationDetailItemModel(type: 2, order_id: self.orderId, order_sn: "", img_back: "", img_front: "", status: 0, issue_start: "", issue_end: "", user_id: userId, user_type: dataModel.type, remark: "", nationality: "\(dataModel.nationality)", age: age)
                cerModel2.latest_validaty_date = self.viewModel.travelDetailModel?.latest_validaty_date ?? ""
                cerModel2.china_travel_latest_validaty_date = self.viewModel.travelDetailModel?.china_travel_latest_validaty_date ?? ""
                cerModel2.isCanEdit = true
                item2.cerDetailModel = cerModel2
                sectionItems.append(item2)
                
            }
        }
        
        self.bottomView.isHidden = !isCanEdit
        self.bottomView.snp.updateConstraints { make in
            make.height.equalTo(isCanEdit ? bottomViewHeight : 0.0)
        }
        tableView.reloadData()
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
    }
    
    @objc func didSaveBtnClicked() {
        if !checkInfo() {
            return
        }
        
        saveAllTravelCertificate()
    }
    
    func checkInfo() -> Bool {
        var errorItemCount = 0
        for item in sectionItems {
            if item.type == .certificate {
                var hasSubmitError = false
                var isDateValidate = true
                item.cerDetailModel.isNeedCheckCer = false
                item.cerDetailModel.isNeedCheckDate = false

                if item.cerDetailModel.isOCR_failed {
                    // 无法识别不能当做无法提交的错误 所以 此处 hasError 不必设置为true
                    item.cerDetailModel.isNeedCheckCer = true
                    item.cerDetailModel.checkTips = "无法识别，请核查文件"
                    
                } else {
                    var noCerInfo = false
                    if item.cerDetailModel.type == 3 { // 只有港澳通行证有正反面
                        noCerInfo = (item.cerDetailModel.img_front.isEmpty || item.cerDetailModel.img_back.isEmpty)
                    } else {
                        noCerInfo = item.cerDetailModel.img_front.isEmpty
                    }
                    
                    if noCerInfo {
                        hasSubmitError = true
                        item.cerDetailModel.isNeedCheckCer = true
                        if item.cerDetailModel.type == 3 { // 港澳通行证
                            item.cerDetailModel.checkTips = item.cerDetailModel.img_front.isEmpty ? "请上传港澳通行证正面" : "请上传港澳通行证反面"
                            
                        } else if item.cerDetailModel.type == 1 { // 中国护照
                            item.cerDetailModel.checkTips = "请上传护照"
                            
                        } else if item.cerDetailModel.type == 2 { // 中国居留许可签证
                            item.cerDetailModel.checkTips = "请上传中国居留许可签证"
                        }
                        
                    } else {
                        item.cerDetailModel.isNeedCheckDate = false
                        if item.cerDetailModel.issue_start.isEmpty || item.cerDetailModel.issue_end.isEmpty {
                            hasSubmitError = true
                            item.cerDetailModel.isNeedCheckDate = true
                            
                        } else {
                            let isValidCertificate = item.cerDetailModel.isValidCer()
                            if !isValidCertificate {
                                if item.cerDetailModel.type == 2, item.cerDetailModel.china_travel_latest_validaty_date.isEmpty {
                                    // 这个情况直接弹toast
                                    hasSubmitError = true
                                    YHHUD.flash(message: "赴港行程尚未成功预约，请前往检查")
                                    
                                } else {
                                    // 有效期不足也能提交
                                    isDateValidate = false
                                    item.cerDetailModel.isNeedCheckCer = true
                                    let deadDate: String = (item.cerDetailModel.type == 2 ? item.cerDetailModel.china_travel_latest_validaty_date :  item.cerDetailModel.latest_validaty_date)
                                    item.cerDetailModel.checkTips = "有效期不足，需要为\(deadDate)或以后"
                                }
                            }
                        }
                    }
                }
                if !hasSubmitError {
                    // 无法识别或有效期不足也要可以提交
                    if !item.cerDetailModel.isOCR_failed && isDateValidate {
                        item.cerDetailModel.isNeedCheckCer = false
                        item.cerDetailModel.isNeedCheckDate = false
                    }
                    
                } else {
                    errorItemCount += 1
                }
            }
        }
        self.tableView.reloadData()
        
        if errorItemCount > 0 {
            return false
        }
        return true
    }
}

private extension YHTravelDocsPreparationDetailVC {
    // 1、获取详情信息
    func loadDetailInfo() {
        
        let params = [
            "order_id": orderId,
            "user_id": dataModel.id,
            "user_type": dataModel.type
        ] as [String: Any]
        
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getTravelDocsDetailInfo(param: params) { success, _ in
            YHHUD.hide()
            if success {
                // TODO: 杜宇哥 UI刷新
                self.updateData()
                
            } else {
                
            }
        }
    
    }
    
    // 2、保存旅行证件
    func saveAllTravelCertificate() {
           
            /*
             {
               "order_id": 0,
               "user_id": 0,
               "user_type": "string",
               "certificates": [
                 {
                   "type": 0,
                   "img_back": "string",
                   "img_front": "string",
                   "issue_start": "string",
                   "issue_end": "string"
                 }
               ]
             }
             */
            var cerArr: [[String: Any]] = []
            for item in sectionItems {
                if item.type == .certificate {
                    var imageback = item.cerDetailModel.img_back
                    if self.type == .chinesePassPort || self.type == .forignPassPort {
                        imageback = ""
                    }
                    let dic: [String: Any] = [
                        "type": item.cerDetailModel.type,
                        "img_front": item.cerDetailModel.img_front,
                        "img_back": imageback,
                        "issue_start": item.cerDetailModel.issue_start,
                        "issue_end": item.cerDetailModel.issue_end
                    ]
                    cerArr.append(dic)
                }
            }
        
            let params = [
                "order_id": orderId,
                "user_id": dataModel.id,
                "user_type": dataModel.type,
                "certificates": cerArr // TODO: 杜宇哥完善下这个数据
            ] as [String: Any]
            
            YHHUD.show(.progress(message: "保存中"))
            viewModel.saveTravelDocsInfo(params: params) { success, error in
                YHHUD.hide()
                if success {
                    YHHUD.flash(message: "保存成功")
                    self.navigationController?.popViewController()
                    return
                }
                YHHUD.flash(message: error?.errorMsg ?? "保存失败")
            }
    }
}

extension YHTravelDocsPreparationDetailVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionItems.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if 0 <= indexPath.section && indexPath.section < sectionItems.count {
            let item = sectionItems[indexPath.section]
            if item.type == .tips {
                if indexPath.section == 0 {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHTravelCertificateTipsCell.cellReuseIdentifier, for: indexPath) as? YHTravelCertificateTipsCell else { return UITableViewCell() }
                    cell.userName = self.dataModel.name
                    cell.tipsArr = item.tipsArr
                    return cell
                }
            }
        }

        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHTravelCertificateUploadCell.cellReuseIdentifier, for: indexPath) as? YHTravelCertificateUploadCell else {
            return UITableViewCell()
        }
        if 0 <= indexPath.section && indexPath.section < sectionItems.count {
            let item = sectionItems[indexPath.section]
            cell.updateModel(item.cerDetailModel)
            cell.updateBlock = {
                [weak self] _ in
                guard let self = self else { return }
                self.checkInfo()
                self.tableView.reloadData()
            }
            cell.templateClick = {
                // 证件类型 1-护照 2-中国旅行证 3-港澳通行证 4-存款证明 5-其他
                [weak self] type in
                guard let self = self else { return }
                
                var templateType: YHAdopterCardType?
                if type == 1 { // 护照
                    templateType = .chinaTravel
                    
                } else if type == 2 { // 中国旅行证
                    templateType = .chinaLife
                    
                } else if type == 3 { // 港澳通行证
                    templateType = .travel
                }
                YHAdopterCardExampleView.exampleView(type: templateType).show()
            }
        }
        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 < sectionItems.count {
            
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
            
        return 14.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 {
            view.backgroundColor = .white
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}
