//
//  CreatOrderHomeVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/29.
//

import UIKit
import JXSegmentedView

class CreatOrderHomeVc: UIViewController {
    var currentIndex = 0
    
    lazy var headView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var childVcView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var segmentedView: JXSegmentedView = {
        let segmentedV = JXSegmentedView()
        segmentedV.delegate = self
        return segmentedV
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let segmentedDa = JXSegmentedTitleDataSource()
        segmentedDa.titles = ["用户".languageString(), "产品信息".languageString(),"现场定位".languageString()]
        segmentedDa.isTitleColorGradientEnabled = true
        segmentedDa.titleNormalColor = UIColor(hexString: "#666666")
        segmentedDa.titleNormalFont = UIFont.PingFangRegular(size: 14)
        segmentedDa.titleSelectedColor = UIColor(hexString: "#333333")
        segmentedDa.titleSelectedFont = UIFont.PingFangMedium(size: 14)
        return segmentedDa
    }()
    
    lazy var indicator:JXSegmentedIndicatorLineView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = UIColor(hexString: "#478BFF")
        indicator.indicatorWidth = 24
        return indicator
    }()
    
    lazy var listContainerView = JXSegmentedListContainerView(dataSource: self)
    lazy var subControllerList = [JXSegmentedListContainerViewListDelegate]()
    
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var model = M_CreatOrder()
    
    var subViewVc1 = CreatOrderUserVc()
    var subViewVc2 = CreatOrderItemVc()
    var subViewVc3 = CreatOrderLocationVc()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBackButton()
        configUI()
        
        MapsTool.shareInstance().ontimelocation = ""
        MapsTool.shareInstance().getCurrentLocation()
    }
    
    func configUI() {
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
            .add(headView)
            .add(childVcView)
        
        topBar.delegate = self
        
        segmentedView.defaultSelectedIndex = currentIndex
        segmentedDataSource.reloadData(selectedIndex: currentIndex)
        segmentedView.indicators = [indicator]
        segmentedView.dataSource = segmentedDataSource
        
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        
        headView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBar.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        
        headView.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        childVcView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
        }
        segmentedView.listContainer = listContainerView
        childVcView.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
         }
        
        addSubViewControlls()
    }
    
    func addSubViewControlls() {
        var cSubC = [JXSegmentedListContainerViewListDelegate]()
        
        do {
            subViewVc1 = UIStoryboard(name: "CreatOrder", bundle: nil).instantiateViewController(withIdentifier: "CreatOrderUserVc") as! CreatOrderUserVc
            subViewVc1.state = 1
            subViewVc1.updateCallback = { (newModel) in
                self.model = newModel
                self.updateChildControllersData()
            }
            cSubC.append(subViewVc1)
        }
        
        do {
            subViewVc2 = UIStoryboard(name: "CreatOrder", bundle: nil).instantiateViewController(withIdentifier: "CreatOrderItemVc") as! CreatOrderItemVc
            subViewVc2.state = 2
            subViewVc2.updateCallback = { (newModel) in
                self.model = newModel
                self.updateChildControllersData()
            }
            cSubC.append(subViewVc2)
        }
        
        do {
             subViewVc3 = UIStoryboard(name: "CreatOrder", bundle: nil).instantiateViewController(withIdentifier: "CreatOrderLocationVc") as! CreatOrderLocationVc
            subViewVc3.state = 3
            subViewVc3.updateCallback = { (newModel) in
                self.model = newModel
                self.updateChildControllersData()
            }
            cSubC.append(subViewVc3)
        }
        
        subControllerList = cSubC
    }
    
    //同步数据
    func updateChildControllersData(){
        debugPrint("=====更新数建单数据====")
        debugPrint(model.jsonValue())
        
        subViewVc1.vm.model = self.model
        subViewVc2.vm.model = self.model
        subViewVc3.model = self.model
    }
    
}

//请求
extension CreatOrderHomeVc{
    func requstSaveData(){
        if !model.usermobile.isValidatePhoneNumber(){
            hud_info("请正确输入11位手机号码~".languageString())
            return
        }
        if model.hasIemi {
            for item in model.items {
                if item.iemi.isEmpty {
                    hud_info("请输入IEMI物联码~".languageString())
                    return
                }
            }
        }
        for item in model.resultPicList {
            if item.ismust == "1" && item.pic.isEmpty {
                hud_info("请上传图片"+"-\(item.picname)~")
                return
            }
        }
        var param = [String:Any]()
    
        param += model.jsonValue()
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/multiplex/newCreateOrder",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            hud_info("操作成功~".languageString())
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                weakSelf.navigationController?.popViewController(animated: true)
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}

extension CreatOrderHomeVc: 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! HomeMessageListVc
    }
}


extension CreatOrderHomeVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar.cd.background(.clear)
        topBar._title = "现场建单".languageString()
        topBar._colorTitle = Config.color.hex("3")
        topBar.bar_navigation.line.cd.isHidden(false)
        
        topBar._style = "11"
        topBar._rightItemsWidth1 = 80
        topBar.bar_navigation.item_right.btn_1.cd
            .text(CD_TopBar.Model.font_item)
            .text(Config.font.font(14))
            .text(Config.color.hex("#478BFF"))
            .text("提交".languageString())
    }
    
    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
        case .rightItem1:
            self.requstSaveData()
            break
        default:
            break
        }
    }
}

