//
//  HomePagingVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/10/13.
//

import UIKit
import MJRefresh
import JXSegmentedView

extension JXPagingListContainerView: JXSegmentedViewListContainer {}

class HomePagingVc: UIViewController {
    @IBOutlet weak var lab_companyName: UIButton!
    @IBOutlet weak var lab_userName: UIButton!
    @IBOutlet weak var icon_user: UIButton!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var headView: UIView!

    lazy var allButton: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.black, for: .normal)
        btn.setTitle("全部".languageString(), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.init(hexString: "333333"), for: .normal)
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(toAllOrderListVc), for: .touchUpInside)
        btn.layer.cornerRadius = 8
        btn.backgroundColor = .white
        return btn
    }()
    
    lazy var bgScrollView: UIScrollView = {
        let sview = UIScrollView(frame:CGRect.init(x: 0, y: 0, width: SCREEN_W, height: SCREEN_H))
        sview.backgroundColor = UIColor(hexString: "f8f8f8")
        return sview
    }()
    
    var pagingView: JXPagingView!
    var userHeaderView: HomePagingListOrderHeaderView!
   
    var userHeaderContainerView: UIView!
    var segmentedViewDataSource: JXSegmentedTitleOrdersDataSource!
  
    var indicator: JXSegmentedIndicatorBackgroundView!
    var segmentedView: JXSegmentedView!
 
    var JXTableHeaderViewHeight: Int = 250
    var JXheightForHeaderInSection: Int = 57
    let JXWidth:CGFloat = 70
    
    var titles = ["新单", "待接单","待派工","待派工"]
    
    //列表
    var isHeaderRefreshed = true
    var isFirstRefreshed = true
    var currentIndex = 0
   
    var orderBaseListView1 = HomePagingListOrderBaseView()
    var orderBaseListView2 = HomePagingListOrderBaseView()
    var orderBaseListView3 = HomePagingListOrderBaseView()
    var orderBaseListView4 = HomePagingListOrderBaseView()
    //当前显示列表
    var currentOrderBaseListView = HomePagingListOrderBaseView()
    
    var model = HomeModel(json: [:])
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        requstIndexData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bgView.snp.makeConstraints { (make) in
            make.top.equalTo(self.headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        configPagingUI()
    }
    
    func configPagingUI(){
        lab_companyName.cd.text(MyInfo.shareInstance().companyName)
        lab_userName.cd.text(MyInfo.shareInstance().userName)
        icon_user.sd_setImage(with: URL(string: MyInfo.shareInstance().userPic), for: .normal, placeholderImage: UIImage(named: "icon_home_user"), context: nil)
        
        if MyInfo.shareInstance().userRole != .Engineer{
            lab_userName.isHidden = true
            icon_user.isHidden = true
        }

        userHeaderContainerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(JXTableHeaderViewHeight)))
        userHeaderView = Bundle.main.loadNibNamed("HomePagingListOrderHeaderView", owner: nil, options: nil)!.first as? HomePagingListOrderHeaderView
        userHeaderView.callback = {
            let vc = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeMessageVc") as! HomeMessageVc
            vc.hidesBottomBarWhenPushed = true
            vc.currentIndex = 0
            vc.callback = { (reload) in
//                self.requstIndexData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        userHeaderView.frame = userHeaderContainerView.bounds
        userHeaderContainerView.addSubview(userHeaderView)

        segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width-100, height: CGFloat(JXheightForHeaderInSection)))
        
        segmentedView.backgroundColor = hexColor(hex: "f8f8f8")
        //配置数据源
        self.segmentedViewDataSource = JXSegmentedTitleOrdersDataSource()
        self.configSegmentedTitleView()
    
        segmentedViewDataSource.itemWidth = JXWidth
        segmentedViewDataSource.isItemSpacingAverageEnabled = false
        segmentedViewDataSource.itemSpacing = 10
        segmentedView.dataSource = segmentedViewDataSource
        
        //配置指示器
        self.indicator = JXSegmentedIndicatorBackgroundView()
        indicator.backgroundColor = .white
        indicator.indicatorColor = UIColor(red: 71/255, green: 139/255, blue: 255/255, alpha: 1.0)
        indicator.indicatorHeight = 40
        indicator.indicatorCornerRadius = 5
        indicator.indicatorWidth = 60
        
