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

import UIKit

class YHResignCertificatePassportTableViewCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHResignCertificatePassportTableViewCell"
    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 lineView: UIView!
    var exampleButton: UIButton!
    var statusButton: UIButton!
    var reasonLabel: UILabel!
    var frontLabel: UILabel!
    var frontImageButton: YHCardButton!
    var frontDeleteButton: UIButton!
    var activityIndicator: UIActivityIndicatorView!
    var showMessageLabel: UILabel!
    var infoView: UIView!
    var cerInfoLabel: UILabel!
    var cerNumberView: YHItemView!
    var cerSignPlaceView: YHItemView!
    var cardLabel: UILabel!
    var cardBeginView: YHItemView!
    var cardEndView: YHItemView!
    var viewModel: YHBaseViewModel = YHBaseViewModel()
    var firstUrl: String = ""
    var lastUrl: String = ""
    var dataModel: YHResignCertificateModel = YHResignCertificateModel() {
        didSet {
            
            isDisableEdit = dataModel.status == ResignCertificateStatus.Complete.rawValue
            
            reasonLabel.isHidden = (dataModel.status != ResignCertificateStatus.Rejected.rawValue)
            reasonLabel.text = "被驳回原因：" + dataModel.audit_remark
            reasonLabel.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                if dataModel.status != ResignCertificateStatus.Rejected.rawValue {
                    make.height.equalTo(0)
                }
                make.top.equalTo(lineView.snp.bottom).offset(dataModel.status == ResignCertificateStatus.Rejected.rawValue ? 18 : 0)
            }
            
            cardBeginView.isUserInteractionEnabled = !isDisableEdit
            cardEndView.isUserInteractionEnabled = !isDisableEdit
            cerNumberView.isUserInteractionEnabled = !isDisableEdit
            cerSignPlaceView.isUserInteractionEnabled = !isDisableEdit

            if dataModel.status == ResignCertificateStatus.NotUpload.rawValue {
                statusButton.backgroundColor = UIColor.brandMainColor(alpha: 0.08)
                statusButton.setTitle("待上传", for: .normal)
                statusButton.setTitleColor(UIColor.brandMainColor, for: .normal)
                
            } else if dataModel.status == ResignCertificateStatus.Review.rawValue {
                statusButton.backgroundColor = UIColor(hex: 0xFF8000).withAlphaComponent(0.08)
                statusButton.setTitle("审核中", for: .normal)
                statusButton.setTitleColor(UIColor(hex: 0xFF8000), for: .normal)
                
            } else if dataModel.status == ResignCertificateStatus.Complete.rawValue {
                statusButton.backgroundColor = UIColor(hex: 0x3CC694).withAlphaComponent(0.08)
                statusButton.setTitle("已完成", for: .normal)
                statusButton.setTitleColor(UIColor(hex: 0x3CC694), for: .normal)
                
            } else if dataModel.status == ResignCertificateStatus.Rejected.rawValue {
                statusButton.backgroundColor = UIColor(hex: 0xF81D22).withAlphaComponent(0.08)
                statusButton.setTitle("已驳回", for: .normal)
                statusButton.setTitleColor(UIColor(hex: 0xF81D22), for: .normal)
            }
        }
    }
    var isDisableEdit: Bool = false

    var failString: String = "" {
        didSet {
            showMessageLabel.text = failString
        }
    }
    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 {
                infoView.isHidden = true
                infoView.snp.remakeConstraints { make in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(frontImageButton.snp.bottom).offset(0)
                    make.height.equalTo(0)
                    make.bottom.equalToSuperview().offset(-18)
                }
                return
            }
            
            infoView.isHidden = false
            infoView.snp.remakeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(frontImageButton.snp.bottom).offset(0)
                make.bottom.equalToSuperview().offset(0)
            }
            
            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
                    if self.isDisableEdit {
                        self.frontDeleteButton.isHidden = true
                    } else {
                        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 == .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 == .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)
                        }
                    }
                }
            }
        }
    }

    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 = 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)
        }
        
        statusButton = {
            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
            return button
        }()
        centerView.addSubview(statusButton)
        statusButton.snp.makeConstraints { make in
            make.left.equalTo(exampleButton.snp.right).offset(8)
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.height.equalTo(16)
            make.width.equalTo(38)
            make.right.lessThanOrEqualTo(-8)
        }
        
        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)
        }
        
        reasonLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.failColor
            label.textAlignment = .left
            label.numberOfLines = 0
            label.text = "被驳回原因："
            return label
        }()
        centerView.addSubview(reasonLabel)
        reasonLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.height.equalTo(0)
            make.top.equalTo(lineView.snp.bottom).offset(18)
        }
        
        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(reasonLabel.snp.bottom).offset(18)
            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(frontLabel.snp.bottom).offset(12)
            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)
        }
        
        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)
        }
        
        infoView = {
            let view = UIView()
            return view
        }()
        centerView.addSubview(infoView)
        infoView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(frontImageButton.snp.bottom).offset(0)
            make.bottom.equalToSuperview().offset(-18)
        }
    
        showMessageLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor.failColor
            label.text = "无法识别，请核查文件"
            return label
        }()
        infoView.addSubview(showMessageLabel)
        showMessageLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalToSuperview().offset(8)
            make.height.equalTo(20)
        }
        
        // 【证件信息 UI】
        cerInfoLabel =  {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            label.text = "证件信息"
            return label
        }()
        infoView.addSubview(cerInfoLabel)
        cerInfoLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(showMessageLabel.snp.bottom).offset(8)
            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)
            }
        }
        infoView.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)
            }
        }
        infoView.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
        }()
        infoView.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)
            }
        }
        infoView.addSubview(cardBeginView)
        cardBeginView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(cardLabel.snp.bottom).offset(0)
            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.valid_date) {
                    failString = ""
                } else {
                    failString = "有效期不足，需要为\(self.dataModel.valid_date)或以后"
                }
            }
        }
        infoView.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)
            make.bottom.equalTo(0)
        }
    }
    
    @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
    }
}
