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

import UIKit

class YHResignCertificateDetailViewController: YHBaseViewController {

    lazy var viewModel: YHResignCertificateDetailViewModel = {
        let vm = YHResignCertificateDetailViewModel()
        return vm
    }()
    
    var dataModel: YHResignCertificateModel = YHResignCertificateModel() {
        didSet {
            
            isDisableEdit = dataModel.status == ResignCertificateStatus.Complete.rawValue

            if dataModel.status == ResignCertificateStatus.NotUpload.rawValue {
                self.statusLabel.backgroundColor = UIColor.brandMainColor(alpha: 0.08)
                self.statusLabel.text = "待上传"
                self.statusLabel.textColor = UIColor.brandMainColor
                
            } else if dataModel.status == ResignCertificateStatus.Review.rawValue {
                self.statusLabel.backgroundColor = UIColor(hex: 0xFF8000).withAlphaComponent(0.08)
                self.statusLabel.text = "审核中"
                self.statusLabel.textColor = UIColor(hex: 0xFF8000)
                
            } else if dataModel.status == ResignCertificateStatus.Complete.rawValue {
                self.statusLabel.backgroundColor = UIColor(hex: 0x3CC694).withAlphaComponent(0.08)
                self.statusLabel.text = "已完成"
                self.statusLabel.textColor = UIColor(hex: 0x3CC694)
                
            } else if dataModel.status == ResignCertificateStatus.Rejected.rawValue {
                self.statusLabel.backgroundColor = UIColor(hex: 0xF81D22).withAlphaComponent(0.08)
                self.statusLabel.text = "已驳回"
                self.statusLabel.textColor = UIColor(hex: 0xF81D22)
            }
        }
    }
    var detailType: UploadCertificateDetailType = .SmallWhiteNote
    var canEditFlag: Bool = true // 已上传状态也可以重新传
    var isDisableEdit: Bool = false
    
    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
    }()
    
    private lazy var statusLabel: UILabel = {
        let lable = UILabel(frame: CGRect(x: 0, y: 0, width: 38, 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
        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 lazy var reasonLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.failColor
        label.textAlignment = .left
        label.numberOfLines = 0
        label.text = "被驳回原因："
        return label
    }()
    
    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()
    }
    
    func getResultString(_ data: String) -> String {
        let dateString = data // 原始日期时间字符串
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 设置原始日期时间格式
        if let date = dateFormatter.date(from: dateString) {
            dateFormatter.dateFormat = "yyyy-MM-dd" // 设置目标日期格式
            let convertedDateString = dateFormatter.string(from: date) // 转换日期到目标格式
            return convertedDateString
        }
        return data
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if dataModel.cert_info.is_show {
            
        } else {
            if detailType == .SmallWhiteNote {
                let view = YHSmallWhiteNoteTemplateView.sheetView()
                view.show()
                let smallWhiteBar: [String: Any] = ["is_show": true,
                                                    "submit": false
                                                    ]
                let params: [String: Any] = [
                    "smallWhiteBar": smallWhiteBar,
                    "id": dataModel.id
                ]
                viewModel.submitResignCertificateUpdate(params) { _, _ in
                }
            }
        }
    }
}

// MARK: - 私有方法
private extension YHResignCertificateDetailViewController {
    
    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 smallWhiteBar: [String: Any] = ["name": "小白条",
                                            "small_white_note_url": uploadImageUrl,
                                            "small_white_note_validity_start": startDateStr,
                                            "small_white_note_validity_end": endDateStr,
                                            "submit": true,
                                            "is_show": true
                                            ]
        let params: [String: Any] = [
            "smallWhiteBar": smallWhiteBar,
            "id": dataModel.id
        ]
        viewModel.submitResignCertificateUpdate(params) { success, error in
            if success {
                YHHUD.flash(message: "保存成功")
                self.navigationController?.popViewController()
            } else {
                let msg = error?.errorMsg ?? "保存失败,请重试"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    func submitHKIDCarInfo() {
        let hkIdCard: [String: Any] = ["name": "香港身份证",
                                       "idcard_url": uploadImageUrl,
                                       "submit": true]
        let params: [String: Any] = [
            "hkIdCard": hkIdCard,
            "id": dataModel.id
        ]
        viewModel.submitResignCertificateUpdate(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) {
        if isDisableEdit {
            return
        }
        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() {
        self.updateUI()
    }
    
    // 获取数据后进行更新
    func updateUI() {
        if detailType == .SmallWhiteNote {
            let url = dataModel.cert_info.small_white_note_url
            if !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
                        if self.isDisableEdit {
                            self.delImageButton.isHidden = true
                        } else {
                            self.delImageButton.isHidden = false
                        }
                    })
                    self.cardButton.setContent("", "")
                }
            }
            startDateStr = getResultString(dataModel.cert_info.small_white_note_validity_start)
            endDateStr = getResultString(dataModel.cert_info.small_white_note_validity_end)
            
            startDateItem.updateDate(date: startDateStr)
            endDateItem.updateDate(date: endDateStr)
        } else {
            let url = dataModel.cert_info.idcard_url
            if !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
                        if self.isDisableEdit {
                            self.delImageButton.isHidden = true
                        } else {
                            self.delImageButton.isHidden = false
                        }
                    })
                    self.cardButton.setContent("", "")
                }
            }
        }
        
        bottomView.snp.remakeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(isDisableEdit ? 0 : YHFileListBottomView.viewH)
        }
        
        reasonLabel.text = "被驳回原因：" + dataModel.audit_remark
        reasonLabel.snp.remakeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(dataModel.status == ResignCertificateStatus.Rejected.rawValue ? 12 : 0)
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            if dataModel.status != ResignCertificateStatus.Rejected.rawValue {
                make.height.equalTo(0)
            }
        }
    }
    
    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(8)
        }
        
        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(4)
            make.height.equalTo(1)
        }
        
        whiteContentView.addSubview(reasonLabel)
        reasonLabel.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(12)
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(0)
        }
        
        whiteContentView.addSubview(cardLabel)
        cardLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.top.equalTo(reasonLabel.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.name)的第一次赴港激活小白条 ", .foreground(UIColor.mainTextColor), .font(UIFont.PFSC_M(ofSize: 17)))\(.view(customLabel, .original(.center))) \(.view(statusLabel, .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.name)的香港身份证 ", .foreground(UIColor.mainTextColor), .font(UIFont.PFSC_M(ofSize: 17)))\(.view(customLabel, .original(.center))) \(.view(statusLabel, .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)
        }
    }
}
