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

import UIKit
import JXSegmentedView

class FinishOrdeInfoVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var vm = FinishOrdeInfoVm()
    var state = 0
    var updateCallback:((M_FinishOrder)->())?
    
    var currentIndex = 0
    var orderNoStr = ""
    var itemIndex = 0
    var orderId = ""
    
    var isNetworking = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .groupTableViewBackground
        self.vm.model.ontimelocation = MapsTool.shareInstance().ontimelocation
        configTableView()
    }
    
    func configTableView() {
        self.tableView.backgroundColor = UIColor(hexString: "f8f8f8")
        self.view.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()
            self.updateCallback?(self.vm.model)
        }
        
        vm.selectCodeCallback = {(code,index,buydate) in
            self.requstIdentifyBarcode(code, index: index, buydate: buydate)
        }
        
        vm.selectImageCallback = {(index,actionIndex) in
            self.itemIndex = actionIndex
            self.currentIndex = index
            self.showImageAlert()
        }
        
        vm.scanPartCodeCallback = {(code,index,partType) in
            self.requestPartData(code, index: index, partType: partType)
        }
        
        vm.makeForms()
    }
}


//网络请求
extension FinishOrdeInfoVc{
    
    func requstUploadImage(_ image:UIImage){
        let cNet = TWOCNetwork(url: "/admin/sys-file/upload",andParam: [:])
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                let iconUrl = data.stringValue(forKey: "url")
                weakSelf.vm.model.items[weakSelf.currentIndex].resultPicList[weakSelf.itemIndex].pic = iconUrl
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.upLoad(image)
    }
    
