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

import UIKit
import SmartCodable
import AttributedString

// 【原则批已获批 - 所有材料已一键发邮件】
class YHPrincipleApprovedMailViewController: YHBaseViewController {

    var orderId: Int = -1
    var items: [SmartCodable] = []
    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
    }()
    
    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)
        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.bottom.equalToSuperview()
        }
    }
}

extension YHPrincipleApprovedMailViewController {
    
    func requestData() {
        
        let group = DispatchGroup()
        group.enter()
        let params: [String: Any] = ["order_id": orderId,
                                      "search_type": 1]
        viewModel.getPrincipleWaitReviewResult(params: params) { _, _ in
            group.leave()
        }
        group.enter()
        viewModel.getEnvelopeInfo(orderId: orderId) { _, _ in
            group.leave()
        }
        
        group.notify(queue: .main) {
            self.updateData()
        }
    }
    
    func updateData() {
        self.items.removeAll()
        
        // 已获得港府甄选名额
        if !self.viewModel.envelopModel.name.isEmpty, !self.viewModel.envelopModel.url.isEmpty {
            self.items.append(self.viewModel.envelopModel)
        }
        
        let waitResultModel = self.viewModel.waitResultModel
        // 入境处已认收受理
        let model2 = waitResultModel.copy()
        model2.type = .entry
        model2.title = "入境处已认收受理"
        model2.subTitle = "申请确认通知书：(来自香港入境处)"
        model2.isUnfold = false
        self.items.append(model2)
        
        // 申请资料已递交港府留档
        let model3 = waitResultModel.copy()
        model3.type = .profile
        model3.title = "申请资料已递交港府留档"
        model3.subTitle = "档案号："
        model3.isUnfold = false
        self.items.append(model3)
        
        self.tableView.reloadData()
    }
}

extension YHPrincipleApprovedMailViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        if 0 <= indexPath.row && indexPath.row < items.count {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleProfileListCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleProfileListCell else {
                return UITableViewCell()
            }
            let m = items[indexPath.row]
            if m is YHPrincipleWaitResultModel {
                if let model = m as? YHPrincipleWaitResultModel {
                    if model.type == .profile || model.type == .entry {
                        cell.updateModel(model)
                        cell.expandClick = {
                            [weak self] isUnfold in
                            guard let self = self else { return }
                            model.isUnfold = isUnfold
                            self.tableView.reloadData()
                        }
                    }
                }
                return cell
            }
        }
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleEnvelopeCell else {
            return UITableViewCell()
        }
        if 0 <= indexPath.row && indexPath.row < items.count {
            let m = items[indexPath.row]
            if m is YHPrincipleEnvelopeModel {
                if let model = m as? YHPrincipleEnvelopeModel {
                    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 YHPrincipleApprovedMailViewController {
    
    func getApproveHeaderView() -> UIView {
        
        let view = UIView()
        
        let titleLabel = UILabel()
        
        var name = self.viewModel.waitResultModel.applicant.userName
        if name.count > 5 {
            name = String(name.prefix(5)) + "..."
        }
        let callName = self.viewModel.waitResultModel.applicant.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))
        detailLabel.attributed.text = str1 + str2
        view.addSubview(detailLabel)
        
        let imgView = UIImageView(image: UIImage(named: "principle_approved_mail"))
        view.addSubview(imgView)
        
        let tipsLabel = UILabel()
        tipsLabel.font = UIFont.PFSC_M(ofSize: 16)
        tipsLabel.textColor = .mainTextColor
        tipsLabel.text = "补充资料已邮件港府"
        tipsLabel.textAlignment = .center
        view.addSubview(tipsLabel)
        
        let tips2Label = UILabel()
        tips2Label.font = UIFont.PFSC_R(ofSize: 12)
        tips2Label.textColor = .mainTextColor(alpha: 0.5)
        tips2Label.text = "请耐心等待港府审核噢~"
        tips2Label.textAlignment = .center
        view.addSubview(tips2Label)
        
        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)
        }
        
        imgView.snp.makeConstraints { make in
            make.top.equalTo(detailLabel.snp.bottom).offset(36)
            make.width.height.equalTo(128)
            make.centerX.equalToSuperview()
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.top.equalTo(imgView.snp.bottom).offset(6)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(24)
        }
        
        tips2Label.snp.makeConstraints { make in
            make.top.equalTo(tipsLabel.snp.bottom).offset(9)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(18)
            make.bottom.equalTo(-60)
        }
        return view
    }
}
