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

import UIKit
import JXSegmentedView

class YHServiceOrderListView: YHBaseViewController {
    private let viewModel : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    typealias Block = (Int,Int,Bool) -> ()
    var block: Block?
    var orderID: Int = 0
    var type: Int = 0
    var mobile: String = ""
    var homeTableView: UITableView!
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无", kEmptyCommonBgName)
        view.backgroundColor = .clear
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
}

extension YHServiceOrderListView {
    func loadData() {
        if YHLoginManager.shared.isLogin() {
            viewModel.getServiceCenterProgressList(orderID, type) {[weak self] success, error in
                guard let self = self else { return }
                if (self.homeTableView != nil) {
                    if self.viewModel.arrDataForSeviceCenterProgress.count == 0 {
                        self.homeTableView.isHidden = true
                        self.noDataView.isHidden = false
                    } else {
                        self.homeTableView.isHidden = false
                        self.noDataView.isHidden = true
                        self.homeTableView.reloadData()
                    }
                }
                if let block = self.block {
                    if type == 3 {
                        var oneflag = false
                        var twoflag = false
                        for item in self.viewModel.arrDataForSeviceCenterProgress {
                            if item.type == 3 {
                                oneflag = isNeedShowRedPointFor(key: kMyScoreRedPointInfoKey, proVersion: item.pro_version)
                            }
                            if item.type == 4 {
                                twoflag = isNeedShowRedPointFor(key: kMyPlanRedPointInfoKey, proVersion: item.pro_version)
                            }
                        }
                        block(type, self.viewModel.arrDataForSeviceCenterProgress.count, oneflag||twoflag)
                    } else {
                        block(type, self.viewModel.arrDataForSeviceCenterProgress.count, false)
                    }
                }
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        homeTableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.rowHeight = UITableView.automaticDimension
            tableView.estimatedRowHeight = 81.0
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(cellWithClass: YHServiceOrderProgressTableViewCell.self)
            return tableView
        }()
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.right.left.bottom.equalToSuperview()
        }
        
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(150)
        }
    }
    
    func isNeedShowRedPointFor(key: String, proVersion: Int) -> Bool {
        if key != kMyPlanRedPointInfoKey && key != kMyScoreRedPointInfoKey {
            return false
        }
        let targetKey = key + "_\(self.orderID)"
        if let dict = UserDefaults.standard.object(forKey: targetKey) as? [String: Any] {
            if !dict.keys.contains(kProVersionKey) ||  !dict.keys.contains(kClickKey) {
                return false
            }
            if let version = dict[kProVersionKey] as? Int {
                if version != proVersion { // 版本不一致一定显示红点
                    return true
                }
                // 版本一致但是未点击显示红点
                if let isClicked = dict[kClickKey] as? Bool, isClicked == false {
                    return true
                }
            }
            return false
        }
        // 本地没有红点记录存储则必展示红点
        return true
    }
}

extension YHServiceOrderListView : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.viewModel.arrDataForSeviceCenterProgress.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 1
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kMargin
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 128
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell0 = tableView.dequeueReusableCell(withClass: YHServiceOrderProgressTableViewCell.self)
        cell0.selectionStyle = .none

        if indexPath.section < self.viewModel.arrDataForSeviceCenterProgress.count {
            cell0.set(dataModel: self.viewModel.arrDataForSeviceCenterProgress[indexPath.section], orderId: orderID)
        }
        return cell0
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.viewModel.arrDataForSeviceCenterProgress[indexPath.section]
        if model.status == 1 || model.status == 4 {
            return
        } else {
            //1 证件 2 信息完善 3 我的评分 4 我的方案 5 我的签字 6我的文书
            if model.type == 1 {
                let vc = YHMineCertificateEntryViewController()
                vc.orderId = orderID
                navigationController?.pushViewController(vc)
                
            } else if model.type == 2 {
                let vc = YHInformationPerfectListVC()
                vc.orderId = orderID
                navigationController?.pushViewController(vc)
                
            } else if model.type == 3 { // 评分
                
                handleRedPointFor(key: kMyScoreRedPointInfoKey, model: model)
                let vc = YHScoreDetailViewController()
                vc.orderId = orderID
//                vc.model = serviceCenterMainReqVM.allInfoScoreModel
                navigationController?.pushViewController(vc)
                        
            } else if model.type == 4 { // 方案
                handleRedPointFor(key: kMyPlanRedPointInfoKey, model: model)
                let vc = YHMineSchemeViewController()
                navigationController?.pushViewController(vc)
                
            } else if model.type == 5 {
                let vc = YHMySignatureListViewController()
                vc.orderId = orderID
                navigationController?.pushViewController(vc)
                
            } else if model.type == 6 {
                let vc = YHMyDocumentsListViewController()
                vc.orderId = orderID
                vc.mobile = mobile
                navigationController?.pushViewController(vc)
            }
        }
    }
    
    func handleRedPointFor(key: String, model: YHServiceCenterProgressModel) {
        if key != kMyPlanRedPointInfoKey && key != kMyScoreRedPointInfoKey {
            return
        }
        if model.type != 3 && model.type != 4 { // 只有我的评分和我的方案进行红点处理
            return
        }
        
        if model.status != 3 { // 只有已完成状态才进行红点处理
            return
        }
        
        let dict:[String: Any] = [kProVersionKey: model.pro_version,
                                  kOrderIdKey: orderID,
                                  kClickKey: true]
        let targetKey = key + "_\(orderID)"
        UserDefaults.standard.set(dict, forKey: targetKey)
        UserDefaults.standard.synchronize()
    }
}


extension YHServiceOrderListView: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
