//
//  OrderDetailMainVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/8/28.
//

import UIKit
import JXSegmentedView
import CaamDau
import Utility 

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

class OrderDetailMainVc: UIViewController {

    @IBOutlet weak var stackBgV: UIStackView!
    @IBOutlet weak var headerV: UIView!
    @IBOutlet weak var curSubV: UIView!
    @IBOutlet weak var tipsView: UIView!
    @IBOutlet weak var buttonView: UIView!
    @IBOutlet weak var mainBtn: UIButton!
    @IBOutlet weak var timeLabel: UILabel!
    
    var baseUrl = TWOCNetwork.shareNetManager().baseURL
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var curVC:OrderDetailInfoVc?
    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 orderNo = ""
    var model = M_OrderDetailInfo()
    
    var callback: ((Bool)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
//        MapsTool.shareInstance().getCurrentLocation()
        configUI()
        requestData()
    }
    
    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)
        }
        
        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: "OrderDetailInfoVc") as! OrderDetailInfoVc
            curViewC.vm.viewType = 0
            curViewC.vm.callBack = {[weak self] txt in
                guard let weakSelf = self else { return }
                weakSelf.doOperation(with: txt)
            }
            curViewC.refreshDatas = {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.requestData()
            }
            curViewC.vm.getLocal()
            cSubC.append(curViewC)
        }
        
        do {
            let curViewC = UIStoryboard(name: "Order", bundle: nil).instantiateViewController(withIdentifier: "OrderDetailInfoVc") as! OrderDetailInfoVc
            curViewC.vm.viewType = 1
            curViewC.getDatas = {
                curViewC.vm.model = self.model
            }
            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! OrderDetailInfoVc
        curVC = vc
    }
    
    
    func setSelectIndex(_ idx:Int) {
        state = idx
        if !subControllerList.isEmpty {
            segmentedView.selectItemAt(index: state)
        }else{
            segmentedDataSource.reloadData(selectedIndex: state)
        }
    }
    
    func setUpMainButton() {
        buttonView.cd.isHidden(model.mainButtonCode.isEmpty)
        mainBtn.cd.text(model.mainButtonName)
        tipsView.cd.isHidden(model.timeLable.isEmpty)
        timeLabel.cd.text(model.timeLable)
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        if model.mainButtonType == 2 {
            R_Web.push(.http(self.model.mainButtonSkipH5Page+"&token=\(MyInfo.shareInstance().token)"))
        }else{
            if model.mainButtonCode != "0" {
                doOperation(with: model.mainButtonCode)
            }
        }
    }
    
}

extension OrderDetailMainVc: 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! OrderDetailInfoVc
        curVC = vc
//        curVC?.vm.model = model
//        if vc.isViewLoaded {
//            vc.tableView.mj_header?.beginRefreshing()
//        }
        
    }
}

extension OrderDetailMainVc: 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 OrderDetailMainVc {
    func requestData() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/order/getOrderDetail",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.orderNo = data.stringValue(forKey: "orderNo")
                weakSelf.model = M_OrderDetailInfo(data)
                weakSelf.setUpMainButton()
                weakSelf.curVC?.vm.model = weakSelf.model
                weakSelf.curVC?.vm.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.curVC?.vm.makeForms()
        }
        cNet.postRequest()
    }
    
    func requestAccept() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/accept",andParam: par)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_info("操作成功~".languageString())
            weakSelf.callback?(true)
            weakSelf.requestData()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requestEngineerAccept() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/engineerAccept",andParam: par)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_info("操作成功~".languageString())
            weakSelf.callback?(true)
            weakSelf.requestData()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func updateUnrealPhone(_ realPhone:String) {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["realPhone"] = realPhone
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/updateUnrealPhone",andParam: par)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_info("操作成功~".languageString())
            weakSelf.requestData()
            //清除该单完工缓存
            weakSelf.deleteCacheDict()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func checkFinishData(){
        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 }
            weakSelf.pushToFinishVc()
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func pushToFinishVc() {
        let vc = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrderVc") as! FinishOrderVc
        vc.hidesBottomBarWhenPushed = true
        vc.orderId = orderId
        vc.orderNoStr = self.orderNo
        vc.updateCallback = {
            self.requestData()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //删除缓存
    func deleteCacheDict() {
        let dictPath:String = NSHomeDirectory() + "/Documents/order\(orderId).plist"
        guard FileManager.default.fileExists(atPath: dictPath) else {
            // 无旧数据
            debugPrint("暂无缓存数据".languageString())
            return
        }
        
        do {
            try FileManager.default.removeItem(atPath: dictPath)
        } catch  {
            debugPrint("删除旧数据失败".languageString())
        }
    }
    
    func showLocationTips() {
        let alertC = UIAlertController(title: "提示".languageString(), message: "您还未开启定位服务，请前往设置开启，以便于准确获取您的位置信息".languageString(), preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: .default))
        alertC.addAction(UIAlertAction(title: "确定".languageString(), style: .default) {(_) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
            }
        })
        CD.visibleVC?.present(alertC, animated: true, completion: nil)
    }
}

