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

import UIKit
import SmartCodable

enum YHPrincipleUploadStatus : Int {
    // 全部
    case all = -1
    // 审核中
    case review = 0
    // 已完成
    case finish = 1
    // 已驳回
    case rejected = 2
    // 待上传
    case preUpload = 3
}


class YHPrincipleReviewListVC: YHBaseViewController {

    var orderId: Int = 0
    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(YHPrincipleUploadStatusCell.self, forCellReuseIdentifier: YHPrincipleUploadStatusCell.cellReuseIdentifier)
        tableView.register(YHPrincipleUnapprovedCell.self, forCellReuseIdentifier: YHPrincipleUnapprovedCell.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()
        items.removeAll()
        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()
        }
    }
    
    func requestData() {
        
        let group = DispatchGroup()
        group.enter()
        // 请求上传信息（《赴港居留同意书》、申请人意见访问、其他证明材料）
        viewModel.getPrincipleUploadDetail(orderId: orderId) { success, error in
//            self.viewModel.uploadDetailModel
            group.leave()
        }
        
        group.enter()
        let params: [String : Any] = ["order_id" : orderId,
                                      "search_type" : 1]
        // 请求 入境处已认收受理 和 申请资料已递交港府留档
        viewModel.getPrincipleWaitReviewResult(params: params) { success, error in
            group.leave()
        }
        group.enter()
        viewModel.getEnvelopeInfo(orderId: orderId) { success, error in
            group.leave()
        }
        
        group.notify(queue: .main) {
            self.updateData()
        }
    }
    
    func updateData() {
        self.items.removeAll()
        
        // 赴港居留同意书
        let agreementModel = self.viewModel.uploadDetailModel.file_data.agreement
        agreementModel.customType = YHPrincipleAgreementType.agreement.rawValue
        agreementModel.title = "《赴港居留同意书》"
        agreementModel.isMust = true
        agreementModel.isNeedTemplate = true
        self.items.append(agreementModel)
        
        // 申请人意见访问
        let opinionModel = self.viewModel.uploadDetailModel.file_data.agreement
        opinionModel.customType = YHPrincipleAgreementType.agreement.rawValue
        opinionModel.title = "申请人意见访问"
        opinionModel.isMust = true
        opinionModel.isNeedTemplate = true
        self.items.append(self.viewModel.uploadDetailModel.file_data.opinion)
        
        // 其他证明条件
        self.items.append(self.viewModel.uploadDetailModel.file_data.other)
        
        // 已获得港府甄选名额
        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 YHPrincipleReviewListVC {
    
    
}

extension YHPrincipleReviewListVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) as! UITableViewCell
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let m = items[indexPath.row]

            if m is YHPrincipleWaitResultModel {
                // 入境处已认收受理 和 申请资料已递交港府留档 cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleUnapprovedCell.cellReuseIdentifier, for: indexPath) as! YHPrincipleUnapprovedCell
                let model = m as! YHPrincipleWaitResultModel
                cell.updateModel(model)
                cell.expandClick = {
                    [weak self] isUnfold in
                    guard let self = self else { return }
                    model.isUnfold = isUnfold
                    self.tableView.reloadData()
                }
                return cell
            }
            
            if m is YHPrincipleEnvelopeModel {
                //  已获得港府甄选名额 信封cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier, for: indexPath) as! YHPrincipleEnvelopeCell
                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
            }
            
            if m is YHPrincipleAgreementModel {
                //  上传文件 cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleUploadStatusCell.cellReuseIdentifier, for: indexPath) as! YHPrincipleUploadStatusCell
                let model = m as! YHPrincipleAgreementModel
                cell.updateModel(model)
                cell.expandClick = {
                    [weak self] isUnfold in
                    guard let self = self else { return }
                    model.isUnfold = isUnfold
                    self.tableView.reloadData()
                }
                return cell
            }
        }
        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 {
#if DEBUG
            
            if true {
                let vc = YHPrincipleCongratulationVC()
                self.navigationController?.pushViewController(vc)
                return
            }
#endif
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 24.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
}
