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

import UIKit
import AttributedString

enum YHCertificateID: Int {
    case signDate = 0 // 签发日期
    case deadDate = 1 // 届满日期
}

class YHCertificateDateItem {
    var id: YHCertificateID = .signDate
    var isMust: Bool = false
    var title: String = ""
    var value: String = ""
    var placeHolder: String = ""
    var errorTips: String = ""
    var isShowErrorTips: Bool = false
    
    init(id: YHCertificateID, isMust: Bool, title: String, value: String, placeHolder: String, errorTips: String, isShowErrorTips: Bool = false) {
        
        self.id = id
        self.isMust = isMust
        self.title = title
        self.value = value
        self.placeHolder = placeHolder
        self.errorTips = errorTips
        self.isShowErrorTips = isShowErrorTips
    }
    
}

class YHTravelCertificateUploadCell: UITableViewCell {

    static let cellReuseIdentifier = "YHTravelCertificateUploadCell"
    
    var dataModel: YHTravelDocsPreparationDetailItemModel = YHTravelDocsPreparationDetailItemModel()
    let viewModel: YHBaseViewModel = YHBaseViewModel()
    
    var updateBlock: ((_ needCheck: Bool) -> Void)?
    
    // type :Int 证件类型 1-护照 2-中国旅行证 3-港澳通行证 4-存款证明 5-其他
    var templateClick: ((_ type: Int) -> Void)?
    
    lazy var whiteConentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 6.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var titleView: UITextView = {
        let titleView = UITextView()
        titleView.textColor = UIColor.mainTextColor
        titleView.font = UIFont.PFSC_M(ofSize: 16)
        titleView.isScrollEnabled = false
        titleView.isEditable = false
        titleView.isSelectable = false
        return titleView
    }()
    
    lazy var templateButton: UIButton = {
        let btn = UIButton()
        btn.frame = CGRect(x: 0, y: 0, width: 48, height: 16)
        btn.setTitle("示例模板", for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 10)
        btn.setTitleColor(.brandMainColor, for: .normal)
        btn.layer.cornerRadius = kCornerRadius3
        btn.clipsToBounds = true
        btn.backgroundColor = .brandMainColor8
        btn.addTarget(self, action: #selector(didTemplateBtnClicked), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(hex: 0xF0F0F0)
        return view
    }()
    
    lazy var rejectReasonLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textColor = UIColor.failColor
        return label
    }()
    