//        segmentedView.indicators = [indicator]
        
        segmentedView.addSubview(allButton)
        allButton.frame = CGRect.init(x: UIScreen.main.bounds.size.width - 60, y: 6, width: 47, height: 44)

        pagingView = JXPagingView(delegate: self)
        
        self.bgView.addSubview(bgScrollView)
        self.bgScrollView.addSubview(segmentedView)
        self.bgScrollView.addSubview(pagingView)
        
        segmentedView.delegate = self
        segmentedView.listContainer = pagingView.listContainerView
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        pagingView.mainTableView.mj_header = header
        
        let navH:CGFloat = ((self.navigationController?.navigationBar.frame.height ?? 44.0)+UIApplication.shared.statusBarFrame.height )
        let barH:CGFloat = TAB_BAR_H
        pagingView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_W, height: SCREEN_H-(navH+barH))
    }
    
    func configSegmentedTitleView(){
        if MyInfo.shareInstance().userRole != .Engineer {
            var sendOrders = ""
            if MyInfo.shareInstance().userRole == .Site{
                sendOrders = model.unTakeEngineerQty
            }else{
                sendOrders = model.unTakeSiteQty
            }
            
            let orderText1 = NSMutableAttributedString(string: "新单".languageString() + "\n"+model.unAcceptQty)
            formatNormal(attriText: orderText1)
            //英文处理
            var orderText2 = NSMutableAttributedString(string: "待派工".languageString()+"\n"+sendOrders)
            let lang = getCurrentLanguage()
            if lang == "英文"{//Pending Technician
                orderText2 = NSMutableAttributedString(string: "Pending"+"\nTechnician"+"\n"+sendOrders)
            }
            
            formatNormal(attriText: orderText2)
            let orderText3 = NSMutableAttributedString(string: "待处理".languageString()+"\n"+model.inDealQty)
            formatNormal(attriText: orderText3)
            
            let orderText4 = NSMutableAttributedString(string: "异常单".languageString()+"\n"+model.exceptionQty)
            formatNormal(attriText: orderText4)
            
            segmentedViewDataSource.attributedTitles = [orderText1.copy(), orderText2.copy(), orderText3.copy(),orderText4.copy()] as! [NSAttributedString]

            formatSelected(attriText: orderText1)
            formatSelected(attriText: orderText2)
            formatSelected(attriText: orderText3)
            formatSelected(attriText: orderText4)
            
            segmentedViewDataSource.selectedAttributedTitles = [orderText1.copy(), orderText2.copy(), orderText3.copy(),orderText4.copy()] as? [NSAttributedString]
        }else{
            
           //师傅端 - 可切换3个列表
            titles = ["新单", "待处理","异常单"]
            
            let orderText1 = NSMutableAttributedString(string: "新单".languageString()+"\n"+model.unAcceptQty)
            formatNormal(attriText: orderText1)
            let orderText2 = NSMutableAttributedString(string: "待处理".languageString()+"\n"+model.inDealQty)
            formatNormal(attriText: orderText2)
            let orderText3 = NSMutableAttributedString(string: "异常单".languageString()+"\n"+model.exceptionQty)
            formatNormal(attriText: orderText3)
            
            segmentedViewDataSource.attributedTitles = [orderText1.copy(), orderText2.copy(), orderText3.copy()] as! [NSAttributedString]

            formatSelected(attriText: orderText1)
            formatSelected(attriText: orderText2)
            formatSelected(attriText: orderText3)
            
            segmentedViewDataSource.selectedAttributedTitles = [orderText1.copy(), orderText2.copy(), orderText3.copy()] as? [NSAttributedString]
        }
      
        self.segmentedView.dataSource = segmentedViewDataSource
    }
    
    func formatNormal(attriText: NSMutableAttributedString) {
        var font = UIFont.systemFont(ofSize: 14)
        let lang = getCurrentLanguage()
        if lang == "英文"{
            font = UIFont.systemFont(ofSize: 12)
        }
        attriText.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hexString: "333333"), NSAttributedString.Key.font : font], range: NSRange(location: 0, length: attriText.string.count))
    }
    func formatSelected(attriText: NSMutableAttributedString) {
        var font = UIFont.systemFont(ofSize: 14)
        let lang = getCurrentLanguage()
        if lang == "英文"{
            font = UIFont.systemFont(ofSize: 12)
        }
        attriText.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.white, NSAttributedString.Key.font : font], range: NSRange(location: 0, length: attriText.string.count))
    }
    
    
   @objc func toAllOrderListVc(){
       let vc = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeOrderListVc") as! HomeOrderListVc
       vc.title = "全部工单".languageString()
        vc.hidesBottomBarWhenPushed = true
       vc.callback = { (reload) in
//           self.requstIndexData()
       }
       self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    //跳转工单详情
    func toOrderDetailVc(_ orderid:String){
        R_OrderDetailMain.router(orderid) { reload in
            if reload{
//                self.requstIndexData()
            }
        }
    }
    
    func doActionWithActionStr(_ actionStr:String,model:HomeModel.HomeOrder){
        switch actionStr {
        case "导航定位":
            let mapM  = MapModel()
            mapM.lat = model.lat
            mapM.lng = model.lnt
            mapM.userAddress = model.userAddress
            
            MapsTool.shareInstance().mapAction(mapM)
            break
        case "拨打电话":
            self.callUserPhone(model.userMobile, orderId: model.orderId)
//            self.callPhone(model.userMobile,orderid: model.orderId)
            break
        case "派工".languageString():
            let assinType = MyInfo.shareInstance().userRole == .Site ? 2 : 1
            R_OrderAssignUser.router(model.orderId, type: assinType) { [weak self] reload in
                guard let weakSelf = self else { return }
                if reload {
//                    weakSelf.requstIndexData()
                }
            }

            break
        case "确认接单".languageString():
            self.showAcceptAlert(model.orderId)
            break
        default:
            break
        }
    }
    
    func showAcceptAlert(_ orderid:String){
        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
            if MyInfo.shareInstance().userRole == .Engineer {
                self.requestEngineerAccept(orderid)
            }else{
                self.requestAccept(orderid)
            }
           
        }))
        self.present(alertController, animated: true, completion: nil)
    }
    
}

