//
//  YHResignUploadTravelPassportTableViewCell.swift
//  galaxy
//
//  Created by EDY on 2024/10/14.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResignUploadTravelPassportTableViewCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHResignUploadTravelPassportTableViewCell"
    typealias UrlBlock = (_ url: String, _ index: Int) -> Void
    var urlBlock: UrlBlock?
    var deleteBlock: UrlBlock?
    typealias ItemBlock = (_ model: YHItemModel) -> Void
    var block: ItemBlock?
    var centerView: UIView!
    var titleLabel: UILabel!
    var exampleButton: UIButton!
    var frontLabel: UILabel!
    var frontImageButton: YHCardButton!
    var frontDeleteButton: UIButton!
    var activityIndicator: UIActivityIndicatorView!
    var showMessageLabel: UILabel!
    var cardBeginView: YHItemView!
    var cardEndView: YHItemView!
    var viewModel: YHBaseViewModel = YHBaseViewModel()
    var firstUrl: String = ""
    var lastUrl: String = ""
    var dataModel: YHResignUploadTravelCardDetailModel = YHResignUploadTravelCardDetailModel()
    var failString: String = "" {
        didSet {
            showMessageLabel.text = failString
            if failString.count != 0 {
                centerView.snp.remakeConstraints { make in
                    make.left.equalTo(16)
                    make.right.equalTo(-16)
                    make.top.equalTo(0)
                    make.bottom.equalTo(0)
                }
                cardBeginView.snp.remakeConstraints { make in
                    make.left.equalTo(18)
                    make.top.equalTo(229)
                    make.height.equalTo(52)
                    make.right.equalTo(-18)
                }
            } else {
                centerView.snp.remakeConstraints { make in
                    make.left.equalTo(16)
                    make.right.equalTo(-16)
                    make.top.equalTo(0)
                    make.bottom.equalTo(-20)
                }
                cardBeginView.snp.remakeConstraints { make in
                    make.left.equalTo(18)
                    make.top.equalTo(209)
                    make.height.equalTo(52)
                    make.right.equalTo(-18)
                }
            }
        }
    }
    var firstImageName: String = "" {
        didSet {
            frontImageButton.setBackgroundImage(UIImage(named: firstImageName), for: .normal)
        }
    }

    var firstLabelName: String = "" {
        didSet {
            frontLabel.text = firstLabelName
        }
    }

    var urls: [String]? {
        didSet {
            guard let firstUrl = urls?.first, firstUrl.count != 0 else {
                cardBeginView.isHidden = true
                cardEndView.isHidden = true
                return
            }
            cardBeginView.isHidden = false
            cardEndView.isHidden = false
            self.firstUrl = firstUrl
            self.viewModel.getPublicImageUrl(firstUrl) {[weak self] success, _ 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("", "")
            }
        }
    }

    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 == .id5 {
                    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 == .id6 {
                    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)
                        }
                    }
                }
            }
        }
    }

    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()
            let str = "* " + "护照信息"
            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
            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 = kCornerRadius3
            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(14)
            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)
        }
        
        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(90)
            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)
        }
        
        activityIndicator = {
            let view = UIActivityIndicatorView()
            view.style = .medium
            return view
        }()
        centerView.addSubview(activityIndicator)
        activityIndicator.snp.makeConstraints { make in
            make.center.equalTo(frontImageButton.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)
        }
        
        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(209)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        cardEndView = {
            let view = YHItemView()
            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.latest_validaty_date) {
                    if failString == "有效期不足，需要为\(self.dataModel.latest_validaty_date)或以后" {
                        failString = ""
                    }
                } else {
                    failString = "有效期不足，需要为\(self.dataModel.latest_validaty_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)
        }
    }
    
    @objc func exampleClick() {
        YHAdopterCardExampleView.exampleView(type: .chinaTravel).show()
    }
    
    @objc func frontImageClick() {
        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, _ 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 frontDeleteClick() {
        firstUrl = ""
        frontDeleteButton.isHidden = true
        frontImageButton.setBackgroundImage(UIImage(named: firstImageName), for: .normal)
        frontImageButton.setContent("card_upload", "点击上传")
        if let block = self.deleteBlock {
            block("", 0)
        }
    }
    
    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
    }
}