    lazy var unvalidLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textColor = UIColor.failColor
        return label
    }()
    
    lazy var warmTipsLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.failColor
        
        let a: ASAttributedString = .init("温馨提示：", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.brandMainColor))
        let b: ASAttributedString = .init("具体根据当地出入境规定办理并提交相关证件，如有疑问，可联系银河客服经理咨询", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor(alpha: 0.5)))
        label.attributed.text = a+b
        return label
    }()
    
    lazy var certificateFrontView: YHCardUploadView = {
        let view = YHCardUploadView(frame: .zero)
        view.remakeUploadViewConstraints()
        view.urlBlock = {
            [weak self] url, _ in
            guard let self = self else { return }
            
            self.dataModel.frontUrlDate = Date().timeIntervalSince1970
            if self.dataModel.type == 3 { // 港澳通行证
                  self.dataModel.img_front = url
                  self.getOCR(url: url, isBack: 0)

            } else {
                self.dataModel.img_front = url
                self.dataModel.img_back = url
                self.updateBlock?(false)
            }
        }
        view.deleteBlock = {
            [weak self] _, _ in
            guard let self = self else { return }
            if !self.dataModel.isCanEdit {
                return
            }

            if self.dataModel.type == 3 { // 港澳通行证
                self.dataModel.img_front = ""
                self.dataModel.isOCR_failed = false

            } else {
                self.dataModel.img_front = ""
                self.dataModel.img_back = ""
            }
            self.dataModel.status = 0
            self.dataModel.frontUrlDate = 0
            self.updateBlock?(false)
        }
        return view
    }()
    
    lazy var certificateBackView: YHCardUploadView = {
        let view = YHCardUploadView(frame: .zero)
        view.remakeUploadViewConstraints()
        view.urlBlock = {
            [weak self] url, _ in
            guard let self = self else { return }

            self.dataModel.backUrlDate = Date().timeIntervalSince1970
            if self.dataModel.type == 3 { // 港澳通行证
                self.dataModel.img_back = url
                self.updateBlock?(false)

            } else {
                self.dataModel.img_front = url
                self.dataModel.img_back = url
                self.updateBlock?(false)
            }
        }
        view.deleteBlock = {
            [weak self] _, _  in
            guard let self = self else { return }
    
            if !self.dataModel.isCanEdit {
                return
            }

            if self.dataModel.type == 3 { // 港澳通行证
                self.dataModel.img_back = ""
                
            } else {
                self.dataModel.img_front = ""
                self.dataModel.img_back = ""
            }
            self.dataModel.status = 0
            self.dataModel.backUrlDate = 0
            self.updateBlock?(false)
        }
        return view
    }()
    
    lazy var selectPanelContentView: UIView = {
        let view = UIView()
        return view
    }()
    
    @objc func didTemplateBtnClicked() {
        
        templateClick?(self.dataModel.type)
    }
    
    func updateArr(_ arr: [YHCertificateDateItem]) {
        selectPanelContentView.removeSubviews()
        var lastItemView: YHTravelCertificateItemView?
        for (index, item) in arr.enumerated() {
           
            let itemView = YHTravelCertificateItemView(frame: .zero)
            itemView.lineView.isHidden = index == 0
            // 标题
            var titleStr: ASAttributedString = .init("\(item.title)", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor))
            // 是否必填
            if item.isMust {
                let mustTag: ASAttributedString = .init("*", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.failColor))
                titleStr = mustTag + titleStr
            }
            
            itemView.title =  titleStr
            itemView.placeHolder = item.placeHolder
            itemView.isNeedShowErrorTips = item.isShowErrorTips
            itemView.errorTips = item.errorTips
            itemView.detail = item.value
            itemView.arrowImgView.isHidden = !self.dataModel.isCanEdit
            itemView.clickBlock = {
                [weak self] in
                guard let self = self else { return }
                
                if !self.dataModel.isCanEdit {
                    return
                }
                
                if item.id == .signDate || item.id == .deadDate {
                    YHDatePickView.show(type: .yyyymmdd, currentDay: item.value) {
                        time in
                        
                        if item.id == .signDate {
                            self.dataModel.issue_start = time
                            
                        } else if item.id == .deadDate {
                            self.dataModel.issue_end = time
                        }
                        self.updateBlock?(false)
                    }
                }
            }
            selectPanelContentView.addSubview(itemView)
            itemView.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                if let lastView = lastItemView {
                    make.top.equalTo(lastView.snp.bottom)

                } else {
                    make.top.equalTo(0)
                }
                if index == arr.count-1 {
                    make.bottom.equalTo(0)
                }
            }
            lastItemView = itemView
        }
    }
    
    func updateModel(_ model: YHTravelDocsPreparationDetailItemModel) {
        
        dataModel = model
        
        var title = ""
        var frontTitle = ""
        var backTitle = ""
        
        if model.nationality == "1" { // 国籍为中国
            if model.type == 1 { // 护照
                title = "护照信息"
                frontTitle = "护照资料页"
                
            } else if model.type == 3 { // 港澳通行证
                title = "港澳通行证 (逗留D签注)"
                frontTitle = "港澳通行证正面"
                backTitle = "港澳通行证反面"
            }
            
        } else { // 国籍为外国
            if model.type == 1 { // 护照
                title = "护照信息"
                frontTitle = "护照资料页"
                
            } else if model.type == 2 { // 中国居留许可签证
                title = "中国居留许可签证"
                frontTitle = "中国居留许可签证"
            }
        }
        
        // 标题设置
        var titleStr: ASAttributedString = .init(string: title, .font(UIFont.PFSC_M(ofSize: 16)), .foreground(UIColor.mainTextColor))
        let mustTag: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 16)), .foreground(UIColor.failColor))
        let template: ASAttributedString = " \(.view(templateButton, .original(.center)))"
        
        let isMust = true
        let isShowTemplate = true
        if isMust {
            titleStr = mustTag + titleStr
        }
        if isShowTemplate {
            titleStr += template
        }
        titleView.attributed.text = titleStr
        
        // 证件正反面标题
        certificateFrontView.frontLabel.text = frontTitle
        certificateBackView.frontLabel.text = backTitle
        // 证件正反面图片
        certificateFrontView.state = !model.isCanEdit
        certificateBackView.state = !model.isCanEdit
        
        var frontDefaultImg = "credentials_default_front"
        let  backDefaultImg = "credentials_default_back"
        if model.type == 2 { // 中国居留许可证
            frontDefaultImg = "credentials_default_residence_front"
        }
        
