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

import UIKit
import AttributedString

// 原则批已获批 - 待提交
class YHPrincipleApprovedWaitSubmitVC: YHBaseViewController {

    var orderId: Int = -1
    var items: [YHPrincipleEnvelopeModel] = []
    let viewModel = YHPrincleViewModel()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionHeaderHeight = 24.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHPrincipleProfileListCell.self, forCellReuseIdentifier: YHPrincipleProfileListCell.cellReuseIdentifier)
        tableView.register(YHPrincipleEnvelopeCell.self, forCellReuseIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hex: 0xF8F8F8)
        let imgView = UIImageView(image: UIImage(named: "principle_detail_head_bg"))
        view.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(imgView.snp.width)
        }
        return view
    }()
    
    lazy var uploadBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("去上传".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didUploadBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "原则批"
        gk_navigationBar.backgroundColor = .clear
        createUI()
        requestData()
    }
    
    func createUI() {
        view.addSubview(bgView)
        view.addSubview(tableView)
        view.addSubview(uploadBtn)
        
        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(uploadBtn.snp.top).offset(-8)
        }
        
        uploadBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-42)
            make.height.equalTo(48.0)
        }

    }
    
    @objc func didUploadBtnClicked() {
        let vc = YHPrincipleUploadListVC()
        vc.orderId = self.orderId
        navigationController?.pushViewController(vc)
    }
    
    func requestData() {
        viewModel.getEnvelopeInfo(orderId: orderId) { _, _ in
            self.items.removeAll()
            // 已获得港府甄选名额
            if !self.viewModel.envelopModel.name.isEmpty, !self.viewModel.envelopModel.url.isEmpty {
                self.viewModel.envelopModel.isUnfold = true
                self.items.append(self.viewModel.envelopModel)
            }
            self.tableView.reloadData()
        }
    }
}

extension YHPrincipleApprovedWaitSubmitVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleEnvelopeCell else {
            return UITableViewCell()
        }
        if 0 <= indexPath.row && indexPath.row < items.count {
            let model = items[indexPath.row]
            cell.updateModel(model)
            cell.expandClick = {
                [weak self] isUnfold in
                guard let self = self else { return }
                model.isUnfold = isUnfold
                self.tableView.reloadData()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        if 0 <= indexPath.section && indexPath.section < items.count {
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return self.getApproveHeaderView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
}

extension YHPrincipleApprovedWaitSubmitVC {
    
    func getApproveHeaderView() -> UIView {
        
        let view = UIView()
        
        let titleLabel = UILabel()
        
        var name = self.viewModel.envelopModel.name
        if name.count > 5 {
            name = String(name.prefix(5)) + "..."
        }
        let callName = self.viewModel.envelopModel.sex == 2 ? "女士" : "先生"
        
        let title: ASAttributedString = .init("祝贺您，\(name)\(callName)！", .font(UIFont.PFSC_M(ofSize: 24)), .foreground(UIColor.mainTextColor))
        titleLabel.attributed.text = title
        view.addSubview(titleLabel)
        
        let detailLabel = UILabel()
        detailLabel.numberOfLines = 0
        let str1: ASAttributedString = .init("您【与家人】申请的【优秀人才入境计划】，", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        let str2: ASAttributedString = .init("已获得港府的甄选名额", .font(UIFont.PFSC_B(ofSize: 14)), .foreground(UIColor.brandMainColor))
        let str3: ASAttributedString = .init("，请您于", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        let time: ASAttributedString = .init("\(self.viewModel.envelopModel.convertDateFormat())", .font(UIFont.PFSC_B(ofSize: 14)), .foreground(UIColor.brandMainColor))
        let str4: ASAttributedString = .init("前补充更多文件，即可等待获得港府的正式批准！", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        detailLabel.attributed.text = str1 + str2 + str3 + time + str4
        view.addSubview(detailLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(34)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-36)
        }
    
        return view
    }
}
