//
//  SettlementCheckOrderDetailVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/10/8.
//

import UIKit
import MJRefresh

public struct R_SettlementCheckOrderDetail {
    static func router(_ param:[String:Any],callback: ((Bool)->Void)?) {
        let vc = SettlementCheckOrderDetailVc.cd_storyboard("Settlement", from: "SettlementCheckOrderDetailVc") as! SettlementCheckOrderDetailVc
        vc.callback = callback
        vc.settleId = param.stringValue(forKey: "settleId")
        CD.push(vc)
    }
}

class SettlementCheckOrderDetailVc: UIViewController {
    @IBOutlet weak var btn_right1: UIButton!
    @IBOutlet weak var btn_right2: UIButton!
    @IBOutlet weak var btn_right3: UIButton!

    @IBOutlet weak var bottomView: UIView!
    
    lazy var tableView: UITableView = {
        let tab = UITableView()
        return tab
    }()
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var callback:((Bool)->())?
   
    var vm = SettlementCheckOrderDetailVm()
    
    var operateButtonList = [[String:Any]]()
    
    var settleId = ""
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
            .add(tableView)
        topBar.delegate = self
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBar.snp.bottom)
            make.left.right.bottom.equalToSuperview()
            make.bottom.equalToSuperview().offset(-100)
        }
        configTableView()
        
        requestData()
    }
    
    func configTableView() {
        self.tableView.backgroundColor = UIColor(hexString: "f8f8f8")
       
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        vm.callback = {
            self.tableView.reloadData()
        }
       
        vm.makeForms()
        
        let header = MJRefreshNormalHeader()
        header.stateLabel.textColor = UIColor(hexString: "999999")
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        tableView.mj_header = header
    }
    
    
    @IBAction func rightClickAction(_ sender: UIButton) {
        if let acName = sender.titleLabel?.text {
            let filterArr = self.operateButtonList.filter { item in
                item.stringValue(forKey: "buttonName") == acName
            }
            
            if filterArr.count > 0{
                let item = filterArr.first
                let actionFlag = item?.stringValue(forKey: "buttonCode")
                self.handleWithActionName(actionFlag ?? "")
            }
        }
    }
    
    func handleWithActionName(_ actionName:String){
        debugPrint(actionName)

        switch actionName {
        case "abandonCheckBill":
            //放弃申诉
            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.requstAbandonCheckBill()
            }))
            self.present(alertController, animated: true, completion: nil)
            
        //申诉
        case "complainCheckBill":
            R_SettlementCheckAppeal.router(["checkBillId":settleId]) { reload in
                if reload {
                    self.requestData()
                }
            }
            
        //申诉审核
        case "auditCheckBill":
            R_SettlementCheckSure.router(["checkBillId":settleId]) { reload in
                if reload {
                    self.requestData()
                }
            }
        default:
            break
        }
        
    }
    
}


//网络请求
extension SettlementCheckOrderDetailVc{
    
    //mark refresh
    @objc func headerRefresh(){
        self.tableView.mj_header.endRefreshing()
        
        requestData()
    }
    
    func requestData(){
        var param = [String:Any]()
        param["checkBillId"] = settleId
        let cNet = TWOCNetwork(url: "/app/v2/checkBill/getCheckBillDetail",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                self?.getActionsWithRespond(data)
                self?.vm.dataDict = data
                self?.vm.makeForms()
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    //放弃申诉
    func requstAbandonCheckBill(){
        var param = [String:Any]()
        param["checkBillId"] = settleId
        
        let cNet = TWOCNetwork(url: "/app/v2/checkBillDo/abandonCheckBill",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async(execute: {
                hud_info("操作成功~".languageString())
                self?.requestData()
            })
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func getActionsWithRespond(_ detailDict:[String:Any]){
        btn_right1.isHidden = true
        btn_right2.isHidden = true
        btn_right3.isHidden = true
    
        var actionNameArr = [String]()
        
       if let operateButtonList = detailDict["operateButtonList"] as? [[String:Any]] {
            for item in operateButtonList {
                actionNameArr.append(item.stringValue(forKey: "buttonName"))
            }
           
           self.operateButtonList = operateButtonList
        }
        
        if actionNameArr.count > 0 {
            let actionName = actionNameArr[0]
            btn_right1.setTitle(actionName, for: .normal)
            btn_right1.isHidden = false
        }
        
        if actionNameArr.count > 1 {
            let actionName = actionNameArr[1]
            btn_right2.setTitle(actionName, for: .normal)
            btn_right2.isHidden = false
        }
        
        if actionNameArr.count > 2 {
            let actionName = actionNameArr[2]
            btn_right3.setTitle(actionName, for: .normal)
            btn_right3.isHidden = false
        }

    }
    
}



extension SettlementCheckOrderDetailVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar._style = "10"
        topBar.cd.background(Config.color.hex("478BFF"))
        topBar._title = "考核单详情".languageString()
        topBar._colorTitle = Config.color.hex("f")
        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("f")
            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
        }
    }
}



// MARK: - Table view data source
extension SettlementCheckOrderDetailVc: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.forms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellVM = vm.forms[indexPath.row]
        let cellIdentifier = cellVM.cellId.isEmpty ? String(describing: cellVM.cellClass) : cellVM.cellId
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            let bundle = Bundle.main.path(forResource:cellIdentifier, ofType: "nib")
            if bundle == nil{
                tableView.register(cellVM.cellClass, forCellReuseIdentifier: cellIdentifier)
            }else{
                let cellNib = UINib(nibName:cellIdentifier, bundle: nil)
                tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier)
            }
            cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        }
        
        guard let endCell = cell else {
            fatalError("没有找到标识为：\(cellIdentifier)的Cell")
        }
        cellVM.bind(endCell)
        return endCell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.init(hexString: "f8f8f8")
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellVM = vm.forms[indexPath.row]
        return cellVM.frameH
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellVM = vm.forms[indexPath.row]
        cellVM.tapBlock?()
    }
}

