//
//  PartsReturnMainVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/27.
//

import UIKit
import JXSegmentedView

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

class PartsReturnMainVc: 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()]
    
    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:PartsReturnListVc?
    
    var callBack:((Bool)->Void)?
    
    var model = M_PartsReturnList()
    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..<3 {
            do {
                let curViewC = UIStoryboard(name: "PartsManagement", bundle: nil).instantiateViewController(withIdentifier: "PartsReturnListVc") as! PartsReturnListVc
                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! PartsReturnListVc
        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.unInPartsQty)"]
        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? PartsReturnListVc, 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 PartsReturnMainVc: 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! PartsReturnListVc
        curVC = vc
//        if vc.isViewLoaded {
//            vc.vm.searchKey = searchKey
//        }
    }
}

extension PartsReturnMainVc: 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
        }
    }
}

