//
//  CreatOrderItemVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/29.
//

import UIKit
import JXSegmentedView

class CreatOrderItemVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var vm = CreatOrderItemVm()
    var state = 0
    var itemIndex = 0
    var updateCallback:((M_CreatOrder)->())?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .groupTableViewBackground
        configTableView()
        congigDefaultData()
    }
    
    func congigDefaultData(){
        let item = M_CreatOrder.M_Item()
        self.vm.model.items.append(item)
        self.vm.makeForms()
    }
    
    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) in
            self.requstIdentifyBarcode(code, index: index)
        }
        
        vm.selectImageCallback = {(index,actionIndex) in
            self.itemIndex = actionIndex
            self.showImageAlert(idx: actionIndex)
        }
        
        vm.makeForms()
    }
}


//网络请求
extension CreatOrderItemVc{
    
    func requstIdentifyBarcode(_ code:String,index:Int){
        var param = [String:Any]()
        param["barcode"] = code
        let cNet = TWOCNetwork(url: "/app/v2/multiplex/identifyBarcode",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                if let itemList = data["itemList"] as? [[String:Any]] {
                    if itemList.count > 0{
                        let item = itemList[0]
                        
                        weakSelf.vm.model.items[index].bigitemcatid = item.stringValue(forKey: "bigCategoryId")
                        weakSelf.vm.model.items[index].bigitemcatname = item.stringValue(forKey: "bigCategoryName")
                        
                        weakSelf.vm.model.items[index].smallitemcatid = item.stringValue(forKey: "smallCategoryId")
                        weakSelf.vm.model.items[index].smallitemcatname = item.stringValue(forKey: "smallCategoryName")
                        
                        weakSelf.vm.model.items[index].itemid = item.stringValue(forKey: "id")
                        weakSelf.vm.model.items[index].itemname = item.stringValue(forKey: "itemName")
                        weakSelf.vm.model.items[index].itemcode = item.stringValue(forKey: "itemCode")
                        weakSelf.vm.model.items[index].entId = item.stringValue(forKey: "entId")
                        
                        weakSelf.vm.model.items[index].brandId = item.stringValue(forKey: "brandId")
                      
                        weakSelf.vm.model.brandid = item.stringValue(forKey: "brandId")
                        weakSelf.vm.model.brandname = item.stringValue(forKey: "brandName")
                        
//                        let dict = item as NSDictionary
//
//                        weakSelf.vm.model.items[index].hasInCode = false
//                        weakSelf.vm.model.items[index].hasOutCode = false
//                        weakSelf.vm.model.items[index].hasBarCode3 = false
//                        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 index == 0{
                            weakSelf.vm.model.brandid = item.stringValue(forKey: "brandId")
                            weakSelf.vm.model.brandname = item.stringValue(forKey: "brandName")
                        }
                        
                        weakSelf.vm.makeForms()
                    }
                    else{
                        hud_error("识别暂无产品型号~".languageString())
                    }
                }
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func requstUploadImage(_ image:UIImage, idx:Int){
        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.resultPicList[idx].pic = iconUrl
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.upLoad(image)
    }
}

extension CreatOrderItemVc: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func showImageAlert(idx:Int) {
        guard self.vm.model.items.count > 0 else {
            return
        }
        let picUrl = self.vm.model.resultPicList[idx].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()
            })
            
            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.resultPicList[idx].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 += "工单号："
//                    waterStr += orderNoStr
//                    waterStr += "\n"
//
//                    waterStr += "时间："
//                    waterStr += Date().string("yyyy-MM-dd HH:mm:ss")
//                    waterStr += "\n"
//
//                    waterStr += "地址："
//                    waterStr += MapsTool.shareInstance().ontimelocation
                    
                    let waterImage = resultImage.waterMarkedImage(waterMarkText: waterStr)
                  //上传图片
                    self.requstUploadImage(waterImage, idx: itemIndex)
                }
            }
        }
        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 CreatOrderItemVc: 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 CreatOrderItemVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
