//
//  OrderCasePoolMainVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/5.
//

import UIKit
import JXSegmentedView

public struct R_OrderCasePoolMain {
    static func router(_ orderid: String, callback: ((Bool)->Void)?) {
        let vc = OrderCasePoolMainVc.cd_storyboard("Order", from: "OrderCasePoolMainVc") as! OrderCasePoolMainVc
        vc.orderId = orderid
        CD.push(vc)
    }
}

class OrderCasePoolMainVc: UIViewController {

    @IBOutlet weak var stackBgV: UIStackView!
    @IBOutlet weak var headerV: UIView!
    @IBOutlet weak var curSubV: UIView!
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var curVC:OrderCasePoolListVc?
    var state = 0
    
    lazy var segmentedView: JXSegmentedView = {
        let segmentedV = JXSegmentedView()
        segmentedV.delegate = self
        return segmentedV
    }()
    
    var segmentedtTitles:[String] = ["标准案例".languageString(), "案例工单".languageString()]
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let segmentedDa = JXSegmentedTitleDataSource()
        segmentedDa.titles = segmentedtTitles
        segmentedDa.isTitleColorGradientEnabled = true
        segmentedDa.titleNormalColor = Config.color.hex("6")
        segmentedDa.titleNormalFont = UIFont.PingFangRegular(size: 14)
        segmentedDa.titleSelectedColor = Config.color.hex("3")
        segmentedDa.titleSelectedFont = UIFont.PingFangMedium(size: 14)
        return segmentedDa
    }()
    
    lazy var indicator:JXSegmentedIndicatorLineView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = Config.color.hex("#478BFF")
        indicator.indicatorWidth = 24
        return indicator
    }()
    
    lazy var listContainerView = JXSegmentedListContainerView(dataSource: self)
    lazy var subControllerList = [JXSegmentedListContainerViewListDelegate]()
    
    var orderId = ""
    
    var caseDemoList:[M_OrderCasePool] = []
    var orderDemoList:[M_OrderCasePool] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        requestData()
    }
    
    func configUI() {
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
        topBar.delegate = self
        
        stackBgV.snp.makeConstraints { make in
            make.top.equalTo(topBar.snp_bottom)
        }
        
        segmentedView.defaultSelectedIndex = state
        segmentedDataSource.reloadData(selectedIndex: state)
        segmentedView.indicators = [indicator]
        segmentedView.dataSource = segmentedDataSource
        headerV.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        addSubViewControlls()
        setCurrentVC()
        
        view.addSubview(self.listContainerView)
        segmentedView.listContainer = listContainerView
        curSubV.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
        }
    }
    
    func addSubViewControlls() {
        var cSubC = [JXSegmentedListContainerViewListDelegate]()
        
        do {
            let curViewC = UIStoryboard(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "OrderCasePoolListVc") as! OrderCasePoolListVc
            curViewC.vm.viewType = 0
            curViewC.getDatas = {
                curViewC.vm.models = self.caseDemoList
            }
            curViewC.refreshDatas = {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.requestData()
            }
            cSubC.append(curViewC)
        }
        
        do {
            let curViewC = UIStoryboard(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "OrderCasePoolListVc") as! OrderCasePoolListVc
            curViewC.vm.viewType = 1
            curViewC.getDatas = {
                curViewC.vm.models = self.orderDemoList
            }
            curViewC.refreshDatas = {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.requestData()
            }
            cSubC.append(curViewC)
        }
        
        subControllerList = cSubC
    }

    func setCurrentVC() {
        let vc = subControllerList[segmentedView.selectedIndex] as! OrderCasePoolListVc
        curVC = vc
    }
    
    
    func setSelectIndex(_ idx:Int) {
        state = idx
        if !subControllerList.isEmpty {
            segmentedView.selectItemAt(index: state)
        }else{
            segmentedDataSource.reloadData(selectedIndex: state)
        }
    }
    
    func setDatas() {
        segmentedtTitles = ["\("标准案例".languageString()) \(caseDemoList.count)", "\("案例工单".languageString()) \(orderDemoList.count)"]
        segmentedDataSource.titles = segmentedtTitles
        segmentedView.reloadData()
        
        for (index ,item) in subControllerList.enumerated() {
            if let vc = item as? OrderCasePoolListVc{
                switch index {
                case 0:
                    vc.vm.models = caseDemoList
                case 1:
                    vc.vm.models = orderDemoList
                default:
                    break
                }
                vc.vm.makeForms()
            }
        }
    }
    
    func setModels()  {
        caseDemoList = [M_OrderCasePool(["caseDemoId":"AL2023-102","caseDemoNo":"AL2023-101","fault":"毛毛虫","category":"GL2/PINK","createTime":"2023-01-11 10:00-11:00"]),M_OrderCasePool(["caseDemoId":"AL2023-102","caseDemoNo":"AL2023-102","fault":"毛毛虫","category":"GL2/PINK","createTime":"2023-01-11 10:00-11:00"]),M_OrderCasePool(["caseDemoId":"AL2023-102","caseDemoNo":"AL2023-103","fault":"毛毛虫","category":"GL2/PINK","createTime":"2023-01-11 10:00-11:00"])]
        orderDemoList = [M_OrderCasePool(["orderId":"70","orderNo":"SP20230629212019834418","fault":"毛毛虫","category":"GL2/PINK","createTime":"2023-01-11 10:00-11:00"]),M_OrderCasePool(["orderId":"71","orderNo":"SP20230629212019834419","fault":"毛毛虫","category":"GL2/PINK","createTime":"2023-01-11 10:00-11:00"])]
    }
}

extension OrderCasePoolMainVc: JXSegmentedViewDelegate, JXSegmentedListContainerViewDataSource {
    
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return subControllerList.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return subControllerList[index]
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        let vc = subControllerList[index] as! OrderCasePoolListVc
        curVC = vc
        
    }
}

extension OrderCasePoolMainVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        topBar._style = "10"
        
        topBar.cd.background(.white)
        topBar._title = "案例池".languageString()
        topBar.bar_navigation.item_centre._colorTitle = Config.color.hex("3")
        topBar.bar_navigation.item_centre.btn_1.titleLabel?.font = Config.font.fontMedium(18)
        topBar.bar_navigation.line.cd.isHidden(false)
            .background(Config.color.hex("EC"))
    }
    
    func update(withTopBar item: CD_TopNavigationBar.Item) -> [CD_TopNavigationBarItem.Item.Style]? {
        switch item {
        case .leftItem1:
            let color:UIColor = Config.color.hex("6")
            let icon = CD_IconFont.tback_light(22)
            return [.title([(icon.text, icon.font, color, .normal), (icon.text, icon.font, Config.color.hex("6"), .highlighted), (icon.text, icon.font, Config.color.hex("6"), .selected)])]
        default:
            return nil
        }
    }
    
    func didSelect(withTopBar item: CD_TopNavigationBar.Item) {
        super_topBarClick(item)
        switch item {
        case .leftItem1:
            break
        default:
            break
        }
    }
}

extension OrderCasePoolMainVc {
    func requestData() {
//        setModels()
//        setDatas()
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/caseDemo",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                weakSelf.caseDemoList = data.arrayValue(forKey: "caseDemoList").compactMap({M_OrderCasePool($0)})
                weakSelf.orderDemoList = data.arrayValue(forKey: "orderDemoList").compactMap({M_OrderCasePool($0)})
                weakSelf.setDatas()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.curVC?.vm.makeForms()
        }
        cNet.postRequest()
    }
}

