//
//  YHPrincipleUploadStatusCell.swift
//  galaxy
//
//  Created by edy on 2024/8/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString
import IQKeyboardManagerSwift

enum YHPrincipleUploadStatus : Int {
    // 审核中
    case review = 0
    // 已通过
    case pass = 1
    // 已驳回
    case rejected = 2
    // 待上传
    case preUpload = 3
    // // 已邮件港府
    case mail = 4
}

class YHPrincipleUploadStatusCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHPrincipleUploadStatusCell"

    var itemModel:YHPrincipleAgreementModel?
    var items: [YHPrincipleContentUrlModel] = []
    var expandClick:((Bool)->())?
    var fileEditBlock:((YHPrincipleContentUrlModel, Int) -> ())?
    var fileClickBlock:((YHPrincipleContentUrlModel, Int) -> ())?
    var uploadBtnClick:((YHPrincipleAgreementModel?)->())?
    var templateBtnClick:((YHPrincipleAgreementModel?)->())?

    let viewModel = YHPrincleViewModel()
    
    lazy var whiteView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 6.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var titleLabel : UITextView  = {
        let label = UITextView()
        label.textColor = UIColor(hex: 0x4E4E4E)
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.isScrollEnabled = false
        label.isEditable = false
        label.isSelectable = false
        return label
    }()
    
    lazy var statusLabel: UILabel = {
        let statusLabel = UILabel()
        statusLabel.textAlignment = .center
        statusLabel.font = UIFont.PFSC_M(ofSize:10)
        statusLabel.layer.cornerRadius = kCornerRadius3
        statusLabel.clipsToBounds = true
        statusLabel.frame = CGRectMake(0, 0, 38, 16)
        return statusLabel
    }()
    
    lazy var templateButton: UIButton = {
        let btn = UIButton()
        btn.frame = CGRect(x: 0, y: 0, width: 66, height: 27)
        btn.setTitle("获取模板", for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 12)
        btn.setTitleColor(.brandMainColor, for: .normal)
        btn.layer.cornerRadius = kCornerRadius3
        btn.clipsToBounds = true
        btn.backgroundColor = UIColor.init(hex: 0xF0F4FB)
        btn.addTarget(self, action: #selector(didTemplateBtnClicked), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var lineView: UIView = {
        let line = UIView()
        line.backgroundColor = .separatorColor
        return line
    }()
    
    lazy var rejectReasonLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textColor = UIColor.failColor
        return label
    }()
    
    lazy var grayLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textColor = UIColor.labelTextColor2
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        var label = UILabel()
        label.numberOfLines = 0
        return label
    }()
    
    lazy var uploadBtn: UIButton = {
        let btn = UIButton(frame: CGRectMake(0, 0, KScreenWidth-36.0*2.0, 45.0))
        btn.setTitle("上传".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.init(hex: 0x3570DC), for: .normal)
        btn.iconInLeft(spacing: 6)
        btn.setImage(UIImage(named: "form_add_info"), for: .normal)
        btn.addTarget(self, action: #selector(didClickUploadBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var dotLineLayer:CAShapeLayer = {
        let borderLayer =  CAShapeLayer()
        borderLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: KScreenWidth-36.0*2, height: 45.0), cornerRadius: 3.0).cgPath
        borderLayer.lineWidth = 1
        //[数组第一个数字表示单个虚线长度，第二个数字表示间隔]
        borderLayer.lineDashPattern = [3,1]  as [NSNumber]?
        //前边是虚线的长度，后边是虚线之间空隙的长度
        borderLayer.lineDashPhase = 0.1
        //实线边框
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = UIColor.brandMainColor.cgColor
        return borderLayer
    }()
    
    lazy var bottomRedTipsLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.failColor
        return label
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style:.grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(YHPrincipleUploadFileCell.self, forCellReuseIdentifier: YHPrincipleUploadFileCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        return tableView
    }()
    
    @objc func didTemplateBtnClicked() {
        templateBtnClick?(self.itemModel)
    }
    
    @objc func didClickUploadBtn() {
        uploadBtnClick?(self.itemModel)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    func setupUI() {
        self.selectionStyle = .none
        self.contentView.backgroundColor = .clear
        self.backgroundColor = .clear
    }
    
    func updateModel(_ model: YHPrincipleAgreementModel) {
        
        itemModel = model
        items.removeAll()
        items.append(contentsOf: model.content_url)

        contentView.removeSubviews()
        self.dotLineLayer.removeFromSuperlayer()
        
        contentView.addSubview(whiteView)
        whiteView.addSubview(titleLabel)
        whiteView.addSubview(templateButton)
        whiteView.addSubview(lineView)
        whiteView.addSubview(rejectReasonLabel)
        whiteView.addSubview(grayLabel)
        whiteView.addSubview(detailLabel)
        whiteView.addSubview(tableView)
        whiteView.addSubview(uploadBtn)
        whiteView.addSubview(bottomRedTipsLabel)
        tableView.reloadData()
        
        // 标题
        var titleStr: ASAttributedString = .init("\(self.getTitle(type: model.customType))", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.mainTextColor))
        // 是否必填
        if model.isMust {
            let mustTag: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.failColor))
            titleStr = mustTag + titleStr
        }
        // 审核状态
        if model.isNeedUploadStatus {
            self.statusLabel.text = self.getUploadStatusText(status: model.check_status)
            let width = model.check_status == YHPrincipleUploadStatus.mail.rawValue ? 58.0 : 38.0
            self.statusLabel.frame = CGRect(x: 0, y: 0, width: width, height: 16)
            self.statusLabel.textColor = self.getUploadTitleColor(status: model.check_status)
            self.statusLabel.backgroundColor = self.getUploadBgColor(status: model.check_status)
            let status: ASAttributedString = " \(.view(self.statusLabel, .original(.center)))"
            titleStr = titleStr + status
        }
        titleLabel.attributed.text = titleStr
        
        // 模板显示
        templateButton.isHidden = !model.isNeedTemplate
        
        // 红色已驳回原因
        let reason = "驳回原因: " + model.audit_content
        rejectReasonLabel.text = reason
        rejectReasonLabel.isHidden = model.audit_content.isEmpty || model.check_status != YHPrincipleUploadStatus.rejected.rawValue
        
        // 灰色提示
        model.tips = self.getTips(type: model.customType)
        grayLabel.text = model.tips
        grayLabel.isHidden = model.tips.isEmpty
        
        // 富文本
        let detail = self.getDetailText(type: model.customType)
        detailLabel.attributed.text = detail
        // 上传按钮显示
        uploadBtn.isHidden = !model.isNeedUploadBtn
        if model.isNeedUploadBtn {
            uploadBtn.layer.addSublayer(self.dotLineLayer)
        }
        
        // 底部红色提示
        bottomRedTipsLabel.text = self.getCheckTips(type: model.customType)
        bottomRedTipsLabel.isHidden = !model.isShowRedTips
        
        whiteView.snp.remakeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-20)
        }
        
        titleLabel.snp.remakeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(11)
            make.right.equalTo(model.isNeedTemplate ? -90 : -8)
        }
        
        templateButton.snp.remakeConstraints { make in
            make.top.equalTo(13)
            make.right.equalTo(-16)
            if model.isNeedTemplate {
                make.width.equalTo(66)
            } else {
                make.width.equalTo(0)
            }
            make.height.equalTo(27)
        }
        
        lineView.snp.remakeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
            make.height.equalTo(1.0)
        }
        
        let isHiddenReason =  model.audit_content.isEmpty || model.check_status != YHPrincipleUploadStatus.rejected.rawValue
        rejectReasonLabel.snp.remakeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(isHiddenReason ? 0 : 16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            if isHiddenReason {
                make.height.equalTo(0)
            }
        }

        grayLabel.snp.remakeConstraints { make in
            make.top.equalTo(rejectReasonLabel.snp.bottom).offset(model.tips.isEmpty ? 0 : 16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            if model.tips.isEmpty {
                make.height.equalTo(0)
            }
        }
        
        detailLabel.snp.remakeConstraints { make in
            make.top.equalTo(grayLabel.snp.bottom).offset(detail.length <= 0  ? 0 : 16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            if detail.length <= 0 {
                make.height.equalTo(0)
            }
        }
        
        tableView.snp.remakeConstraints { make in
            make.top.equalTo(detailLabel.snp.bottom).offset(model.content_url.count <= 0 ? 0 : 16)
            make.left.equalTo(0)
            make.right.equalTo(0)
            var listHeight = 0.0
            if model.content_url.count > 0 {
               listHeight = Double(model.content_url.count) * 55.0 + Double(model.content_url.count-1) * 8.0
            }
            make.height.equalTo(listHeight)
        }
        
        uploadBtn.snp.remakeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            if model.isNeedUploadBtn {
                make.height.equalTo(45)
            } else {
                make.height.equalTo(0)
            }
            make.top.equalTo(tableView.snp.bottom).offset(!model.isNeedUploadBtn  ? 0 : 16)
        }
        
        bottomRedTipsLabel.snp.remakeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(uploadBtn.snp.bottom).offset(!model.isShowRedTips ? 0 : 16)
            if !model.isShowRedTips {
                make.height.equalTo(0)
            }
            make.bottom.equalTo(-16)
        }
    }
    
    func getUploadBgColor(status: Int) -> UIColor {
        var color = UIColor.black
        
        if status == YHPrincipleUploadStatus.review.rawValue {
            color = UIColor(hex: 0xFFF5EB)
            
        } else if status == YHPrincipleUploadStatus.rejected.rawValue {
            color = UIColor(hex: 0xFFF2F2)
            
        } else if status == YHPrincipleUploadStatus.pass.rawValue {
            color = UIColor(hex: 0xF0FBF7)
            
        } else if status == YHPrincipleUploadStatus.mail.rawValue {
            color = UIColor(hex: 0xF0F4FB)
        }
        return color
    }
    
    func getUploadTitleColor(status: Int) -> UIColor {
        var color = UIColor.black
        
        if status == YHPrincipleUploadStatus.review.rawValue {
            color = UIColor(hex: 0xFF8000)
            
        } else if status == YHPrincipleUploadStatus.rejected.rawValue {
            color = UIColor(hex: 0xF81D22)
            
        } else if status == YHPrincipleUploadStatus.pass.rawValue {
            color = UIColor(hex: 0x3CC694)
            
        } else if status == YHPrincipleUploadStatus.mail.rawValue {
            color = UIColor.brandMainColor
        }
        return color
    }
    
    func getTitle(type: Int) -> String {
        if type == YHPrincipleAgreementType.agreement.rawValue {
           return "《赴港居留同意书》"
        }
        if type == YHPrincipleAgreementType.opinion.rawValue {
            return "申请人意见访问"
        }
        if type == YHPrincipleAgreementType.other.rawValue {
            return "其他证明材料"
        }
        return ""
    }
    
    func getUploadStatusText(status: Int) -> String {
        var statusText = ""
        if status == YHPrincipleUploadStatus.review.rawValue {
            statusText = "审核中"
        
        } else if status == YHPrincipleUploadStatus.rejected.rawValue {
            statusText = "已驳回"
            
        } else if status == YHPrincipleUploadStatus.pass.rawValue {
            statusText = "已通过"
            
        } else if status == YHPrincipleUploadStatus.mail.rawValue {
            statusText = "已邮件港府"
        }
        return statusText
    }
    
    func getDetailText(type: Int) -> ASAttributedString {
        if type == YHPrincipleAgreementType.agreement.rawValue {
            let a: ASAttributedString = .init("请【下载模板】，填写信息，贵单位", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("签字盖章", .font(UIFont.PFSC_B(ofSize: 13)),.foreground(UIColor.brandMainColor))
            let c: ASAttributedString = .init("后，拍照or扫描上传", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
            return a+b+c
        }
        if type == YHPrincipleAgreementType.opinion.rawValue {
            let a: ASAttributedString = .init("请【下载模板】，填写信息，拍照or扫描上传", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
            return a
        }
        if type == YHPrincipleAgreementType.other.rawValue {
            let a: ASAttributedString = .init("", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
            return a
        }
        let a: ASAttributedString = .init("", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
        return a
    }
    
    func getTips(type: Int) -> String {
        
        if type == YHPrincipleAgreementType.agreement.rawValue {
           return "由你现时所属内地工作单位或负责储存你的记录的內地有关当局所发出的赴港居留同意书。"
        }
        if type == YHPrincipleAgreementType.opinion.rawValue {
            return ""
        }
        if type == YHPrincipleAgreementType.other.rawValue {
            var text = ""
            if let remark = self.itemModel?.remark, !remark.isEmpty {
                text = "\n"+remark
            }
            return "1、新公司在职证明（在申请期间更换了工作时必传）\n2、海外学历认证证书：如您曾申报过由非中国内地学院颁发的学位，则必传（比如：留服认证）\n"+text
        }
        return ""
    }
    
    func getCheckTips(type: Int) -> String {
        if type == YHPrincipleAgreementType.agreement.rawValue {
           return "请上传《赴港居留同意书》"
        }
        if type == YHPrincipleAgreementType.opinion.rawValue {
            return "请上传申请人意见访问"
        }
        if type == YHPrincipleAgreementType.other.rawValue {
            return "请上传其他证明材料"
        }
        return ""
    }
}

extension YHPrincipleUploadStatusCell: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleUploadFileCell.cellReuseIdentifier, for: indexPath) as! YHPrincipleUploadFileCell
        if 0 <= indexPath.section, indexPath.section < items.count {
            let model: YHPrincipleContentUrlModel = items[indexPath.section]
            cell.updateModel(model)
            if let itemModel = self.itemModel {
                cell.isShowEditBtn = (itemModel.check_status == YHPrincipleUploadStatus.preUpload.rawValue ||
                                      itemModel.check_status == YHPrincipleUploadStatus.rejected.rawValue)
            } else {
                cell.isShowEditBtn = false
            }
            cell.editBlock = {
                [weak self] selectModel in
                guard let self = self else { return }
                self.fileEditBlock?(selectModel, indexPath.section)
            }
            cell.clickBlock = {
                [weak self] selectModel in
                guard let self = self else { return }
                self.fileClickBlock?(selectModel, indexPath.section)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 8.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}

extension YHPrincipleUploadStatusCell {
    
    
    
}
