//
//  PartsManagementMainVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/21.
//

import UIKit
import JXSegmentedView

public struct R_PartsManagementMain {
    static func router(_ searchType: Int, callback: ((Bool)->Void)?) {
        let vc = PartsManagementMainVc.cd_storyboard("PartsManagement", from: "PartsManagementMainVc") as! PartsManagementMainVc
        vc.state = searchType
        vc.callBack = callback
        CD.push(vc)
    }
}

class PartsManagementMainVc: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var stackBgV: UIStackView!
    @IBOutlet weak var headerV: UIView!
    @IBOutlet weak var curSubV: UIView!
    @IBOutlet weak var tf_search: UITextField!
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var state = 0
    
    lazy var segmentedView: JXSegmentedView = {
        let segmentedV = JXSegmentedView()
        segmentedV.delegate = self
        return segmentedV
    }()
    
    var segmentedtTitles:[String] = ["全部".languageString(), "待审核".languageString(), "待发货".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 searchKey = ""
    
    var curVC:PartsManagementListVc?
    
    var callBack:((Bool)->Void)?
    
    var model = M_PartsManagementList()
    override func viewDidLoad() {
        super.viewDidLoad()
        tf_search.delegate = self
        tf_search.returnKeyType = .search
        tf_search.placeholder = "请输入用户名/联系电话/地址等关键字".languageString()
        configUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    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)
        }
        
        view.addSubview(self.listContainerView)
        segmentedView.listContainer = listContainerView
        curSubV.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
        }
        
        addSubViewControlls()
        
        setCurrentVC()
    }
    
    func addSubViewControlls() {
        var cSubC = [JXSegmentedListContainerViewListDelegate]()
        
        for idx in 0..<4 {
            do {
                let curViewC = UIStoryboard(name: "PartsManagement", bundle: nil).instantiateViewController(withIdentifier: "PartsManagementListVc") as! PartsManagementListVc
                curViewC.vm.searchType = idx
//                curViewC.vm.searchKey = searchKey
                curViewC.getData = {[weak self] in
                    guard let weakSelf = self else { return }
                    curViewC.searchKey = weakSelf.searchKey
                }
                curViewC.vm.dataBack = { [weak self] m in
                    guard let weakSelf = self else { return }
                    weakSelf.model = m
                    weakSelf.setSegmentedtTitles()
                }
                curViewC.vm.reloadList = { [weak self] arr in
                    guard let weakSelf = self else { return }
                    weakSelf.reloadList(arr, idx: idx)
                }
                cSubC.append(curViewC)
            }
        }
        
        subControllerList = cSubC
    }
    
    func setCurrentVC() {
        let vc = subControllerList[segmentedView.selectedIndex] as! PartsManagementListVc
        curVC = vc
    }
    
    func setSelectIndex(_ idx:Int) {
        state = idx
        if !subControllerList.isEmpty {
            segmentedView.selectItemAt(index: state)
        }else{
            segmentedDataSource.reloadData(selectedIndex: state)
        }
    }
    
    func setSegmentedtTitles() {
        segmentedtTitles = ["\("全部".languageString()) \(model.allQty)", "\("待审核".languageString()) \(model.unCheckPartsQty)", "\("待发货".languageString()) \(model.unDeliveryPartsQty)", "\("待签收".languageString()) \(model.unSignPartsQty)"]
        segmentedDataSource.titles = segmentedtTitles
        segmentedView.reloadData()
    }
    
    func reloadList(_ arr:[Int], idx:Int) {
        let reloadArr = arr.filter({$0 != idx})
        for (i,item) in subControllerList.enumerated() {
            if let vc = item as? PartsManagementListVc, vc.isViewLoaded, reloadArr.contains(i) {
                vc.headerRefresh()
            }
        }
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        searchKey = sender.text!
        curVC!.vm.searchKey = searchKey
        curVC?.headerRefresh()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

extension PartsManagementMainVc: 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! PartsManagementListVc
        curVC = vc
//        if vc.isViewLoaded {
//            vc.vm.searchKey = searchKey
//        }
    }
}

extension PartsManagementMainVc: 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(true)
    }
    
    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
        }
    }
}

