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

import UIKit
import AttributedString

enum YHCustomerServiceStatus: Int {
    
    case none = 0
    
    case principleWaitResult = 11 // 原则批等待结果
    case principleSupplement = 12 // 原则批待补件
    case principleApproved = 13   // 原则批已获批
    case principleRejected = 14   // 原则批未获批准
    
    case officialApproved = 15    // 正式批已获批
}

class YHPrincipleWaitResultViewController: YHBaseViewController {

    var orderId: Int = -1
    var status: Int = -1
    var items: [YHPrincipleWaitResultModel] = []
    var isQuerying: Bool = false
    
    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(YHPrinciplePhotoListCell.self, forCellReuseIdentifier: YHPrinciplePhotoListCell.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
        
        if self.status == YHCustomerServiceStatus.principleWaitResult.rawValue {
            self.gk_navTitle = "等待中"
            
        } else if self.status == YHCustomerServiceStatus.principleRejected.rawValue {
            self.gk_navTitle = "未获批准"
        
        } else if self.status == YHCustomerServiceStatus.principleSupplement.rawValue {
            self.gk_navTitle = "待补件"
        }
        gk_navigationBar.backgroundColor = .clear
        createUI()
        getPrincipleWaitResult()
    }
    
    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 YHPrincipleWaitResultViewController {
    
    func getPrincipleWaitResult() {
        
        YHHUD.show(.progress(message: "加载中..."))

        let params: [String : Any] = ["order_id" : orderId,
                                      "search_type" : 1]
        viewModel.getPrincipleWaitReviewResult(params: params) { success, error in
            YHHUD.hide()
            
            self.items.removeAll()
            let waitResultModel = self.viewModel.waitResultModel
            if self.status == YHCustomerServiceStatus.principleWaitResult.rawValue {
                if waitResultModel.resultImageList.count > 0 {
                    // 实时入境处身份申请进度
                    let model1 = waitResultModel.copy()
                    model1.type = .photo
                    model1.title = "实时入境处身份申请进度"
                    model1.isUnfold = true
                    self.items.append(model1)
                }
            }
            
            // 入境处已认收受理
            let model2 = waitResultModel.copy()
            model2.type = .entry
            model2.title = "入境处已认收受理"
            model2.subTitle = "申请确认通知书：(来自香港入境处)"
            if self.status ==  YHCustomerServiceStatus.principleWaitResult.rawValue { // 原则批等待结果
                model2.isUnfold = waitResultModel.resultImageList.count <= 0
                
            } else if self.status == YHCustomerServiceStatus.principleSupplement.rawValue { // 原则批待补件
                model2.isUnfold = false
                
            } else if self.status == YHCustomerServiceStatus.principleRejected.rawValue { // 原则批未获批准
                model2.isUnfold = false
            }
            self.items.append(model2)
            
            
            // 申请资料已递交港府留档
            let model3 = waitResultModel.copy()
            model3.type = .profile
            model3.title = "申请资料已递交港府留档"
            model3.subTitle = "档案号："
            if self.status ==  YHCustomerServiceStatus.principleWaitResult.rawValue { // 原则批等待结果
                model3.isUnfold = waitResultModel.resultImageList.count <= 0
                
            } else if self.status == YHCustomerServiceStatus.principleSupplement.rawValue { // 原则批待补件
                model3.isUnfold = false
                
            } else if self.status == YHCustomerServiceStatus.principleRejected.rawValue { // 原则批未获批准
                model3.isUnfold = false
            }
            self.items.append(model3)
            self.tableView.reloadData()
        }
    }
}

extension YHPrincipleWaitResultViewController: 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 {
            let model = items[indexPath.row]
            if model.type == .photo {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHPrinciplePhotoListCell.cellReuseIdentifier, for: indexPath) as! YHPrinciplePhotoListCell
                model.isQuerying = self.isQuerying
                cell.updateModel(model)
                cell.expandClick = {
                    [weak self] isUnfold in
                    guard let self = self else { return }
                    model.isUnfold = isUnfold
                    self.tableView.reloadData()
                }
                cell.queryClick = {
                    [weak self] in
                    guard let self = self else { return }
                    YHHUD.show(.progress(message: "查询中..."))
                    self.viewModel.queryApproval(orderId: self.orderId) {
                        [weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success {
                            YHHUD.flash(message: "查询成功")
                            self.isQuerying = true
                            self.tableView.reloadData()
                        }
                    }
                }
                return cell
            }
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleProfileListCell.cellReuseIdentifier, for: indexPath) as! YHPrincipleProfileListCell
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let model = items[indexPath.row]
            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
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    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? {
        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 helloName = self.status == YHCustomerServiceStatus.principleRejected.rawValue ? "很遗憾，" : "您好，"
        let title: ASAttributedString = .init("\(helloName)\(name)\(callName)！", .font(UIFont.PFSC_M(ofSize: 24)),.foreground(UIColor.mainTextColor))
        titleLabel.attributed.text = title
        view.addSubview(titleLabel)
        
        let tipsLabel = UILabel()
        tipsLabel.numberOfLines = 0
        tipsLabel.font = UIFont.PFSC_R(ofSize: 14)
        tipsLabel.textColor = .mainTextColor(alpha: 0.7)
        tipsLabel.text = "您的【优秀人才入境计划】赴港居留申请资料已经递交港府。"
        view.addSubview(tipsLabel)

        let detailLabel = UILabel()
        detailLabel.numberOfLines = 0
        detailLabel.font = UIFont.PFSC_R(ofSize: 14)
        detailLabel.attributed.text = self.getDescOfStatus(self.status)
        view.addSubview(detailLabel)

        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(34)
        }
        
        tipsLabel.snp.makeConstraints { make in
            // 待补件
            let isWaitSupply = self.status == 12
            let topMargin = isWaitSupply ? 12.0 : 0.0
            make.top.equalTo(titleLabel.snp.bottom).offset(topMargin)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            if !isWaitSupply {
                make.height.equalTo(0)
            }
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(tipsLabel.snp.bottom).offset(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-36)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func getDescOfStatus(_ status: Int) -> ASAttributedString {
        
        // 11 等待原则批结果
        // 12 正在进行原则批补件
        // 13 原则批已获批
        // 14 未获批准~
    
        if status == YHCustomerServiceStatus.principleWaitResult.rawValue { // 等待原则批结果
            let str1: ASAttributedString = .init("您的【优秀人才入境计划】赴港居留申请资料已经递交港府，且入境事务处已经认收受理！港府审核周期预计在12个月内，", .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))
            var str3: ASAttributedString = .init("，请您耐心等待！", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor(alpha: 0.7)))
            if self.viewModel.waitResultModel.resultImageList.count > 0 {
                str3 = .init("，详见下方截图：", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor(alpha: 0.7)))
            }
            return str1 + str2 + str3
            
        } else if status == YHCustomerServiceStatus.principleSupplement.rawValue { // 待补件
            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))
            return str1 + str2
            
        } else if status == YHCustomerServiceStatus.principleRejected.rawValue { // 未获批准~
            
            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)))
            return str1 + str2 + str3
        }
        let defaultStr: ASAttributedString = .init("")
        return defaultStr
    }
}