    func requstIdentifyBarcode(_ code:String,index:Int,buydate:String){
        if code == ""{
            hud_error("请输入或扫码条码".languageString())
            return
        }
        if isNetworking{return}
        isNetworking = true
        
        var param = [String:Any]()
        param["barcode"] = code
        param["orderId"] = orderId
        param["buyDate"] = buydate
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/orderFinishDo/barcode",andParam: param)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.isNetworking = false
            if let data = result["data"] as? [String:Any] {
                weakSelf.vm.model.items[index].itemid = data.stringValue(forKey: "itemId")
                weakSelf.vm.model.items[index].itemname = data.stringValue(forKey: "itemName")
                weakSelf.vm.model.items[index].itemcode = data.stringValue(forKey: "itemCode")
                weakSelf.vm.model.items[index].entId = data.stringValue(forKey: "entId")
                
                weakSelf.vm.model.items[index].bigitemcatid = data.stringValue(forKey: "bigCategoryId")
                weakSelf.vm.model.items[index].bigitemcatname = data.stringValue(forKey: "bigCategoryName")
                weakSelf.vm.model.items[index].smallitemcatid = data.stringValue(forKey: "smallCategoryId")
                weakSelf.vm.model.items[index].smallitemcatname = data.stringValue(forKey: "smallCategoryName")
                
                //是否有这些日期 ,参数
                let dict = data as NSDictionary
                for key in dict.allKeys{
                    if key as! String == "inCode" {
                        //有一码
                        weakSelf.vm.model.items[index].hasInCode = true
                    }
                    if key as! String == "outCode" {
                        //有二码
                        weakSelf.vm.model.items[index].hasOutCode = true
                    }
                    
                    if key as! String == "barCode3" {
                        weakSelf.vm.model.items[index].hasBarCode3 = true
                    }
                    
                    if key as! String == "itemEndDate" {
                        weakSelf.vm.model.items[index].hasItemEndDate = true
                    }
                    
                    if key as! String == "partsEndDate" {
                        weakSelf.vm.model.items[index].hasPartsEndDate = true
                    }
                    
                    if key as! String == "installDate" {
                        weakSelf.vm.model.items[index].hasInstallDate = true
                    }
                    
                    if key as! String == "guaranteeType" {
                        weakSelf.vm.model.items[index].hasGuaranteeType = true
                    }
                    
                    if key as! String == "buyDate" {
                        weakSelf.vm.model.items[index].hasBuyDate = true
                    }
                    
                    if key as! String == "iemi" {
                        weakSelf.vm.model.items[index].hasIemi = true
                    }
                }
                
                weakSelf.vm.model.items[index].partsEndDate = data.stringValue(forKey: "partsEndDate")
                weakSelf.vm.model.items[index].itemEndDate = data.stringValue(forKey: "itemEndDate")
                weakSelf.vm.model.items[index].installDate = data.stringValue(forKey: "installDate")
                weakSelf.vm.model.items[index].guaranteeType = data.stringValue(forKey: "guaranteeType")
                
                let buyDate = data.stringValue(forKey: "buyDate")
                if buyDate != "" {
                    weakSelf.vm.model.items[index].buyDate = buyDate
                }
                
                if index == 0 {
                    let itemCategoryId = weakSelf.vm.model.itemCategoryId
                    let itemId = weakSelf.vm.model.itemid
                    
                    let guaranteeType = data.stringValue(forKey: "guaranteeType")
                    if guaranteeType != ""{
                        weakSelf.vm.model.guaranteeType = guaranteeType.intValue()
                    }
                    
                    let new_itemId = data.stringValue(forKey: "itemId")
                    var new_itemCategoryId = ""
                    
                    if data.stringValue(forKey: "bigCategoryId") != "" && data.stringValue(forKey: "bigCategoryId") != "0"{
                        new_itemCategoryId = data.stringValue(forKey: "bigCategoryId")
                    }
                    if data.stringValue(forKey: "smallCategoryId") != "" && data.stringValue(forKey: "smallCategoryId") != "0"{
                        new_itemCategoryId = data.stringValue(forKey: "smallCategoryId")
                    }
                    
                    if new_itemId != ""{
                        weakSelf.vm.model.itemid = new_itemId
                    }
                    
                    if new_itemCategoryId != ""{
                        weakSelf.vm.model.itemCategoryId = new_itemCategoryId
                    }
                    
                    if itemId != new_itemId {
                        //清空配件
                        weakSelf.vm.model.partsList.removeAll()
                    }
                    
                    if itemCategoryId != new_itemCategoryId {
                        //清空故障
                        weakSelf.vm.model.faultList.removeAll()
                        
                        //初始化 默认一个故障
                        if weakSelf.vm.model.companymanyfault == 1{
                            weakSelf.vm.model.faultList.append(M_FinishOrder.M_Fault(json: [:]))
                        }
                    }
                }
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.isNetworking = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                hud_error(errorStr)
            }
        }
        cNet.postRequest()
    }
    
    //查配件
    func requestPartData(_ code:String,index:Int,partType:String){
        if code == ""{
            hud_error("扫码条码出错了~".languageString())
            return
        }
        var newItem = self.vm.model.partsList[index]
        if partType == "旧件扫码"{
            newItem.barcode2 = code
        }else{
            newItem.barcode = code
        }
        self.vm.model.partsList[index] = newItem
        self.vm.makeForms()
        
        /*
        //暂不请求后台
        var paramDict = [String:Any]()
        
        paramDict["partsCode"] = code
        paramDict["orderId"] = orderId
        paramDict["itemId"] = vm.model.itemid
        
        paramDict["pageNumber"] = 1
        paramDict["pageSize"] = 10
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/getPartsByCode",andParam: paramDict)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
        
            if let data = result["data"] as? [String:Any] {
                var newItem = weakSelf.vm.model.partsList[index]
                if partType == "旧件扫码"{
                        newItem.barcode2 = code
                        newItem.oldPartsId = data.stringValue(forKey: "partsId")
                        newItem.oldPartsCode = data.stringValue(forKey: "partsCode")
                        newItem.oldPartsName = data.stringValue(forKey: "partsName")
                        newItem.oldPic = data.stringValue(forKey: "partsPic")
                    }else{
                        newItem.barcode = code
                        newItem.partsId = data.stringValue(forKey: "partsId")
                        newItem.partsCode = data.stringValue(forKey: "partsCode")
                        newItem.partsName = data.stringValue(forKey: "partsName")
                        newItem.userPrice = data.stringValue(forKey: "userPrice")
                        
                        newItem.maxQty = data.stringValue(forKey: "maxQty")
                        newItem.invQty = data.stringValue(forKey: "invQty")
                        newItem.pic = data.stringValue(forKey: "partsPic")
                    }
                 
                    weakSelf.vm.model.partsList[index] = newItem
                    weakSelf.vm.makeForms()
                }else{
                    hud_error("未找到相关配件~")
                }
                    
        }
        cNet.failCall = {[weak self] (errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
         
         */
    }
         
}


