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

import UIKit

class YHPrincipleFileModel {
    var value: String = ""
    var name: String = ""
    var btnTitle: String = ""
    
    init(value: String = "", name: String = "", btnTitle: String = "") {
        self.value = value
        self.name = name
        self.btnTitle = btnTitle
    }
}

class YHPrincipleProfileItemView: UIView {
    
    static let viewH: CGFloat = 20.0
    var btnClick: (() -> Void)?
    
    lazy var pointView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.brandMainColor(alpha: 0.16)
        view.layer.cornerRadius = 1.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.numberOfLines = 0
        label.lineBreakMode = .byCharWrapping
        label.textColor = UIColor.mainTextColor(alpha: 0.7)
        label.textAlignment = .left
        return label
    }()
    
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 11)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.backgroundColor = UIColor(hex: 0xF4F6FA)
        btn.layer.cornerRadius = 10.0
        btn.addTarget(self, action: #selector(didRightBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    @objc func didRightBtnClicked() {
        btnClick?()
    }
     
    func updateModel(_ model: YHPrincipleFileModel) {
        titleLabel.text = model.name
        rightBtn.setTitle(model.btnTitle, for: .normal)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    func setupUI() {
        self.addSubview(self.pointView)
        self.addSubview(self.titleLabel)
        self.addSubview(self.rightBtn)
        
        self.pointView.snp.makeConstraints { make in
            make.width.height.equalTo(4.0)
            make.centerY.equalToSuperview()
            make.left.equalTo(16.0)
        }
        
        self.titleLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(self.pointView.snp.right).offset(8.0)
            make.right.equalTo(self.rightBtn.snp.left).offset(-16.0)
        }
        
        self.rightBtn.snp.makeConstraints { make in
            make.width.equalTo(38.0)
            make.height.equalTo(20.0)
            make.centerY.equalToSuperview()
            make.right.equalTo(-16.0)
        }
    }
}

class YHPrincipleProfileListCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHPrincipleProfileListCell"
    var itemModel: YHPrincipleWaitResultModel?
    var items: [YHPrincipleFileModel] = []
    var expandClick: ((Bool) -> Void)?

    let viewModel = YHPrincleViewModel()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 15)
        label.textColor = UIColor.mainTextColor
        return label
    }()
    
    lazy var listTitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_M(ofSize: 14)
        label.textColor = UIColor.mainTextColor
        return label
    }()
    
    lazy var iconImgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "custom_service_icon_right"))
        return view
    }()
    
    lazy var whiteView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 6.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var expandBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "custom_service_expand_0"), for: .normal)
        btn.addTarget(self, action: #selector(didExpandBtnClicked), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 0, left: KScreenWidth, bottom: 20, right: 40)
        return btn
    }()
    
    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: UIViewController.current)
       return tool
    }()
    
    func updateModel(_ model: YHPrincipleWaitResultModel) {
        
        itemModel = model
        items.removeAll()
        if model.type == .entry {
            let url = model.applicationFileNumberAttachment
            var name = "申请确认通知书"
            if !url.pathExtension.isEmpty {
                let cleanedExtension = url.pathExtension.components(separatedBy: "?").first ?? ""
                name = name + "." + cleanedExtension
            }
            let m = YHPrincipleFileModel(value: url, name: name, btnTitle: "查看")
            items.append(m)
            
        } else if model.type == .profile {
            for file in model.fileNumberList {
                let name = file.applicationName + " " + file.fileNumber
                let m = YHPrincipleFileModel(value: file.fileNumber, name: name, btnTitle: "复制")
                items.append(m)
            }
        }
        titleLabel.text = model.title
        listTitleLabel.text = model.subTitle
        whiteView.isHidden = !model.isUnfold
        let imgName = model.isUnfold ? "custom_service_expand_1" : "custom_service_expand_0"
        expandBtn.setImage(UIImage(named: imgName), for: .normal)
        expandBtn.isHidden = items.count <= 0

        if !model.isUnfold || items.count <= 0 {
            whiteView.removeSubviews()
            whiteView.snp.remakeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(0.0)
                make.height.equalTo(0.0)
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.bottom.equalTo(-32)
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
            return
        }
        
        whiteView.removeSubviews()
        whiteView.addSubview(self.listTitleLabel)
        listTitleLabel.snp.remakeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }

        whiteView.snp.remakeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(16.0)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-32)
        }
        
        var lastItemView: UIView = listTitleLabel
        for (index, item) in items.enumerated() {
            let itemView = YHPrincipleProfileItemView(frame: .zero)
            let viewHeight = self.getHeight(text: item.name, font: itemView.titleLabel.font, width: KScreenWidth-118.0)
            itemView.updateModel(item)
            if model.type == .entry {
                itemView.btnClick = {
                    YHHUD.show(.progress(message: "加载中..."))
                    // 中文编码
                    if let url = item.value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
                         self.viewModel.getRealUsefulUrl(url) {
                            [weak self] resultUrl in
                            YHHUD.hide()
                            guard let self = self else { return }
                            self.previewFileTool.openXLSXRemoteFile(urlString: resultUrl, fileName: "申请确认通知书")
                        }
                    }
                }
                
            } else if model.type == .profile {
                itemView.btnClick = {
                    UIPasteboard.general.string = item.value
                    YHHUD.flash(message: "复制成功")
                }
            }
            
            whiteView.addSubview(itemView)
            itemView.snp.makeConstraints { make in
                make.left.right.equalTo(0)
                make.height.equalTo(viewHeight)
                make.top.equalTo(lastItemView.snp.bottom).offset(16.0)
                if index == items.count-1 {
                    make.bottom.equalTo(-16.0)
                }
            }
            lastItemView = itemView
        }
        self.setNeedsLayout()
        self.layoutIfNeeded()
        
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    @objc func didExpandBtnClicked() {
        guard let model = itemModel else { return }
        expandClick?(!model.isUnfold)
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        self.contentView.backgroundColor = .clear
        self.backgroundColor = .clear
        contentView.addSubview(iconImgView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(expandBtn)
        contentView.addSubview(whiteView)
        
        iconImgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.width.height.equalTo(15.0)
            make.centerY.equalTo(titleLabel)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImgView.snp.right).offset(6)
            make.right.equalTo(expandBtn.snp.left)
            make.top.equalTo(0)
            make.height.equalTo(20)
        }
        
        expandBtn.snp.makeConstraints { make in
            make.width.height.equalTo(20.0)
            make.centerY.equalTo(titleLabel)
            make.right.equalTo(-20.0)
        }
        
        whiteView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(0.0)
            make.height.equalTo(0.0)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-32)
        }
    }
    
    func getHeight(text: String, font: UIFont, width: CGFloat) -> CGFloat {
        
        let size = CGSize.init(width: width, height: CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font: font]
        let strSize = text.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        var height = CGSize(width: strSize.width, height: ceil(strSize.height)).height
        if height < 20.0 {
             height = 20
        }
        return ceil(height)
    }
}
