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

import UIKit
import AttributedString

class YHResignCertificateHKTableViewCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHResignCertificateHKTableViewCell"
    
    typealias UrlBlock = (_ url: String, _ index: Int) -> ()
    var urlBlock: UrlBlock?
    var deleteBlock: UrlBlock?
    typealias ItemBlock = (_ model: YHItemModel) -> ()
    var block: ItemBlock?
    var centerView: UIView!
    var titleLabel: UILabel!
    var exampleButton: UIButton!
    var frontLabel: UILabel!
    var backSurfaceLabel: UILabel!
    var frontImageButton: YHCardButton!
    var backSurfaceImageButton: YHCardButton!
    var frontDeleteButton: UIButton!
    var backSurfaceDeleteButton: UIButton!
    var activityIndicator: UIActivityIndicatorView!
    var showMessageLabel: UILabel!
    var cerInfoLabel: UILabel!
    var cerNumberView: YHItemView!
    var cerSignPlaceView: YHItemView!
    var cardLabel: UILabel!
    var signLabel: UILabel!
    var cardBeginView: YHItemView!
    var cardEndView: YHItemView!
    var signBeginView: YHItemView!
    var signEndView: YHItemView!
    var viewModel: YHBaseViewModel = YHBaseViewModel()
    var firstUrl: String = ""
    var lastUrl: String = ""
    var dataModel: YHResignCertificateModel = YHResignCertificateModel()
    var failString: String = "" {
        didSet {
            showMessageLabel.text = failString
        }
    }
    var firstImageName: String = "" {
        didSet {
            frontImageButton.setBackgroundImage(UIImage(named: firstImageName), for: .normal)
        }
    }
    var lastImageName: String = "" {
        didSet {
            backSurfaceImageButton.setBackgroundImage(UIImage(named: lastImageName), for: .normal)
        }
    }
    var firstLabelName: String = "" {
        didSet {
            frontLabel.text = firstLabelName
        }
    }
    var lastLabelName: String = "" {
        didSet {
            backSurfaceLabel.text = lastLabelName
        }
    }
    var urls: [String]? {
        didSet {
            guard let firstUrl = urls?.first, firstUrl.count != 0 else {
                guard let lastUrl = urls?.last, lastUrl.count != 0 else {
                    cerInfoLabel.isHidden = true
                    cerNumberView.isHidden = true
                    cerSignPlaceView.isHidden = true
                    cardLabel.isHidden = true
                    signLabel.isHidden = true
                    cardBeginView.isHidden = true
                    cardEndView.isHidden = true
                    signBeginView.isHidden = true
                    signEndView.isHidden = true
                    showMessageLabel.isHidden = true
                    return
                }
                cerInfoLabel.isHidden = false
                cerNumberView.isHidden = false
                cerSignPlaceView.isHidden = false
                cardLabel.isHidden = false
                signLabel.isHidden = false
                cardBeginView.isHidden = false
                cardEndView.isHidden = false
                signBeginView.isHidden = false
                signEndView.isHidden = false
                showMessageLabel.isHidden = false

                self.lastUrl = lastUrl
                self.viewModel.getPublicImageUrl(lastUrl) {[weak self] success, error in
                    guard let self = self else { return }
                    guard let url = success else { return }
                    self.backSurfaceImageButton.kf.setBackgroundImage(with: URL(string: url), for: .normal, completionHandler:  { _ in
                        self.backSurfaceDeleteButton.isHidden = false
                    })
                    self.backSurfaceImageButton.setContent("", "")
                }
                return
            }
            cerInfoLabel.isHidden = false
            cerNumberView.isHidden = false
            cerSignPlaceView.isHidden = false
            cardLabel.isHidden = false
            signLabel.isHidden = false
            cardBeginView.isHidden = false
            cardEndView.isHidden = false
            signBeginView.isHidden = false
            signEndView.isHidden = false
            showMessageLabel.isHidden = false

            self.firstUrl = firstUrl
            self.viewModel.getPublicImageUrl(firstUrl) {[weak self] success, error in
                guard let self = self else { return }
                guard let url = success else { return }
                self.frontImageButton.kf.setBackgroundImage(with: URL(string: url), for: .normal, completionHandler:  { _ in
                    self.frontDeleteButton.isHidden = false
                })
                self.frontImageButton.setContent("", "")
            }
            guard let lastUrl = urls?.last, lastUrl.count != 0 else { return }
            self.lastUrl = lastUrl
            self.viewModel.getPublicImageUrl(lastUrl) {[weak self] success, error in
                guard let self = self else { return }
                guard let url = success else { return }
                self.backSurfaceImageButton.kf.setBackgroundImage(with: URL(string: url), for: .normal, completionHandler:  { _ in
                    self.backSurfaceDeleteButton.isHidden = false
                })
                self.backSurfaceImageButton.setContent("", "")
            }
            
        }
    }

    var data: [YHItemModel] = [] {
        didSet {
            for item in data {
                let isShow = item.isShowPrompts ?? false
                let message = item.message ?? ""
                let isNeed = item.isNeed ?? false
                if item.id == .id38 { // 卡片有效期签发日期
                    cardBeginView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        cardBeginView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        cardBeginView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                }
                if item.id == .id39 { // 卡片有效期届满日期
                    cardEndView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        cardEndView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        cardEndView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                    if self.compareDates(dateString1: item.message ?? "", dateString2: self.dataModel.valid_date) {
                        failString = ""
                    } else {
                        if item.message != "" {
                            failString = "卡片有效期不足，需要为\(self.dataModel.valid_date)或以后"
                        }
                    }
                }
                if item.id == .id3 { // 签注有效期开始时间
                    signBeginView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        signBeginView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        signBeginView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                }
                if item.id == .id4 {  // 签注有效期到期时间
                    signEndView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        signEndView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        signEndView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                    if self.compareDates(dateString1: item.message ?? "", dateString2: self.dataModel.sign_valid_date) {
                        if failString == "签注有效期不足，需要为\(self.dataModel.sign_valid_date)或以后" {
                            failString = ""
                        }
                    } else {
                        if failString == "卡片有效期不足，需要为\(self.dataModel.valid_date)或以后" {
                            
                        } else {
                            if item.message != "" {
                                failString = "签注有效期不足，需要为\(self.dataModel.sign_valid_date)或以后"
                            }
                        }
                    }
                }
                
                if item.id == .id36 { // 证件信息 证件号码
                    cerNumberView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        cerNumberView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        cerNumberView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                }
                
                if item.id == .id37 { // 证件信息 签发地
                    cerSignPlaceView.dataSource = item
                    if isShow && message.count == 0 && isNeed {
                        cerSignPlaceView.snp.updateConstraints { make in
                            make.height.equalTo(72)
                        }
                    } else {
                        cerSignPlaceView.snp.updateConstraints { make in
                            make.height.equalTo(52)
                        }
                    }
                }
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius6
            return view
        }()
        
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        titleLabel = {
            let label = UILabel()
//            label.font = UIFont.PFSC_M(ofSize: 17)
            let str = "* " + "港澳通行证 (逗留D签注)"
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_M(ofSize: 17),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            let starRange = NSRange(location: 0, length: 2)
            questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
            label.attributedText = questionAttrStr
//            label.textColor = UIColor.mainTextColor
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
        }
        
        exampleButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.08)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 10)
            button.contentHorizontalAlignment = .center
            button.setTitle("示例模板", for: .normal)
            button.setTitleColor( UIColor.brandMainColor, for: .normal)
            button.layer.cornerRadius = kCornerRadius2
            button.addTarget(self, action: #selector(exampleClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(exampleButton)
        exampleButton.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(8)
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.height.equalTo(16)
            make.width.equalTo(48)
        }
        
        let lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(52)
            make.height.equalTo(1)
        }
        
        frontLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.mainTextColor50
            label.text = "证件页1"
            label.textAlignment = .center
            return label
        }()
        centerView.addSubview(frontLabel)
        frontLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(self.snp.centerX)
            make.top.equalTo(70)
            make.height.equalTo(20)
        }
        
        backSurfaceLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.mainTextColor50
            label.textAlignment = .center
            label.text = "证件页2"
            return label
        }()
        centerView.addSubview(backSurfaceLabel)
        backSurfaceLabel.snp.makeConstraints { make in
            make.right.equalTo(-18)
            make.left.equalTo(self.snp.centerX)
            make.top.equalTo(70)
            make.height.equalTo(20)
        }
        
        frontImageButton = {
            let button = YHCardButton()
            button.setContent("card_upload", "点击上传")
            button.setBackgroundImage(UIImage(named: firstImageName), for: .normal)
            button.addTarget(self, action: #selector(frontImageClick), for: .touchUpInside)
            button.layer.cornerRadius = 4
            button.clipsToBounds = true
            return button
        }()
        centerView.addSubview(frontImageButton)
        frontImageButton.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(102)
            make.height.equalTo(91)
            make.width.equalTo(CGFloat(147).fix)
        }
        
        frontDeleteButton = {
            let button = UIButton(type: .custom)
            button.setBackgroundImage(UIImage(named: "service_card_delete"), for: .normal)
            button.addTarget(self, action: #selector(frontDeleteClick), for: .touchUpInside)
            button.isHidden = true
            return button
        }()
        centerView.addSubview(frontDeleteButton)
        frontDeleteButton.snp.makeConstraints { make in
            make.centerX.equalTo(frontImageButton.snp.right)
            make.centerY.equalTo(frontImageButton.snp.top)
            make.height.equalTo(21)
            make.width.equalTo(21)
        }
        
        backSurfaceImageButton = {
            let button = YHCardButton()
            button.setContent("card_upload", "点击上传")
            button.setBackgroundImage(UIImage(named: lastImageName), for: .normal)
            button.addTarget(self, action: #selector(backSurfaceImageClick), for: .touchUpInside)
            button.layer.cornerRadius = 4
            button.clipsToBounds = true
            return button
        }()
        centerView.addSubview(backSurfaceImageButton)
        backSurfaceImageButton.snp.makeConstraints { make in
            make.right.equalTo(-18)
            make.top.equalTo(102)
            make.height.equalTo(91)
            make.width.equalTo(CGFloat(147).fix)
        }

        backSurfaceDeleteButton = {
            let button = UIButton(type: .custom)
            button.setBackgroundImage(UIImage(named: "service_card_delete"), for: .normal)
            button.addTarget(self, action: #selector(backSurfaceDeleteClick), for: .touchUpInside)
            button.isHidden = true
            return button
        }()
        centerView.addSubview(backSurfaceDeleteButton)
        backSurfaceDeleteButton.snp.makeConstraints { make in
            make.centerX.equalTo(backSurfaceImageButton.snp.right)
            make.centerY.equalTo(backSurfaceImageButton.snp.top)
            make.height.equalTo(21)
            make.width.equalTo(21)
        }
        
        activityIndicator = {
            let view = UIActivityIndicatorView()
            view.style = .medium
            return view
        }()
        centerView.addSubview(activityIndicator)
        activityIndicator.snp.makeConstraints { make in
            make.center.equalTo(backSurfaceImageButton.snp.center)
            make.height.equalTo(25)
            make.width.equalTo(25)
        }
        
        showMessageLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.failColor
            label.text = "无法识别，请核查文件"
            return label
        }()
        centerView.addSubview(showMessageLabel)
        showMessageLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(201)
            make.height.equalTo(20)
        }
        
        // 【证件信息 UI】
        cerInfoLabel =  {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "证件信息"
            return label
        }()
        centerView.addSubview(cerInfoLabel)
        cerInfoLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(229)
            make.height.equalTo(20)
        }
        cerNumberView = {
            let view = YHItemView()
            let line = UIView()
            line.backgroundColor = UIColor.separatorColor
            view.addSubview(line)
            line.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            return view
        }()
        cerNumberView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
            }
        }
        centerView.addSubview(cerNumberView)
        cerNumberView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cerInfoLabel.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        cerSignPlaceView = {
            let view = YHItemView()
            let line = UIView()
            line.backgroundColor = UIColor.separatorColor
            view.addSubview(line)
            line.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            return view
        }()
        cerSignPlaceView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
            }
        }
        centerView.addSubview(cerSignPlaceView)
        cerSignPlaceView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cerNumberView.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        // 【卡片有效期 UI】
        cardLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "卡片有效期"
            return label
        }()
        centerView.addSubview(cardLabel)
        cardLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(cerSignPlaceView.snp.bottom).offset(24)
            make.height.equalTo(20)
        }
        cardBeginView = {
            let view = YHItemView()
            let line = UIView()
            line.backgroundColor = UIColor.separatorColor
            view.addSubview(line)
            line.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            return view
        }()
        cardBeginView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
            }
        }
        centerView.addSubview(cardBeginView)
        cardBeginView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardLabel.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        cardEndView = {
            let view = YHItemView()
            let line = UIView()
            line.backgroundColor = UIColor.separatorColor
            view.addSubview(line)
            line.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            return view
        }()
        cardEndView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
                if self.compareDates(dateString1: model.message ?? "", dateString2: self.dataModel.valid_date) {
                    if failString == "卡片有效期不足，需要为\(self.dataModel.valid_date)或以后" {
                        failString = ""
                    }
                } else {
                    failString = "卡片有效期不足，需要为\(self.dataModel.valid_date)或以后"
                }
            }
        }
        centerView.addSubview(cardEndView)
        cardEndView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardBeginView.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        // 【签注有效期 UI】
        signLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "签注有效期"
            return label
        }()
        centerView.addSubview(signLabel)
        signLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardEndView.snp.bottom).offset(24)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        signBeginView = {
            let view = YHItemView()
            let line = UIView()
            line.backgroundColor = UIColor.separatorColor
            view.addSubview(line)
            line.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            }
            return view
        }()
        signBeginView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
            }
        }
        centerView.addSubview(signBeginView)
        signBeginView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(signLabel.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        signEndView = {
            let view = YHItemView()
            return view
        }()
        signEndView.block = {[weak self] model in
            guard let self = self else { return }
            if let block = self.block {
                block(model)
                if self.compareDates(dateString1: model.message ?? "", dateString2: self.dataModel.sign_valid_date) {
                    if failString == "签注有效期不足，需要为\(self.dataModel.sign_valid_date)或以后" {
                        failString = ""
                    }
                } else {
                    failString = "签注有效期不足，需要为\(self.dataModel.sign_valid_date)或以后"
                }
            }
        }
        centerView.addSubview(signEndView)
        signEndView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(signBeginView.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
    }
    
    @objc func exampleClick() {
        YHAdopterCardExampleView.exampleView(type: .travel).show()
    }
    
    @objc func frontImageClick() {
        self.endEditing(true)
        if firstUrl.count != 0 {
            let vc = YHImageViewController()
            vc.imgString = firstUrl
            UIViewController.current?.navigationController?.pushViewController(vc)
            return
        }
        YHImagePickerView.show() {[weak self] image in
            guard let self = self else { return }
            self.frontImageButton.setContent("card_loading", "上传中")
            self.frontImageButton.startRotationAnimation()
            self.viewModel.uploadImage(image) {[weak self] success, error in
                guard let self = self else { return }
                self.frontImageButton.stopRotationAnimation()
                self.frontImageButton.setContent("", "")
                
                guard let url = success else { return }
                self.frontImageButton.setBackgroundImage(image, for: .normal)
                self.frontDeleteButton.isHidden = false
                if let block = self.urlBlock {
                    block(url, 0)
                }
            }
        }
    }
    
    @objc func backSurfaceImageClick() {
        self.endEditing(true)
        if lastUrl.count != 0 {
            let vc = YHImageViewController()
            vc.imgString = lastUrl
            UIViewController.current?.navigationController?.pushViewController(vc)
            return
        }
        YHImagePickerView.show() {[weak self] image in
            guard let self = self else { return }
            self.backSurfaceImageButton.setContent("card_loading", "上传中")
            self.backSurfaceImageButton.startRotationAnimation()
            self.viewModel.uploadImage(image) {[weak self] success, error in
                guard let self = self else { return }
                self.backSurfaceImageButton.stopRotationAnimation()
                self.backSurfaceImageButton.setContent("", "")
                
                guard let url = success else { return }
                self.backSurfaceImageButton.setBackgroundImage(image, for: .normal)
                self.backSurfaceDeleteButton.isHidden = false
                if let block = self.urlBlock {
                    block(url, 1)
                }
            }
        }
    }
    
    @objc func frontDeleteClick() {
        firstUrl = ""
        frontDeleteButton.isHidden = true
        frontImageButton.setBackgroundImage(UIImage(named: firstImageName), for: .normal)
        frontImageButton.setContent("card_upload", "点击上传")
        if let block = self.deleteBlock {
            block("", 0)
        }
    }
    
    @objc func backSurfaceDeleteClick() {
        lastUrl = ""
        backSurfaceDeleteButton.isHidden = true
        backSurfaceImageButton.setBackgroundImage(UIImage(named: lastImageName), for: .normal)
        backSurfaceImageButton.setContent("card_upload", "点击上传")
        if let block = self.deleteBlock {
            block("", 1)
        }
    }
    
    func compareDates(dateString1: String, dateString2: String) -> Bool {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        guard let date1 = dateFormatter.date(from: dateString1),
              let date2 = dateFormatter.date(from: dateString2) else {
            return false
        }
        
        if date1 < date2 {
            return false
        }
        return true
    }
}
