//
//  FinishOrderVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/9/4.
//

import UIKit
import JXSegmentedView

class FinishOrderVc: UIViewController {
    var currentIndex = 0
    
    lazy var headView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        return view
    }()
    
    lazy var submitButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = hexColor(hex: "478BFF")
        btn.setTitleColor(.white, for: .normal)
        btn.setTitle("提交".languageString(), for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 22
        btn.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    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()]
        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_FinishOrder(json: [:])
    var orderId = ""
    var orderNoStr = ""
    
    var subViewVc1 = FinishOrdeInfoVc()
    var subViewVc2 = FinishOrdeFeeVc()
    
    var canEdit = false
    var isBusy = false
    
    var updateCallback:(()->())?
    override func viewDidLoad() {
        super.viewDidLoad()
     
        configUI()
        MapsTool.shareInstance().ontimelocation = ""
        MapsTool.shareInstance().getCurrentLocation()
        self.requstGetFinishData()
    }
    
    func configUI() {
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
            .add(headView)
            .add(bottomView)
            .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)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(72)
        }
        
        bottomView.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.height.equalTo(44)
        }
        
        
        headView.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        childVcView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.bottom.equalTo(bottomView.snp.top)
        }
        segmentedView.listContainer = listContainerView
        childVcView.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
         }
    }
    
    func addSubViewControlls() {
        var cSubC = [JXSegmentedListContainerViewListDelegate]()
        
        do {
            subViewVc1 = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrdeInfoVc") as! FinishOrdeInfoVc
            subViewVc1.state = 1
            subViewVc1.vm.canEdit = canEdit
            subViewVc1.orderId = orderId
            subViewVc1.vm.model = model
            subViewVc1.orderNoStr = orderNoStr
            subViewVc1.updateCallback = { (newModel) in
                self.model = newModel
                self.updateChildControllersData()
            }
            cSubC.append(subViewVc1)
        }
        
        do {
            subViewVc2 = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrdeFeeVc") as! FinishOrdeFeeVc
            subViewVc2.state = 2
            
            subViewVc2.vm.canEdit = canEdit
            subViewVc2.vm.model = model
            subViewVc2.updateCallback = { (newModel) in
                self.model = newModel
                self.updateChildControllersData()
            }
            cSubC.append(subViewVc2)
        }
    
        subControllerList = cSubC
    }
    
    //同步数据
    func updateChildControllersData(){
        debugPrint("=====更新完工单数据====")
        debugPrint(model.jsonValue())
        
        subViewVc1.vm.model = self.model
        subViewVc2.vm.model = self.model
    }
    
    @objc func submitAction(){
        self.view.endEditing(true)
        updateChildControllersData()
        showOrderSubmitAlert()
    }
    
    
    func checkOrderSubmit(){
        let checkStr = model.checkValue()
        if checkStr != ""{
            hud_error(checkStr)
            return
        }
        requstSaveData()
    }
    
    func showBackAlert(){
//        let alertController = UIAlertController.init(title: "是否退出完工？", message: "", preferredStyle: .alert)
//        alertController.addAction(UIAlertAction.init(title: "取消", style: .default, handler: { (action) in
//            //关闭
//        }))
//        alertController.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in
//            self.navigationController?.popViewController(animated: true)
//        }))
//        self.present(alertController, animated: true, completion: nil)
        
        FinishOrderAlertVc.show(self, title: "", message: "是否进行完工数据缓存？".languageString()) { action in
            if action == .left{
                //不保存
                self.deleteCacheDict()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else if action == .right{
                //缓存后退出
                self.saveCacheDict()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else{
                //关闭弹窗
            }
        }
    }
    
    func showOrderSubmitAlert(){
        let alertController = UIAlertController.init(title: "是否确认提交？".languageString(), message: "", preferredStyle: .alert)
        alertController.addAction(UIAlertAction.init(title: "取消".languageString(), style: .default, handler: { (action) in
            //关闭
        }))
        alertController.addAction(UIAlertAction.init(title: "确定".languageString(), style: .default, handler: { (action) in
            self.checkOrderSubmit()
        }))
        self.present(alertController, animated: true, completion: nil)
    }
}

//请求
extension FinishOrderVc{
    func requstGetFinishData(){
        var param = [String:Any]()
        param["orderId"] = orderId
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/orderFinishDo/getFinishDetail",andParam: param)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                let model = M_FinishOrder(json: data)
                weakSelf.model = model
                if model.finishButton != "1"{
                    //隐藏提交按钮
                    weakSelf.submitButton.isHidden = true
                    weakSelf.bottomView.snp.makeConstraints { (make) in
                        make.bottom.left.right.equalToSuperview()
                        make.height.equalTo(0)
                    }
                    weakSelf.bottomView.isHidden = true
                    weakSelf.canEdit = false
                }else{
                    weakSelf.submitButton.isHidden = false
                    weakSelf.canEdit = true
                    //读缓存
                    weakSelf.readCacheDict()
                }
                weakSelf.addSubViewControlls()
                weakSelf.listContainerView.reloadData()
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requstSaveData(){
        if isBusy {
            return //防多点
        }
       
        var param = [String:Any]()
        param += model.jsonValue()
        
        isBusy = true
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/orderFinishDo/finish",andParam: param)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            hud_info("操作成功~".languageString())
            weakSelf.isBusy = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                MineGetCodeTool.defaultTool().timerNumber = 0
                weakSelf.navigationController?.popViewController(animated: true)
                weakSelf.updateCallback?()
                //正常完工和保存删除缓存
                weakSelf.deleteCacheDict()
                
//                if weakSelf.model.finishStatus == 1{
//                    weakSelf.deleteCacheDict()
//                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            self.isBusy = false
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}

///缓存
extension FinishOrderVc{
    
    func saveCacheDict(){
        var curSaveDict = [String:Any]()
        
        curSaveDict += self.model.makeCachJsonValue()
        
        // 保存到本地
        let newDict = NSDictionary(dictionary: curSaveDict)
        let dictPath:String = NSHomeDirectory() + "/Documents/order\(orderId).plist"
        if FileManager.default.fileExists(atPath: dictPath) {
            do {
                try FileManager.default.removeItem(atPath: dictPath)
            }catch{
                debugPrint("删除完工本地旧数据失败")
            }
        }
        
        if newDict.write(to: URL(fileURLWithPath: dictPath), atomically: true) {
            debugPrint("当前内容已缓存！")
        }else{
            debugPrint("缓存发生错误！")
        }
    }
    
    func readCacheDict(){
        let dictPath:String = NSHomeDirectory() + "/Documents/order\(orderId).plist"
        guard FileManager.default.fileExists(atPath: dictPath) else {
            // 无旧数据
            return
        }
        
        //  开始读取旧数据
        guard let oldDict = NSDictionary(contentsOfFile: dictPath) else {
            // 读取旧数据失败
            return
        }
        
        if let cacheJson = oldDict as? [String:Any]{
          
            self.model.serviceTypeId = cacheJson.stringValue(forKey: "serviceTypeId")
            self.model.serviceTypeName = cacheJson.stringValue(forKey: "serviceTypeName")
           
            self.model.finishNote = cacheJson.stringValue(forKey: "finishNote")
            let status = cacheJson.intValue(forKey: "finishStatus")
            if status > 0 {
                self.model.finishStatus = status
            }
            self.model.outTransIn = cacheJson.intForKey("outTransIn") //0否1是
            self.model.guaranteeType = cacheJson.intForKey("guaranteeType")
            
            if cacheJson.stringValue(forKey: "isPolicy") != ""{
                self.model.isPolicy = cacheJson.intForKey("isPolicy") //0否1是
            }
            if cacheJson.stringValue(forKey: "isSafeEnvironment") != ""{
                self.model.isSafeEnvironment = cacheJson.intForKey("isSafeEnvironment") //0否1是
            }
            
            self.model.buyChannelName = cacheJson.stringValue(forKey: "buyChannelName")
            self.model.buyChannelId = cacheJson.stringValue(forKey: "buyChannelId")
            self.model.virtuallyUserMobile = cacheJson.stringValue(forKey: "virtuallyUserMobile")
            
            self.model.specailAmountPic1 = cacheJson.stringValue(forKey: "specailAmountPic1")
            self.model.specailAmountPic2 = cacheJson.stringValue(forKey: "specailAmountPic2")
            self.model.specailAmountPic3 = cacheJson.stringValue(forKey: "specailAmountPic3")
            self.model.specailAmountRemark = cacheJson.stringValue(forKey: "specailAmountRemark")
            self.model.userPayAmount = cacheJson.stringValue(forKey: "userPayAmount")
            self.model.userPayDiscount = cacheJson.stringValue(forKey: "userPayDiscount")
            self.model.userPayPic1 = cacheJson.stringValue(forKey: "userPayPic1")
            self.model.userPayPic2 = cacheJson.stringValue(forKey: "userPayPic2")
            self.model.userPayPic3 = cacheJson.stringValue(forKey: "userPayPic3")
            self.model.userPayRemark = cacheJson.stringValue(forKey: "userPayRemark")
           
            self.model.siteAmount = cacheJson.stringValue(forKey: "siteAmount")
            self.model.rewardAmount = cacheJson.stringValue(forKey: "rewardAmount")
            self.model.longDistance = cacheJson.stringValue(forKey: "longDistance")
            self.model.longDistanceAmount = cacheJson.stringValue(forKey: "longDistanceAmount")
            self.model.rewardReason = cacheJson.stringValue(forKey: "rewardReason")
            self.model.specailAmount = cacheJson.stringValue(forKey: "specailAmount")
            self.model.siteFinalAmount = cacheJson.stringValue(forKey: "siteFinalAmount")
     
            if let itemDatas = cacheJson["itemResultList"] as? [[String:Any]] {
                self.model.items = itemDatas.compactMap({ data in
                    M_FinishOrder.M_Item(json: data)
                })
                
                if  self.model.items.count > 0 {
                    self.model.itemid = self.model.items[0].itemid
                    if  self.model.items[0].bigitemcatid != ""{
                        self.model.itemCategoryId =  self.model.items[0].bigitemcatid
                    }
                    if  self.model.items[0].smallitemcatid != ""{
                        self.model.itemCategoryId =  self.model.items[0].smallitemcatid
                    }
                    
                    if  self.model.items[0].inbarcode != ""{
                        self.model.code1 =  self.model.items[0].inbarcode
                    }
                }
            }
            
            if let partDatas = cacheJson["partsList"] as? [[String:Any]] {
                self.model.partsList = partDatas.compactMap({ data in
                    M_FinishOrder.M_Part(json: data)
                })
            }
            
            if let faultDatas = cacheJson["faultList"] as? [[String:Any]] {
                self.model.faultList = faultDatas.compactMap({ data in
                    M_FinishOrder.M_Fault(json: data)
                })
            }
            
            if let feeList = cacheJson["specailFeeList"] as? [[String:Any]] {
                self.model.specailFeeList = feeList.compactMap({ data in
                    M_FinishOrder.M_FeeItem(json: data)
                })
            }
            
            if let feeList = cacheJson["userPayList"] as? [[String:Any]] {
                self.model.userPayList = feeList.compactMap({ data in
                    M_FinishOrder.M_FeeItem(json: data)
                })
            }
            
            if let feeList = cacheJson["showFeeList"] as? [[String:Any]] {
                self.model.showFeeList = feeList.compactMap({ data in
                    M_FinishOrder.M_FeeLine(json: data)
                })
            }
        }
    }
    
    //删除缓存
    func deleteCacheDict() {
        let dictPath:String = NSHomeDirectory() + "/Documents/order\(orderId).plist"
        guard FileManager.default.fileExists(atPath: dictPath) else {
            // 无旧数据
            debugPrint("暂无缓存数据")
            return
        }
        
        do {
            try FileManager.default.removeItem(atPath: dictPath)
        } catch  {
            debugPrint("删除旧数据失败")
        }
    }
}


extension FinishOrderVc: 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) {
    }
}


extension FinishOrderVc: 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 = "10"
    }
    
    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) {
        switch item {
        case .leftItem1:
            if canEdit{
                self.showBackAlert()
                MineGetCodeTool.defaultTool().timerNumber = 0 //短信验证码置零
            }else{
                self.navigationController?.popViewController(animated: true)
            }
           
        default:
            break
        }
    }
}


