//
//  YHResignCertificateDetailHkViewController.swift
//  galaxy
//
//  Created by EDY on 2024/9/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHResignCertificateDetailHkViewController: YHBaseViewController {
        
    var updateBlock: ((YHResignCertificateInfoModel) -> Void)?
    
    lazy var viewModel: YHResignCertificateDetailViewModel = {
        let vm = YHResignCertificateDetailViewModel()
        return vm
    }()
    
    var cerId: Int = 0 // 证件ID
    // 通过cerId请求 的数据对象
    private var dataModel: YHResignCertificateModel = YHResignCertificateModel()
    var orderId: Int = 0
    var tipsArr: [ASAttributedString] = []
    var urls: [String] = ["", ""]
    var data: [YHItemModel] = []
    var isShowPrompt = false
    var failString: String = ""
    var isDisableEdit: Bool = false

    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(YHResignCertificateHKTableViewCell.self, forCellReuseIdentifier: YHResignCertificateHKTableViewCell.cellReuseIdentifier)
        return tableView
    }()
    
    let bottomViewHeight = 98.0
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0xF8F9FB)
        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(98)
        }
        self.bottomView.addSubview(bottomBtn)
        self.bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        reuqestCertificateDetail()

    }
    
    func getTextWithType(type: Int, date: String) -> ASAttributedString {
        
        if type ==  0 {
           return .init("上传《港澳通行证》(需有效期≥\(date))", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
        }
        
        if type == 1 {
            let a = ASAttributedString.init("若有效期不足，请至少在续签前3个月完成证件更新", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.brandMainColor))
            let b = ASAttributedString.init("，请提醒出入境办证人员", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor50))
            let c = ASAttributedString.init("务必保留背面逗留D签注", .font(UIFont.PFSC_R(ofSize: 14)),
                .foreground(UIColor.brandMainColor))
            let d = ASAttributedString.init("，避免影响入境香港及续签时长!", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor50))
            return a+b+c+d
        }
        
        return .init("", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
    }
    
    func getTipsWithType(date: String) -> [ASAttributedString] {
        return [self.getTextWithType(type: 0, date: date),
                self.getTextWithType(type: 1, date: date)]
    }
    
    func updateData() {
        
        // travel_cert_type 证件类型 0-未知 1-护照 3-港澳通行证
        // nationality : Int = -1  国籍 1-中国 2-国外
        self.viewModel.dataModel = dataModel
        if dataModel.cert_info.img_front.count != 0 {
            urls[0] = dataModel.cert_info.img_front
        }
        if dataModel.cert_info.img_back.count != 0 {
            urls[1] = dataModel.cert_info.img_back
        }
        self.data = viewModel.getBaseDatadSource(isShowPrompt)
        // 头部提示
        tipsArr = getTipsWithType(date: self.dataModel.valid_date)
        tableView.reloadData()
        
    }
    
    @objc func didSaveBtnClicked() {
    
        if isDisableEdit {
            return
        }
        if !checkInfo() {
            isShowPrompt = true
            updateData()
            return
        }
        
        saveAllTravelCertificate()
    }
    
    func checkInfo() -> Bool {
        if urls.first?.count == 0 {
            failString = "请港澳通行证正面"
            return false
        }
        if urls.last?.count == 0 {
            failString = "请港澳通行证背面"
            return false
        }
        
        if self.viewModel.dataModel.cert_info.number.count <= 0 { // 证件号码为空
            return false
        }
        
        if self.viewModel.dataModel.cert_info.address.count <= 0 { // 证件签发地为空
            return false
        }
        
        if self.viewModel.dataModel.cert_info.issue_start.count == 0 {
            return false
        }
        if self.viewModel.dataModel.cert_info.issue_end.count == 0 {
            return false
        }
        if self.viewModel.dataModel.cert_info.validate_start.count == 0 {
            return false
        }
        if self.viewModel.dataModel.cert_info.validate_end.count == 0 {
            return false
        }
        return true
    }
    
    func reuqestCertificateDetail() {
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getCertificateDetail(self.cerId) {
            [weak self] model, error in
            YHHUD.hide()
            guard let self = self else { return }
            guard let model = model else {
                let msg = error?.errorMsg ?? ""
                YHHUD.flash(message: msg)
                return
            }
            self.dataModel = model
            self.loadDetailInfo()
            self.showExampleView()
            isDisableEdit = dataModel.status == ResignCertificateStatus.Complete.rawValue
            bottomView.isHidden = isDisableEdit ? true : false
            bottomView.snp.updateConstraints { make in
                make.height.equalTo(self.isDisableEdit ? 0 : 98)
            }
        }
    }
    
    func showExampleView() {
        if dataModel.cert_info.is_show {
            
        } else {
            YHAdopterCardExampleView.exampleView(type: .travel).show()
            let hkPassPort: [String: Any] = ["is_show": true,
                                             "submit": false
                                             ]
            let params: [String: Any] = [
                "hkPassPort": hkPassPort,
                "id": dataModel.id
            ]
            viewModel.submitResignCertificateUpdate(params) { _, _ in
            }
        }
    }
}