extension OrderDetailMainVc {
    func showAlert(titleStr:String = "", msg:String = "", txt:String = "") {
        let alertC = UIAlertController(title: titleStr, message: msg, preferredStyle: .alert)
        let action1 = UIAlertAction(title: "取消".languageString(), style: .default)
        let action2 = UIAlertAction(title: "确认".languageString(), style: .default, handler: {[weak self] action in
            guard let weakSelf = self else { return }
            switch txt {
            case "accept"://确认接单(网点)
                weakSelf.requestAccept()
            case "engineerAccept"://确认接单(师傅)
                weakSelf.requestEngineerAccept()
            default:
                break
            }
        })
        alertC.addAction(action1)
        alertC.addAction(action2)
        self.present(alertC, animated: true, completion: nil)
    }
    
    func changeVirtualNumber() {
        R_ChangeVirtualNumber.router(model.userMobile) { [weak self] num in
            guard let weakSelf = self else { return }
            if !num.isEmpty {
                weakSelf.updateUnrealPhone(num)
            }
        }
    }
    
    func pushOrderMapDistance(with str:String) {
        let type = str == "startOff" ? 1 : 2
        R_OrderMapDistance.router(orderId, data: model, showType: type) { [weak self] bool in
            guard let weakSelf = self else { return }
            if bool {
                weakSelf.callback?(true)
                weakSelf.requestData()
            }
        }
    }
    