extension HomePagingVc: JXPagingViewDelegate,JXSegmentedViewDelegate{

    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return JXTableHeaderViewHeight
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userHeaderContainerView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return JXheightForHeaderInSection
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return titles.count
    }

    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        switch index {
        case 0:
            orderBaseListView1.searchType = 1
            orderBaseListView1.beginFirstRefresh()
            orderBaseListView1.didSeletedCallback = { (orderId) in
                self.toOrderDetailVc(orderId)
            }
            orderBaseListView1.didClickButtonCallback = { (actionStr,model) in
                self.doActionWithActionStr(actionStr, model: model)
            }
            return orderBaseListView1
        case 1:
            if MyInfo.shareInstance().userRole != .Engineer {
                orderBaseListView2.searchType = 3
            }else{
                orderBaseListView2.searchType = 20 //师傅端第二个不是派工
            }
            orderBaseListView2.beginFirstRefresh()
            orderBaseListView2.didSeletedCallback = { (orderId) in
                self.toOrderDetailVc(orderId)
            }
            orderBaseListView2.didClickButtonCallback = { (actionStr,model) in
                self.doActionWithActionStr(actionStr, model: model)
            }
            
            return orderBaseListView2
        case 2:
            if MyInfo.shareInstance().userRole != .Engineer {
                orderBaseListView3.searchType = 20
            }else{
                orderBaseListView3.searchType = 21
            }
            orderBaseListView3.beginFirstRefresh()
            orderBaseListView3.didSeletedCallback = { (orderId) in
                self.toOrderDetailVc(orderId)
            }
            orderBaseListView3.didClickButtonCallback = { (actionStr,model) in
                self.doActionWithActionStr(actionStr, model: model)
            }
            
            return orderBaseListView3
        case 3:
            orderBaseListView4.searchType = 21
            orderBaseListView4.beginFirstRefresh()
            orderBaseListView4.didSeletedCallback = { (orderId) in
                self.toOrderDetailVc(orderId)
            }
            orderBaseListView4.didClickButtonCallback = { (actionStr,model) in
                self.doActionWithActionStr(actionStr, model: model)
            }
            
            return orderBaseListView4
            
        default:
            orderBaseListView1.beginFirstRefresh()
            orderBaseListView1.didSeletedCallback = { (orderId) in
                self.toOrderDetailVc(orderId)
            }
            orderBaseListView1.didClickButtonCallback = { (actionStr,model) in
                self.doActionWithActionStr(actionStr, model: model)
            }
            return orderBaseListView1
        }
        
    }
    
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if currentIndex == index {
            return //无完全切换不刷新，减少接口调用
        }
        currentIndex = index
        
        switch index {
        case 0:
            orderBaseListView1.searchType = 1
            orderBaseListView1.beginFirstRefresh()
            currentOrderBaseListView = orderBaseListView1
        case 1:
            orderBaseListView2.searchType = MyInfo.shareInstance().userRole != .Engineer ? 3 : 20
            orderBaseListView2.beginFirstRefresh()
            currentOrderBaseListView = orderBaseListView2
        case 2:
            orderBaseListView3.searchType = MyInfo.shareInstance().userRole != .Engineer ? 20 : 21
            orderBaseListView3.beginFirstRefresh()
            currentOrderBaseListView = orderBaseListView3
        case 3:
            orderBaseListView4.searchType = 21
            orderBaseListView4.beginFirstRefresh()
            currentOrderBaseListView = orderBaseListView4
            
        default:
            orderBaseListView1.beginFirstRefresh()
        }
    }

    func mainTableViewDidScroll(_ scrollView: UIScrollView) {
       
    }
    
}