private extension YHResignCertificateDetailHkViewController {
    // 1、获取详情信息
    func loadDetailInfo() {
        self.updateData()
    }
    
    // 2、保存旅行证件
    func saveAllTravelCertificate() {
        let hkPassPort: [String: Any] = ["name": "港澳通行证",
                                        "issue_start": self.viewModel.dataModel.cert_info.issue_start,
                                        "issue_end": self.viewModel.dataModel.cert_info.issue_end,
                                        "img_front": urls[0],
                                        "img_back": urls[1],
                                        "validate_start": self.viewModel.dataModel.cert_info.validate_start,
                                        "validate_end": self.viewModel.dataModel.cert_info.validate_end,
                                         "number": self.viewModel.dataModel.cert_info.number,
                                        "address": self.viewModel.dataModel.cert_info.address,
                                        "sign_type": "D",
                                        "submit": true,
                                        "is_show": true]
        let params: [String: Any] = [
            "hkPassPort": hkPassPort,
            "id": dataModel.id
        ]
        viewModel.submitResignCertificateUpdate(params) { success, error in
            if success {
                self.updateBlock?(self.viewModel.dataModel.cert_info)
                YHHUD.flash(message: "保存成功")
                self.navigationController?.popViewController()
                
            } else {
                let msg = error?.errorMsg ?? "保存失败,请重试"
                YHHUD.flash(message: msg)
            }
        }
    }
}

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

        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 = tipsArr
            return cell
        }
    
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHResignCertificateHKTableViewCell.cellReuseIdentifier, for: indexPath) as? YHResignCertificateHKTableViewCell else { return UITableViewCell() }
        cell.firstImageName = "service_adopter_card_travel_front"
        cell.lastImageName = "service_adopter_card_travel_back"
        cell.firstLabelName = "港澳通行证正面"
        cell.lastLabelName = "港澳通行证背面"
        cell.dataModel = dataModel
        cell.failString = failString
        cell.data = data
        cell.urls = urls
        cell.urlBlock = { [weak self] url, index in
            guard let self = self else { return }
            self.urls[index] = url
            if index == 0 {
                self.dataModel.cert_info.img_front = url
            } else {
                self.dataModel.cert_info.img_back = url
            }
            self.viewModel.getPublicImageUrl(url) {[weak self] success, _ in
                guard let self = self else { return }
                guard let url = success else { return }
                if index == 0 {
                    self.viewModel.getHKCardInfoByOcr(url, isBack: 0) { success, result in
                        YHHUD.hide()
                        if success, let result = result {
                            if !result.card_num.isEmpty {
                                self.dataModel.cert_info.number = result.card_num
                            }
                            if !result.issuing_authority.isEmpty {
                                self.dataModel.cert_info.address = result.IssueAddress
                            }
                            if !result.term_begins.isEmpty {
                                self.dataModel.cert_info.issue_start = result.term_begins
                            }
                            if !result.end_of_term.isEmpty {
                                self.dataModel.cert_info.issue_end = result.end_of_term
                            }
                            
                        } else {
                            // OCR 无法识别
                            self.failString = "非逗留(D)签证，请检查文件"
                        }
                        self.updateData()
                    }
                } else {
                    self.viewModel.getHKCardBackInfoByOcr(url, isBack: 1) { success, result in
                        YHHUD.hide()
                        if success, let result = result {
                            if !result.card_num.isEmpty {
                                self.dataModel.cert_info.number = result.card_num
                            }
                            if !result.issuing_authority.isEmpty {
                                self.dataModel.cert_info.address = result.IssueAddress
                            }
                            if !result.back_term_begins.isEmpty {
                                self.dataModel.cert_info.validate_start = result.back_term_begins
                            }
                            if !result.back_end_of_term.isEmpty {
                                self.dataModel.cert_info.validate_end = result.back_end_of_term
                            }
                        } else {
                            // OCR 无法识别
                            self.failString = "非逗留(D)签证，请检查文件"
                        }
                        self.updateData()
                    }
                }
            }
        }
        cell.deleteBlock = { [weak self] url, index in
            guard let self = self else { return }
            self.urls[index] = url
            if index == 0 {
                self.dataModel.cert_info.img_front = ""
            } else {
                self.dataModel.cert_info.img_back = ""
            }
            self.updateData()
        }
        cell.block = {[weak self] model in
            guard let self = self else { return }
            self.viewModel.updatesModel(model)
            self.dataModel = self.viewModel.dataModel
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    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
    }
}
