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

import UIKit
import AttributedString

class YHResignUploadDocListViewController: YHBaseViewController {
    var orderId: Int = 0
    // 批次id
    var batchId: Int = 0
    lazy var viewModel: YHResignUploadDocListViewModel = {
        let vm = YHResignUploadDocListViewModel()
        return vm
    }()

    var bgImageView: UIImageView!
    var titleLabel: UILabel!
    var messageLabel: UILabel!

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 16.0
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(YHResignUploadDocListCell.self, forCellReuseIdentifier: YHResignUploadDocListCell.cellReuseIdentifier)
        tableView.register(YHResignUploadSuccessDocListCell.self, forCellReuseIdentifier: YHResignUploadSuccessDocListCell.cellReuseIdentifier)
        
        return tableView
    }()

    //我已知悉，确认
    lazy var rewardBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("去查看港府续签结果", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.white, for: .disabled)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickNextBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        return button
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(self.rewardBtn)
        self.rewardBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(48)
        }
        view.layer.zPosition = 10
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    @objc func clickNextBtn() {
        let vc = YHLookResignResultViewController()
        vc.orderId = orderId
        vc.batchId = batchId
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
}

private extension YHResignUploadDocListViewController {
    func loadData() {
        viewModel.getUploadDocList(orderID: orderId, stepID: batchId) {[weak self] success, err in
            guard let self = self else { return }
            if self.viewModel.mainModel.supplement_voucher_url.count == 0 {
                self.bottomView.isHidden = true
                let a = ASAttributedString.init("请您于", .font(UIFont.PFSC_R(ofSize:14)), .foreground(UIColor.mainTextColor50))
                let b = ASAttributedString.init("\(self.viewModel.mainModel.supplement_deadline)前", .font(UIFont.PFSC_M(ofSize:14)),.foreground(UIColor.brandMainColor))
                let c = ASAttributedString.init("根据补件清单上传资料递交至港府；如无及时递交，可能导致身份失效！", .font(UIFont.PFSC_R(ofSize:14)), .foreground(UIColor.mainTextColor50))
                messageLabel.attributed.text = a+b+c
            } else {
                let a = ASAttributedString.init("您申请的【优才入境计划】续签，", .font(UIFont.PFSC_M(ofSize:17)), .foreground(UIColor.mainTextColor))
                let b = ASAttributedString.init("补件资料已递交至港府！", .font(UIFont.PFSC_M(ofSize:17)),.foreground(UIColor.yhOrangeColor))
                let c = ASAttributedString.init("请耐心等待港府审批~", .font(UIFont.PFSC_M(ofSize:17)), .foreground(UIColor.mainTextColor))
                titleLabel.attributed.text = a+b+c
                self.bottomView.isHidden = false
                self.messageLabel.isHidden = true
                tableView.snp.remakeConstraints { make in
                    make.left.equalToSuperview()
                    make.right.equalToSuperview()
                    make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 100)
                    make.bottom.equalTo(-98)
                }
            }
            self.tableView.reloadData()
        }
    }
    
    func setupUI() {
        gk_navTitle = "续签补件"
        view.backgroundColor = UIColor.contentBkgColor
    
        bgImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "resign_upload_doc_head")
            return imageView
        }()
        view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(375.fix)
        }
        
        titleLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            let a = ASAttributedString.init("您申请的【优才入境计划】续签，", .font(UIFont.PFSC_M(ofSize:17)), .foreground(UIColor.mainTextColor))
            let b = ASAttributedString.init("已获得港府补件通知！", .font(UIFont.PFSC_M(ofSize:17)),.foreground(UIColor.yhOrangeColor))
            label.attributed.text = a+b
            return label
        }()
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(60)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 24)
        }
        
        messageLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            let a = ASAttributedString.init("请您于", .font(UIFont.PFSC_M(ofSize:14)), .foreground(UIColor.mainTextColor50))
            let b = ASAttributedString.init("2024年8月8日前", .font(UIFont.PFSC_M(ofSize:14)),.foreground(UIColor.brandMainColor))
            let c = ASAttributedString.init("根据补件清单上传资料递交至港府；如无及时递交，可能导致身份失效！", .font(UIFont.PFSC_M(ofSize:14)), .foreground(UIColor.mainTextColor50))
            label.attributed.text = a+b+c
            return label
        }()
        view.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(44)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 84)
        }
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(98)
            make.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.bottom.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 152)
        }
    }
    
    func getHeight(_ value: String) -> CGFloat {
        let text = value // 要显示的文本内容
        let font = UIFont.PFSC_B(ofSize: 14) // 字体大小
        let maxWidth = KScreenWidth - 146 // 最大宽度限制
        
        // 创建NSAttributedString对象并设置属性
        let attributes = [NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
        _ = NSMutableAttributedString(string: text, attributes: attributes)
         
        // 根据指定的最大宽度和字体大小计算文本的高度
        let size = (text as NSString).boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size
        return size.height
    }
}


extension YHResignUploadDocListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.viewModel.mainModel.supplement_voucher_url.count == 0 {
            return 2
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.viewModel.mainModel.supplement_voucher_url.count == 0 {
            let approveCell = tableView.dequeueReusableCell(withIdentifier: YHResignUploadDocListCell.cellReuseIdentifier, for: indexPath) as! YHResignUploadDocListCell
            approveCell.section = indexPath.section
            if indexPath.section == 0 {
                approveCell.title = "资料上传"
                approveCell.dataSource = self.viewModel.mainModel.upload_list
                if self.viewModel.mainModel.upload_list.count == 0 {
                    approveCell.isHidden = true
                } else {
                    approveCell.isHidden = false
                }
            } else {
                approveCell.title = "文书确认"
                approveCell.dataSource = self.viewModel.mainModel.doc_list
                if self.viewModel.mainModel.doc_list.count == 0 {
                    approveCell.isHidden = true
                } else {
                    approveCell.isHidden = false
                }
            }
            approveCell.clickBlock = { [weak self] model, section in
                guard let self = self else { return }
                if section == 0 {
                    // 跳转文件上传
                    let vc = YHResignUploadDocDetailViewController()
                    vc.id = model.id
                    self.navigationController?.pushViewController(vc)
                } else {
                    // 跳转列表
                    if model.status == 0 {
                        YHHUD.flash(message: "文书正在努力撰写中，请等待")
                    } else {
                        let vc = YHResignDocumentManagementVC(orderId: orderId, id: batchId)
                        self.navigationController?.pushViewController(vc)
                    }
                }
            }
            return approveCell
        } else {
            let approveCell = tableView.dequeueReusableCell(withIdentifier: YHResignUploadSuccessDocListCell.cellReuseIdentifier, for: indexPath) as! YHResignUploadSuccessDocListCell
            approveCell.dataSource = [self.viewModel.mainModel.supplement_voucher_url]
            return approveCell
        }
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.viewModel.mainModel.supplement_voucher_url.count == 0 {
            if indexPath.section == 0 {
                var height: CGFloat = 0
                for item in self.viewModel.mainModel.upload_list {
                    height = height + 32
                    let value = getHeight(item.name)
                    height = height + value
                }
                return CGFloat(52 + height)
            } else {
                var height: CGFloat = 0
                for item in self.viewModel.mainModel.doc_list {
                    height = height + 32
                    let value = getHeight(item.name)
                    height = height + value
                }
                return CGFloat(52 + height)
            }
        }
        return 67
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 16.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}