//        certificateFrontView.defaultImageName = frontDefaultImg
//        certificateBackView.defaultImageName = backDefaultImg
//        
//        certificateFrontView.url = model.img_front
//        certificateBackView.url = model.img_back
        
        if !model.img_front.isEmpty, certificateFrontView.url == model.img_front {
            if model.frontUrlDate - Date().timeIntervalSince1970 > 5*60 {
                certificateFrontView.url = model.img_front
            }
        } else {
            certificateFrontView.defaultImageName = frontDefaultImg
            certificateFrontView.url = model.img_front

        }
        
        if !model.img_back.isEmpty, certificateBackView.url == model.img_back {
            if model.backUrlDate - Date().timeIntervalSince1970 > 5*60 {
                certificateBackView.url = model.img_back
            }
        } else {
            certificateBackView.defaultImageName = backDefaultImg
            certificateBackView.url = model.img_back
        }
        
        // 除了港澳通行证需要上传正反面 其他都是上传正面
        certificateBackView.isHidden = model.type != 3
        
        // 是否有证件
        let hasNoCertiInfo = model.img_front.isEmpty && model.img_back.isEmpty
        // 需要显示被拒原因
        model.isNeedShowRejectReason = (model.status == 2)
        let isShowReason = (model.isNeedShowRejectReason && !model.remark.isEmpty)
        rejectReasonLabel.text = isShowReason ? "被驳回原因：" + model.remark : ""
        
        // 只有中国居留许可签证才显示温馨提示
        let isShowWarmTips = (model.type == 2)
        warmTipsLabel.isHidden = !isShowWarmTips
        warmTipsLabel.snp.remakeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(lineView.snp.bottom).offset(isShowWarmTips ? 18.0 : 0)
            if !isShowWarmTips {
                make.height.equalTo(0)
            }
        }
        
        var rejectTop = 18.0
        if isShowReason {
            rejectTop = 8.0
        }
        rejectReasonLabel.snp.remakeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(warmTipsLabel.snp.bottom).offset(isShowReason ? rejectTop : 0)
            make.bottom.equalTo(certificateFrontView.snp.top).offset(-18)
            if !isShowReason {
                make.height.equalTo(0)
            }
        }
        
        let isShowCheck = (model.isNeedCheckCer && !model.checkTips.isEmpty)
        unvalidLabel.text = model.checkTips
        
        unvalidLabel.snp.remakeConstraints { make in
            make.top.equalTo(certificateFrontView.snp.bottom).offset(isShowCheck ? 8 : 0)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            if !isShowCheck {
                make.height.equalTo(0)
            }
        }
        
        selectPanelContentView.snp.remakeConstraints { make in
            var offSet = 16.0
            if isShowCheck {
                if hasNoCertiInfo {
                    offSet = 18.0
                } else {
                    offSet = 8.0
                }
            }
            make.top.equalTo(unvalidLabel.snp.bottom).offset(offSet)
            make.bottom.equalTo(0)
            make.left.equalTo(18)
            make.right.equalTo(-10)
            if hasNoCertiInfo {
                make.height.equalTo(0)
            }
        }
        
        if hasNoCertiInfo {
            updateArr([])
            
        } else {
            
            let item1 = YHCertificateDateItem(id: .signDate, isMust: true, title: "签发日期", value: model.issue_start, placeHolder: "请选择", errorTips: "请选择签发日期", isShowErrorTips: self.dataModel.isNeedCheckDate && model.issue_start.isEmpty)
            let item2 = YHCertificateDateItem(id: .deadDate, isMust: true, title: "届满日期", value: model.issue_end, placeHolder: "请选择", errorTips: "请选择届满日期", isShowErrorTips: self.dataModel.isNeedCheckDate && model.issue_end.isEmpty)
            let arr: [YHCertificateDateItem] = [item1, item2]
            updateArr(arr)
        }
        
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        contentView.addSubview(whiteConentView)
        whiteConentView.addSubview(titleView)
        whiteConentView.addSubview(lineView)
        whiteConentView.addSubview(rejectReasonLabel)
        whiteConentView.addSubview(certificateFrontView)
        whiteConentView.addSubview(certificateBackView)
        whiteConentView.addSubview(warmTipsLabel)
        whiteConentView.addSubview(unvalidLabel)
        whiteConentView.addSubview(selectPanelContentView)
        
        whiteConentView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        titleView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(titleView.snp.bottom).offset(4)
            make.height.equalTo(0.5)
        }
        
        warmTipsLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(lineView.snp.bottom).offset(18)
            make.height.equalTo(0)
        }

        rejectReasonLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(lineView.snp.bottom).offset(18)
            make.bottom.equalTo(certificateFrontView.snp.top).offset(-18)
        }
        
        certificateFrontView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(certificateBackView.snp.left).offset(0)
            make.width.equalTo(certificateBackView.snp.width)
            make.height.equalTo(122)
        }
        
        certificateBackView.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.top.equalTo(certificateFrontView)
            make.height.equalTo(122)
        }
        
        unvalidLabel.snp.makeConstraints { make in
            make.top.equalTo(certificateFrontView.snp.bottom).offset(8)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        selectPanelContentView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-10)
            make.top.equalTo(unvalidLabel.snp.bottom).offset(8)
            make.bottom.equalTo(0)
        }
        
    }
}

