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

import UIKit

class YHResignUploadTravelHKTableViewCell: UITableViewCell {
    static let cellReuseIdentifier = "YHResignUploadTravelHKTableViewCell"
    
    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 backSurfaceLabel: UILabel!
    var frontImageButton: YHCardButton!
    var backSurfaceImageButton: YHCardButton!
    var frontDeleteButton: UIButton!
    var backSurfaceDeleteButton: UIButton!
    var activityIndicator: UIActivityIndicatorView!
    var showMessageLabel: UILabel!
    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: 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)
                }
                cardLabel.snp.remakeConstraints { make in
                    make.left.equalTo(18)
                    make.right.equalTo(-18)
                    make.top.equalTo(229)
                    make.height.equalTo(20)
                }
            } else {
                centerView.snp.remakeConstraints { make in
                    make.left.equalTo(16)
                    make.right.equalTo(-16)
                    make.top.equalTo(0)
                    make.bottom.equalTo(-12)
                }
                cardLabel.snp.makeConstraints { make in
                    make.left.equalTo(18)
                    make.right.equalTo(-18)
                    make.top.equalTo(217)
                    make.height.equalTo(20)
                }
            }
        }
    }
    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 {
                    cardLabel.isHidden = true
                    signLabel.isHidden = true
                    cardBeginView.isHidden = true
                    cardEndView.isHidden = true
                    signBeginView.isHidden = true
                    signEndView.isHidden = true
                    return
                }
                self.lastUrl = lastUrl
                self.viewModel.getPublicImageUrl(lastUrl) {[weak self] success, _ 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("", "")
                }
                cardLabel.isHidden = false
                signLabel.isHidden = false
                cardBeginView.isHidden = false
                cardEndView.isHidden = false
                signBeginView.isHidden = false
                signEndView.isHidden = false
                return
            }
            cardLabel.isHidden = false
            signLabel.isHidden = false
            cardBeginView.isHidden = false
            cardEndView.isHidden = false
            signBeginView.isHidden = false
            signEndView.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("", "")
            }
            guard let lastUrl = urls?.last, lastUrl.count != 0 else { return }
            self.lastUrl = lastUrl
            self.viewModel.getPublicImageUrl(lastUrl) {[weak self] success, _ 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 == .id1 {
                    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 == .id2 {
                    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 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)
                        }
                    }
                }
            }
        }
    }

    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)
        
        titleLabel = {
            let label = UILabel()
            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
            return label
        }()
        centerView.addSubview(titleLabel)
        
        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)
        
        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)
        
        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)
        
        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)
        
        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)
        
        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)

        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)
        
        activityIndicator = {
            let view = UIActivityIndicatorView()
            view.style = .medium
            return view
        }()
        centerView.addSubview(activityIndicator)
        
        showMessageLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.failColor
            label.text = "无法识别，请核查文件"
            return label
        }()
        centerView.addSubview(showMessageLabel)
        
        cardLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "卡片有效期"
            return label
        }()
        centerView.addSubview(cardLabel)
        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)
        
        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)
            }
        }
        centerView.addSubview(cardEndView)
        
        signLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "签注有效期"
            return label
        }()
        centerView.addSubview(signLabel)
        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)
        
        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.latest_validaty_date) {
                    if failString == "签注有效期不足，需要为\(self.dataModel.latest_validaty_date)或以后" {
                        failString = ""
                    }
                } else {
                    failString = "签注有效期不足，需要为\(self.dataModel.latest_validaty_date)或以后"
                }
            }
        }
        centerView.addSubview(signEndView)
        makeConstraint()
    }
    
    func makeConstraint() {
        centerView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
        }
        
        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.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(self.snp.centerX)
            make.top.equalTo(70)
            make.height.equalTo(20)
        }
        
        backSurfaceLabel.snp.makeConstraints { make in
            make.right.equalTo(-18)
            make.left.equalTo(self.snp.centerX)
            make.top.equalTo(70)
            make.height.equalTo(20)
        }
        
        frontImageButton.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(102)
            make.height.equalTo(90)
            make.width.equalTo(CGFloat(147).fix)
        }
        
        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.snp.makeConstraints { make in
            make.right.equalTo(-18)
            make.top.equalTo(102)
            make.height.equalTo(90)
            make.width.equalTo(CGFloat(147).fix)
        }

        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.snp.makeConstraints { make in
            make.center.equalTo(backSurfaceImageButton.snp.center)
            make.height.equalTo(25)
            make.width.equalTo(25)
        }
        
        showMessageLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(201)
            make.height.equalTo(20)
        }
        
        cardLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(229)
            make.height.equalTo(20)
        }
        
        cardBeginView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardLabel.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        cardEndView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardBeginView.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        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.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(signLabel.snp.bottom)
            make.height.equalTo(52)
            make.right.equalTo(-18)
        }
        
        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() {
        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 backSurfaceImageClick() {
        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, _ 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
    }
}
