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

import UIKit
import AttributedString

enum UploadCertificateDetailType: Int {
    case SmallWhiteNote
    case HongKongCard
}

class YHUploadCertificateDetailVC: YHBaseViewController {
    
    lazy var viewModel: YHUploadCertificateViewModel = {
        let vm = YHUploadCertificateViewModel()
        return vm
    }()
    
    var dataModel: YHUploadCertificateModel = YHUploadCertificateModel() {
        didSet {
        }
    }
    var detailType: UploadCertificateDetailType = .SmallWhiteNote
    var canEditFlag: Bool = true // 已上传状态也可以重新传
    
    lazy var uploadImageVM: YHBaseViewModel = {
        let vm = YHBaseViewModel()
        return vm
    }()
    
    lazy var topImgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "xbt_tips")) //  343 90
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var titleTextView: UITextView  = {
        let lable0 = UITextView()
        lable0.textColor = UIColor.mainTextColor
        lable0.font = UIFont.PFSC_M(ofSize: 17)
        lable0.isScrollEnabled = false
        lable0.isEditable = false
        lable0.isSelectable = false
        return lable0
        
    }()
    
    private lazy var customLabel: UILabel = {
        let lable = UILabel(frame: CGRect(x: 0, y: 0, width: 48, height: 16))
        lable.text = "示例模板"
        lable.font = .PFSC_M(ofSize: 10)
        lable.backgroundColor = UIColor(hex: 0x2F7EF6, transparency: 0.08)
        lable.textColor = .brandMainColor
        lable.layer.cornerRadius = kCornerRadius3
        lable.clipsToBounds = true
        lable.textAlignment = .center
        lable.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapExampleMudel))
        lable.addGestureRecognizer(tap)
        return lable
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    private lazy var cardLabel: UILabel = {
        let lable = UILabel()
        lable.text = "小白条正面"
        lable.font = .PFSC_R(ofSize: 12)
        lable.textColor = UIColor.mainTextColor50
        lable.clipsToBounds = true
        lable.textAlignment = .center
        return lable
    }()
    
    private lazy var cardButton: YHCardButton = {
        let button = YHCardButton()
        button.setContent("card_upload", "点击上传")
        button.setBackgroundImage(UIImage(named: "service_cn_card_front"), for: .normal)
        button.addTarget(self, action: #selector(clickCardButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius4
        button.clipsToBounds = true
        return button
    }()
    
    private lazy var delImageButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setBackgroundImage(UIImage(named: "service_card_delete"), for: .normal)
        button.addTarget(self, action: #selector(clickDelImageBtn), for: .touchUpInside)
        button.isHidden = true
        return button
    }()
    
    private lazy var startDateItem: YHUploadCertificateDateItem = {
        let view = YHUploadCertificateDateItem()
        return view
    }()
    
    private var startDateStr: String = ""
    private var endDateStr: String = ""
    private var uploadImageUrl: String = ""
    
    private lazy var endDateItem: YHUploadCertificateDateItem = {
        let view = YHUploadCertificateDateItem()
        return view
    }()
    
    lazy var bottomView: YHFileListBottomView = {
        let view = YHFileListBottomView()
        view.updateBtnTitle(title: "确认，保存")
        view.block = { _ in
            self.submitInfo()
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
}

// MARK: - 私有方法
private extension YHUploadCertificateDetailVC {
    
    func isAllInfoOK() -> Bool {
        
        if uploadImageUrl.isEmpty {
            var txt = ""
            if detailType == .SmallWhiteNote {
                txt = "上传小白条"
            } else {
                txt = "上传香港身份证"
            }
            YHHUD.flash(message: txt)
            
            return false
        }
        
        if detailType == .SmallWhiteNote {
            
            if startDateStr.isEmpty {
                YHHUD.flash(message: "选择入境日期")
                startDateItem.needCheckMustFlag = true
                endDateItem.needCheckMustFlag = true
                return false
            }
            
            if endDateStr.isEmpty {
                YHHUD.flash(message: "选择逗留截止日期")
                startDateItem.needCheckMustFlag = true
                endDateItem.needCheckMustFlag = true
                return false
            }
            
            // 检验先后 startDateStr < endDateStr
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            
            // 假设我们有两个日期
            if let date1 = dateFormatter.date(from: startDateStr), let date2 = dateFormatter.date(from: endDateStr) {
                // 使用Calendar比较两个日期
                let calendar = Calendar.current

                // 比较结果
                let isDate1Earlier = calendar.compare(date1, to: date2, toGranularity: .day) == .orderedAscending
                if isDate1Earlier {
                    print("date1 在 date2 之前")
                } else {
                    YHHUD.flash(message: "逗留截止日期必须晚于入境日期")
                    return false
                }
            }
        }
        return true
    }
    
    func submitInfo() {
        if isAllInfoOK() {
            if detailType == .SmallWhiteNote {
                submitSmallWhiteBarInfo()
            } else {
                submitHKIDCarInfo()
            }
        }
    }
    
    func submitSmallWhiteBarInfo() {
        
        let params: [String: Any] = [
            "small_white_note_url": uploadImageUrl,
            "small_white_note_validity_start": startDateStr,
            "small_white_note_validity_end": endDateStr,
            
            "user_id": dataModel.user_id,
            "order_id": dataModel.order_id,
            "user_type": dataModel.user_type
        ]
        viewModel.submitSmallWhiteBar(params) { success, error in
            if success {
                YHHUD.flash(message: "保存成功")
                self.navigationController?.popViewController()
            } else {
                let msg = error?.errorMsg ?? "保存失败,请重试"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    func submitHKIDCarInfo() {
        let params: [String: Any] = [
            "idcard_url": uploadImageUrl,
            "user_id": dataModel.user_id,
            "order_id": dataModel.order_id,
            "user_type": dataModel.user_type
        ]
        viewModel.submitIDCardInfo(params) { success, error in
            if success {
                YHHUD.flash(message: "保存成功")
                self.navigationController?.popViewController()
                
            } else {
                let msg = error?.errorMsg ?? "保存失败,请重试"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    @objc func tapItem(gestureRecognizer: UITapGestureRecognizer) {
        
        var title = ""
        var defaultDate = ""
        
        if gestureRecognizer.view == startDateItem {
            title = "选择入境日期"
            defaultDate = startDateStr
        } else {
            title = "选择逗留截止日期"
            defaultDate = endDateStr
        }
        
        YHDatePickView.show(type: .yyyymmdd, title: title, lastIsTaday: false, currentDay: defaultDate) { [weak self] dateStr in
            guard let self = self else { return }
            
            if gestureRecognizer.view == startDateItem {
                startDateStr = dateStr
                startDateItem.updateDate(date: dateStr)
            } else {
                endDateStr = dateStr
                endDateItem.updateDate(date: dateStr)
            }
        }
    }
    
    @objc func clickDelImageBtn() {
        cardButton.setContent("card_upload", "点击上传")
        cardButton.setBackgroundImage(UIImage(named: "service_cn_card_front"), for: .normal)
        delImageButton.isHidden = true
        self.uploadImageUrl = ""
    }
    
    @objc func tapExampleMudel() {
        if detailType == .SmallWhiteNote {
            let view = YHSmallWhiteNoteTemplateView.sheetView()
            view.show()
        } else if detailType == .HongKongCard {
            let view = YHHKCardTemplateView.sheetView()
            view.show()
        }
    }
    
    @objc func clickCardButton() {
        
        if uploadImageUrl.isEmpty {
            // 选择图片
            YHImagePickerView.show {[weak self] image in
                guard let self = self else { return }
                self.cardButton.setContent("card_loading", "上传中")
                self.cardButton.startRotationAnimation()
                self.uploadImageVM.uploadImage(image) {[weak self] success, _ in
                    guard let self = self else { return }
                    self.cardButton.stopRotationAnimation()
                    self.cardButton.setContent("", "")
                    self.delImageButton.isHidden = false
                    
                    guard let url = success else { return }
                    print(url)
                    self.uploadImageUrl = url
                    self.cardButton.setBackgroundImage(image, for: .normal)
                    self.cardButton.isHidden = false
                    
                    if detailType == .SmallWhiteNote {
                        
                        self.viewModel.getPublicImageUrl(url) {[weak self] success, _ in
                            guard let self = self else { return }
                            guard let url = success else { return }
                            
                            // 进行ocr识别
                            self.viewModel.getSmallWhiteBarInfoByOcr(url) { success, _ in
                                if success {
                                    if let tmpModel = self.viewModel.smallWhiteBarInfo {
                                        self.startDateStr = tmpModel.start_time
                                        self.endDateStr = tmpModel.end_time
                                        
                                        self.startDateItem.updateDate(date: self.startDateStr)
                                        self.endDateItem.updateDate(date: self.endDateStr)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {
            showBigImage()
        }
    }
    
    func showBigImage() {
        if !self.uploadImageUrl.isEmpty {
            let vc = YHImageViewController()
            vc.imgString = self.uploadImageUrl
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
    
    func  loadData() {
        let params = [
            "cert_type": (detailType == .SmallWhiteNote) ? 1 : 2, // 证件类型 1-小白条 2-身份证
            "user_id": dataModel.user_id,
            "order_id": dataModel.order_id,
            "user_type": dataModel.user_type
        ] as [String: Any]
        viewModel.getCertificateDetailInfo(params) { success, _ in
            if success {
                self.updateUI()
            }
        }
    }
    
    // 获取数据后进行更新
    func updateUI() {
        if let url = viewModel.certificateDetail?.image_url, !url.isYHEmpty() {
            uploadImageUrl = url
            
            self.viewModel.getPublicImageUrl(url) {[weak self] success, _ in
                guard let self = self else { return }
                guard let url = success else { return }
                self.cardButton.kf.setBackgroundImage(with: URL(string: url), for: .normal, completionHandler: { _ in
                    self.delImageButton.isHidden = false
                })
                self.cardButton.setContent("", "")
            }
        }
        
        if detailType == .SmallWhiteNote {
            startDateStr = viewModel.certificateDetail?.start_time ?? ""
            endDateStr = viewModel.certificateDetail?.end_time ?? ""
            
            startDateItem.updateDate(date: startDateStr)
            endDateItem.updateDate(date: endDateStr)
        }
    }
    
    func setupUI() {
        
        var navTitle = ""
        if detailType == .SmallWhiteNote {
            navTitle = "上传小白条"
            cardLabel.text = "小白条正面"
        } else if detailType == .HongKongCard {
            navTitle = "上传香港身份证"
            cardLabel.text = "香港居民身份证正面"
        }
        
        gk_navTitle = navTitle
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        view.backgroundColor = UIColor.contentBkgColor
        
        view.addSubview(whiteContentView)
        if detailType == .SmallWhiteNote {
            let topImgViewH: CGFloat = 90 * (KScreenWidth - 16 * 2) / 343.0
            view.addSubview(topImgView)
            topImgView.snp.makeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar + kMargin)
                make.left.equalTo(kMargin)
                make.right.equalTo(-kMargin)
                make.height.equalTo(topImgViewH)
            }
            
            whiteContentView.snp.makeConstraints { make in
                make.left.equalTo(kMargin)
                make.right.equalTo(-kMargin)
                make.top.equalTo(topImgView.snp.bottom).offset(14)
                
            }
            
        } else if detailType == .HongKongCard {
            whiteContentView.snp.makeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar + kMargin)
                make.left.equalTo(kMargin)
                make.right.equalTo(-kMargin)
            }
        }
        
        whiteContentView.addSubview(titleTextView)
        titleTextView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-18)
            make.top.equalToSuperview().offset(kMargin)
        }
        
        whiteContentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.top.equalTo(titleTextView.snp.bottom).offset(12)
            make.height.equalTo(1)
        }
        
        whiteContentView.addSubview(cardLabel)
        cardLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.top.equalTo(lineView.snp.bottom).offset(12)
            make.height.equalTo(20)
            make.width.equalTo(160)
        }
        
        if detailType == .SmallWhiteNote {
            
            titleTextView.attributed.text = """
                \("*", .foreground(UIColor.failColor), .font(UIFont.PFSC_M(ofSize: 17)))\(" \(dataModel.apply_name)的第一次赴港激活小白条 ", .foreground(UIColor.mainTextColor), .font(UIFont.PFSC_M(ofSize: 17)))\(.view(customLabel, .original(.center)))
                """
            
            whiteContentView.addSubview(cardButton)
            cardButton.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(18)
                make.top.equalTo(cardLabel.snp.bottom).offset(9)
                make.height.equalTo(99)
                make.width.equalTo(160)
            }
            
            whiteContentView.addSubview(startDateItem)
            startDateItem.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(18)
                make.right.equalToSuperview().offset(-18)
                make.top.equalTo(cardButton.snp.bottom).offset(16)
                make.height.equalTo(YHUploadCertificateDateItem.viewH)
            }
            startDateItem.update(title: "入境日期", isMust: true, hideLineFlag: false)
            
            whiteContentView.addSubview(endDateItem)
            endDateItem.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(18)
                make.right.equalToSuperview().offset(-18)
                make.top.equalTo(startDateItem.snp.bottom)
                make.height.equalTo(YHUploadCertificateDateItem.viewH)
                make.bottom.equalToSuperview()
            }
            endDateItem.update(title: "逗留截止", isMust: true, hideLineFlag: true)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapItem(gestureRecognizer:)))
            startDateItem.addGestureRecognizer(tap)
            
            let tap2 = UITapGestureRecognizer(target: self, action: #selector(tapItem(gestureRecognizer:)))
            endDateItem.addGestureRecognizer(tap2)
        } else if detailType == .HongKongCard {
            titleTextView.attributed.text = """
                \("*", .foreground(UIColor.failColor), .font(UIFont.PFSC_M(ofSize: 17)))\(" \(dataModel.apply_name)的香港身份证 ", .foreground(UIColor.mainTextColor), .font(UIFont.PFSC_M(ofSize: 17)))\(.view(customLabel, .original(.center)))
                """
            
            whiteContentView.addSubview(cardButton)
            cardButton.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(18)
                make.top.equalTo(cardLabel.snp.bottom).offset(9)
                make.height.equalTo(99)
                make.width.equalTo(160)
                make.bottom.equalToSuperview().offset(-kMargin)
            }
        }
        
        // 可编辑
        whiteContentView.addSubview(delImageButton)
        delImageButton.snp.makeConstraints { make in
            make.centerX.equalTo(cardButton.snp.right)
            make.centerY.equalTo(cardButton.snp.top)
            make.height.equalTo(21)
            make.width.equalTo(21)
        }
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(YHFileListBottomView.viewH)
        }
    }
}