//网络请求
extension HomePagingVc{
    //mark refresh
    @objc func headerRefresh(){
        pagingView.mainTableView.mj_header.endRefreshing()
        requstIndexData()
    }
    
    func requstIndexData(){
        var param = [String:Any]()
        param["pageNumber"] = "1"
        param["pageSize"] = "1000"
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/index/flush",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 = HomeModel(json: data,isFirstLoad: true)
                weakSelf.model = model
                weakSelf.userHeaderView.row_update(dataSource: model)
                weakSelf.configSegmentedTitleView()
                weakSelf.segmentedView.reloadData()
                
                if weakSelf.isFirstRefreshed {
                    weakSelf.isFirstRefreshed = false
                    weakSelf.currentOrderBaseListView = weakSelf.orderBaseListView1
                }
                
                //刷新当前列表
                weakSelf.currentOrderBaseListView.beginFirstRefresh()
                
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requestAccept(_ orderid:String){
        var paramDict = [String:Any]()
        paramDict["orderId"] = orderid

        let cNet = TWOCNetwork(url: "/app/v2/orderDo/accept" ,andParam: paramDict)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_info("操作成功~".languageString())
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//                weakSelf.requstIndexData()
                weakSelf.toOrderDetailVc(orderid)
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requestEngineerAccept(_ orderid:String) {
        var paramDict:[String:Any] = [:]
        paramDict["orderId"] = orderid
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/engineerAccept",andParam: paramDict)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            hud_info("操作成功".languageString())
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//                weakSelf.requstIndexData()
                weakSelf.toOrderDetailVc(orderid)
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}