extension YHTravelCertificateUploadCell {
    
    func getOCR(url: String, isBack: Int) {
        
        self.viewModel.getPublicImageUrl(url) {
            
            [weak self] success, _ in
            guard let self = self else { return }
            guard let url = success else { return }
            
            // 进行ocr识别
            YHHUD.show(.progress(message: "识别中..."))
            
            if isBack == 1 {
                self.viewModel.getHKCardBackInfoByOcr(url, isBack: isBack) { success, result in
                    YHHUD.hide()
                    if success, let result = result {
                        self.dataModel.isOCR_failed = false
                        if !result.term_begins.isEmpty {
                            self.dataModel.issue_start = result.term_begins
                        }
                        if !result.end_of_term.isEmpty {
                            self.dataModel.issue_end = result.end_of_term
                        }
                        self.updateBlock?(true)
                    } else {
                        // OCR 无法识别
                        self.dataModel.isOCR_failed = true
                        self.updateBlock?(true)
                    }
                }
                
            } else {
                
                self.viewModel.getHKCardInfoByOcr(url, isBack: isBack) { success, result in
                    YHHUD.hide()
                    if success, let result = result {
                        if !result.term_begins.isEmpty {
                            self.dataModel.issue_start = result.term_begins
                        }
                        if !result.end_of_term.isEmpty {
                            self.dataModel.issue_end = result.end_of_term
                        }
                        self.updateBlock?(true)
                    } else {
                        // OCR 无法识别
                        self.dataModel.isOCR_failed = true
                        self.updateBlock?(true)
                    }
                }
            }
        }
    }

}