extension FinishOrdeInfoVc: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func showImageAlert() {
        guard self.vm.model.items.count > 0 else {
            return
        }
        let picUrl = self.vm.model.items[currentIndex].resultPicList[itemIndex].pic
        if picUrl == "" && !self.vm.canEdit { return}
        
        let alertC = UIAlertController(title: "请选择".languageString(), message: "图片来源".languageString(), preferredStyle: UIAlertController.Style.actionSheet)

        if picUrl != "" {
            alertC.addAction(UIAlertAction(title: "查看大图".languageString(), style: UIAlertAction.Style.default) { [weak self] (_) in
                self?.showBigImage(picUrl)
            })
        }
        
        if vm.canEdit{
            alertC.addAction(UIAlertAction(title: "拍照".languageString(), style: UIAlertAction.Style.default) { [weak self] (_) in
                self?.takePhoto()
            })
            
            if vm.model.companyAppUploadPicType == "1"{
                alertC.addAction(UIAlertAction(title: "相册".languageString(), style: UIAlertAction.Style.default) { [weak self] (_) in
                    self?.localPhoto()
                })
            }
            
            if picUrl != "" {
                alertC.addAction(UIAlertAction(title: "删除".languageString(), style: UIAlertAction.Style.default) { [weak self] (_) in
                    guard let weakSelf = self else { return }
                    weakSelf.vm.model.items[weakSelf.currentIndex].resultPicList[weakSelf.itemIndex].pic = ""
                    weakSelf.vm.makeForms()
                })
            }
        }
    
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: UIAlertAction.Style.cancel, handler: nil))
       self.present(alertC, animated: true, completion: nil)
    }
    
    func takePhoto(){
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
            let pickerImage = UIImagePickerController()
            pickerImage.delegate = self
            pickerImage.allowsEditing = true
            pickerImage.sourceType = UIImagePickerController.SourceType.camera
            pickerImage.modalPresentationStyle = .overFullScreen
            self.present(pickerImage, animated: true, completion: nil)
        }else{
            self.promptInformation("摄像头不存在或已经损坏".languageString())
        }
    }
    
    func localPhoto(){
        let imagePicker = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
            imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
        }
        imagePicker.delegate = self
        imagePicker.modalPresentationStyle = .overFullScreen
        self.present(imagePicker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let theImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            let smallImage = theImage.imageWithMaxSize(1000)
            if let imageData = smallImage.jpegData(compressionQuality: 0.8) {
                if let resultImage = UIImage(data: imageData) {
                    // 加水印
                    var waterStr = ""
                    waterStr += "工单号".languageString()+"："
                    waterStr += orderNoStr
                    waterStr += "\n"
                    
                    waterStr += "时间".languageString()+"："
                    waterStr += Date().string("yyyy-MM-dd HH:mm:ss")
                    waterStr += "\n"
                    
                    waterStr += "地址".languageString()+"："
                    waterStr += MapsTool.shareInstance().ontimelocation
                    
                    let waterImage = resultImage.waterMarkedImage(waterMarkText: waterStr)
                  //上传图片
                    self.requstUploadImage(waterImage)
                }
            }
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func showBigImage(_ url:String){
        let picUrl = kGetServerPicUrl(url)
        var picList = [String]()
        picList.append(picUrl)
        let photos = picList.compactMap({ (item) -> GKPhoto in
            let photo = GKPhoto()
            guard let imageUrl = URL(string: item) else {
                return photo
            }
            photo.url = imageUrl
            return photo
        })
        
        let index = 0
        
        let browser = GKPhotoBrowser(photos: photos, currentIndex: index)
        browser.showStyle = .none
        browser.modalPresentationStyle = .overFullScreen
        browser.show(fromVC: self)
    }
}


// MARK: - Table view data source
extension FinishOrdeInfoVc: 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 FinishOrdeInfoVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}