    func doOperation(with str:String) {
        switch str {
        case "accept","engineerAccept"://确认接单(网点)
            showAlert(titleStr: "是否确认接单？".languageString(), txt: str)
        case "process"://过程反馈
            R_ProcessFeedback.router(model.orderId, callback: nil)
        case "assinSite", "reAssinSite", "assinEngineer"://派单(派服务商),转派其他,派工程师
            let assinType = str == "assinEngineer" ? 2 : 1
            R_OrderAssignUser.router(orderId, type: assinType) { [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callback?(true)
                    weakSelf.requestData()
                }
            }
        case "back"://申请退单
            R_OrderApplyReturn.router(orderId) {  [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callback?(true)
                    weakSelf.requestData()
                }
            }
        case "close"://申请关闭
            R_OrderApplyClose.router(orderId, mobile: model.userMobile) {  [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callback?(true)
                    weakSelf.requestData()
                }
            }
        case "book","reBook"://预约用户,再次预约
            R_OrderBook.router(orderId, userName: model.userName, mobile: model.userMobile, bookDate: model.bookDateShow, bookDatePeriod: model.bookDatePeriod, wishBookDate: model.wishBookDate) {  [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callback?(true)
                    weakSelf.requestData()
                }
            }
        case "startOff", "arrive"://出发,到达签到
            guard !model.lat.isEmpty && !model.lnt.isEmpty && model.notMaintainedAK != 1 else {
                if [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())  {
                    pushOrderMapDistance(with: str)
                }else if CLLocationManager.authorizationStatus() == .denied {
                    showLocationTips()
                }else{
                    MapsTool.shareInstance().getCurrentLocation()
                }
                return
            }
            if !UserDefaults.standard.bool(forKey: "agreeStatus") {
                //添加隐私合规弹窗
//                AMapPrivacyUtility.showPrivacyInfoInWindow { [weak self] bool in
//                    guard let weakSelf = self else { return }
//                    if bool {
//                        weakSelf.pushOrderMapDistance(with: str)
//                    }
//                };
                AMapPrivacyUtility.showPrivacyInfoInWindow { [weak self] bool in
                    guard let weakSelf = self else { return }
                    if bool {
                        if [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())  {
                            weakSelf.pushOrderMapDistance(with: str)
                        }else if CLLocationManager.authorizationStatus() == .denied {
                            weakSelf.showLocationTips()
                        }else{
                            MapsTool.shareInstance().getCurrentLocation()
                        }
                    }
                };
            }else{
                if [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())  {
                    pushOrderMapDistance(with: str)
                }else if CLLocationManager.authorizationStatus() == .denied {
                    showLocationTips()
                }else{
                    MapsTool.shareInstance().getCurrentLocation()
                }
            }
        case "finish"://完工回单
            checkFinishData()
//            let vc = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrderVc") as! FinishOrderVc
//             vc.hidesBottomBarWhenPushed = true
//            vc.orderId = orderId
//            vc.orderNoStr = self.orderNo
//            vc.updateCallback = {
//                self.requestData()
//            }
//            self.navigationController?.pushViewController(vc, animated: true)
            break
        case "caseDemo"://案例池
            R_OrderCasePoolMain.router(orderId, callback: nil)
        case "help"://请求协助
            R_OrderAskForHelp.router(orderId) { [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.requestData()
                }
            }
        case "parts"://配件信息
            let itemId = model.itemList.first?.itemId
            R_OrderPartsInfoMain.router(orderId, itemId: itemId ?? "")
        case "support"://服务支持
            R_OrderServiceSupport.router(orderId)
        case "evaluate"://扫码评价
            //method:  打开方式,固定传app;以后还有短信(sm)方式、公众号(wx)等
            if baseUrl.last != "/" {
                baseUrl.append("/")
            }
            let urlStr = "\(baseUrl)h5/evaluate/page?orderId=\(orderId)&method=app&pushMan=\(MyInfo.shareInstance().userName.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!)&token=\(MyInfo.shareInstance().token)"
            R_OrderEvaluationQRCode.router(urlStr)
        case "finished"://完工详情
            let vc = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrderVc") as! FinishOrderVc
             vc.hidesBottomBarWhenPushed = true
            vc.orderId = orderId
            vc.orderNoStr = self.orderNo
            vc.updateCallback = {
                self.requestData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case "eleServiceBill"://电子服务单
            if baseUrl.last != "/" {
                baseUrl.append("/")
            }
            let urlStr = "\(baseUrl)h5/eleServiceBill/page.html?orderId=\(orderId)&pushMan=\(MyInfo.shareInstance().userName.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!)&token=\(MyInfo.shareInstance().token)"
            R_Web.push(.http(urlStr), title: "电子服务单".languageString())
//            let web = Vc_Web()
//            web.title = "电子服务单"
//            web.webType = .http(urlStr)
//            web.fd_interactivePopDisabled = true
//            CD.push(web)
        case "insure"://保险和理赔
//            let urlStr = "\(TWOCNetwork.shareNetManager().baseURL)/h5/insure/page.html?orderId=\(orderId)&token=\(MyInfo.shareInstance().token)"
            var urlStr = "\(baseUrl)\(self.model.insurePage)&token=\(MyInfo.shareInstance().token)"
            if baseUrl.last == "/" && self.model.insurePage.first == "/" {
                urlStr = "\(baseUrl.dropLast(1))" + "\(self.model.insurePage)&token=\(MyInfo.shareInstance().token)"
            }
//            R_Web.push(.http(urlStr), title: "保险和理赔")
            let web = Vc_Web()
            web.title = "保险和理赔".languageString()
            web.webType = .http(urlStr)
            CD.push(web)
            break
        case "complain"://工单申诉
            R_OrderComplainMain.router(orderId, type: .complain)
        case "complainCheck"://申诉审核
            R_OrderComplainMain.router(orderId, type: .complainCheck)
        case "finishCheck"://完工审核
            R_OrderFinishCheck.router(orderId)
        case "exchangeComfirm"://退换机确认
            break
        case "exchangeOld"://退回旧机
            break
        case "exchangeOldSign"://退换机-旧机签收
            break
        case "exchangeNew"://退换换-新机寄出
            break
        case "exchangeNewSign"://新机签收
            break
        case "sendRepairComfirm"://寄修确认
            break
        case "sendRepairSign"://寄修签收
            break
        case "sendRepairGoodout"://修好寄出
            break
        case "sendRepairCustsign"://代用户签收
            break
        case "updateUnrealPhone"://修改虚拟号
            changeVirtualNumber()
        case "getActivationCode"://获取激活码
            R_OrderGetActivationCode.router(orderId) { [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.requestData()
                }
            }
//        case "getPasswordInPower"://获取开机密码
//            R_OrderGetPasswordInPower.router(orderId) { [weak self] bool in
//                guard let weakSelf = self else { return }
//                if bool {
//                    weakSelf.requestData()
//                }
//            }
        default:
            break
        }
    }
}
