//
//  PartsReturnDetailVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/27.
//

import UIKit

public struct R_PartsReturnDetail{
    static func router(_ returnId: String, callback: (([Int])->Void)?) {
        let vc = PartsReturnDetailVc.cd_storyboard("PartsManagement", from: "PartsReturnDetailVc") as! PartsReturnDetailVc
        vc.vm.returnId = returnId
        vc.callBack = callback
        CD.push(vc)
    }
}

class PartsReturnDetailVc: UIViewController {
    @IBOutlet weak var view_blue: UIView!
    
    @IBOutlet weak var stack_bg: UIStackView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var view_btns: UIView!
    
    @IBOutlet weak var btn_0: UIButton!
    @IBOutlet weak var btn_1: UIButton!
    
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var vm = PartsReturnDetailVm()
    
    var callBack:(([Int])->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        vm.requestDatas()
        vm.makeForms()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        view_blue.backgroundColor = .clear
        view_blue.cd.gradient(layerAxial: [(Config.color.hex("#478BFF").cd_alpha(1), Float(0)), (Config.color.hex("#478BFF").cd_alpha(0), Float(1))], point: (CGPoint(x: 0.50, y: 0.65), CGPoint(x: 0.50, y: 0.89)))
    }

    func makeUI() {
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
        topBar.delegate = self
        
        self.view.bringSubviewToFront(stack_bg)
        stack_bg.snp.makeConstraints { make in
            make.top.equalTo(topBar.bar_navigation.snp_bottom)
        }
        
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.setButtons()
            weakSelf.tableView.reloadData()
        }

        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.backgroundColor = .clear
    }
    
    func setButtons() {
        let btns = vm.model.operateButtonList
        view_btns.cd.isHidden(btns.isEmpty)
        btn_0.cd.isHidden(btns.isEmpty)
        btn_1.cd.isHidden(btns.count < 2)
        guard !btns.isEmpty else {
            return
        }
        btn_0.cd.text(btns[0].buttonName)
        if btns.count == 2 {
            btn_1.cd.text(btns[1].buttonName)
        }
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        let code = vm.model.operateButtonList.filter({$0.buttonName == sender.titleLabel!.text}).first?.buttonCode
        switch code {
        case "returnReject": //-驳回
            R_PartsReturnReject.router(vm.returnId) { [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callBack?([0,1])
                    weakSelf.vm.requestDatas()
                }
            }
            break
        case "returnCheck": //-审核
            returnCheck()
            break
        case "returnIn": //-入库
            R_PartsReturnIn.router(vm.returnId, partsList: vm.model.partsList) { [weak self] bool in
                guard let weakSelf = self else { return }
                if bool {
                    weakSelf.callBack?([0,2])
                    weakSelf.vm.requestDatas()
                }
            }
            break
        default:
            returnCheck()
            break
        }
    }
}

extension PartsReturnDetailVc {
    func returnCheck() {
        let alertVC = UIAlertController.init(title: nil, message: "是否确认审核?".languageString(), preferredStyle: .alert)
        let canncelAC = UIAlertAction.init(title: "取消".languageString(), style: .cancel, handler: nil)
        let sureAC = UIAlertAction.init(title: "确定".languageString(), style: .default) {(UIAlertAction) in
           request()
        }
        alertVC.addAction(canncelAC)
        alertVC.addAction(sureAC)
        CD.visibleVC?.present(alertVC, animated: true, completion: nil)
        
        func request() {
            var par:[String:Any] = [:]
            par["returnId"] = vm.returnId
            hud_loading()
            let cNet = TWOCNetwork(url: "/app/v2/partsDo/returnCheck",andParam: par)
            cNet.successCall = {[weak self](result) in
                guard let weakSelf = self else { return }
                hud_hidden()
                hud_succeed("操作成功~".languageString())
                weakSelf.callBack?([0,1,2])
                weakSelf.vm.requestDatas()
//                CD.pop()
            }
            cNet.failCall = {[weak self](errorTag,errorStr) in
                guard let weakSelf = self else { return }
                hud_hidden()
                hud_error(errorStr)
                weakSelf.vm.makeForms()
            }
            cNet.postRequest()
        }
    }
}

extension PartsReturnDetailVc: 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?()
    }
}

extension PartsReturnDetailVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        topBar._style = "10"

        topBar.cd.background(.clear)
        topBar._title = "配件退回详情".languageString()
        topBar.bar_navigation.item_centre._colorTitle = .white
        topBar.bar_navigation.item_centre.btn_1.titleLabel?.font = Config.font.fontMedium(18)
        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 = .white
            let icon = CD_IconFont.tback_light(22)
            return [.title([(icon.text, icon.font, color, .normal), (icon.text, icon.font, color, .highlighted), (icon.text, icon.font, color, .selected)])]
        default:
            return nil
        }
    }

    func didSelect(withTopBar item: CD_TopNavigationBar.Item) {
        super_topBarClick(item)
        switch item {
        case .leftItem1:
            break
        default:
            break
        }
    }
}

