//
//  SettlementOrderSureVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/9/27.
//  结算单确认

import UIKit


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

class SettlementOrderSureVc: UIViewController {
   
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var btn_submit: UIButton!
    var requestUrl = "app/v2/settle/checkSettle"
    var vm = SettlementOrderSureVm()
    var settleId = ""
    var callback: ((Bool)->Void)?
    var picTag = 1
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "结算确认".languageString()
        self.setNavigationBackButton()
        self.view.backgroundColor = UIColor(hexString: "f8f8f8")
        self.cd.navigationBar(hidden: false)
        btn_submit.setTitle("提交".languageString(), for: .normal)
        configTableView()
    }
    
    func configTableView() {
        view.addSubview(tableView)
        
        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()
        }
        
        vm.imageCallback = { (theTag) in
            self.picTag = theTag
            self.showImageAlert()
        }
        
        vm.makeForms()
    }

    @IBAction func submitAction(_ sender: UIButton) {
        guard vm.result != "" else {
            hud_error("请选择确认结果~".languageString())
            return
        }
        
        if vm.result == "2"{
            guard vm.remark != "" else {
                hud_error("请输入异议内容~".languageString())
                return
            }
        }
        
        
        self.requstData()
    }
    
    
}


//网络请求
extension SettlementOrderSureVc{
    
    func requstData(){
        var param = [String:Any]()
        param["settleId"] = settleId
        
        param["remark"] = vm.remark
        param["result"] = vm.result
        param["pic1"] = vm.pic1
        param["pic2"] = vm.pic2
        param["pic3"] = vm.pic3
        
        let cNet = TWOCNetwork(url: requestUrl,andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async(execute: {
                hud_info("操作成功~".languageString())
                self?.navigationController?.popViewController(animated: true)
                self?.callback?(true)
            })
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    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")
               
                switch weakSelf.picTag {
                case 1:
                    weakSelf.vm.pic1 = iconUrl
                    break
                case 2:
                    weakSelf.vm.pic2 = iconUrl
                    break
                case 3:
                    weakSelf.vm.pic3 = iconUrl
                    break
                default:
                    break
                }
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.upLoad(image)
    }
    
}


extension SettlementOrderSureVc: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func showImageAlert() {
        var picUrl = ""
       
        switch self.picTag {
        case 1:
            picUrl = self.vm.pic1
            break
        case 2:
            picUrl = self.vm.pic2
            break
        case 3:
            picUrl = self.vm.pic3
            break
        default:
            break
        }
    
        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)
            })
        }
        
        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: "删除", style: UIAlertAction.Style.default) { [weak self] (_) in
//                    guard let weakSelf = self else { return }
//                    weakSelf.deletePic()
//                })
//            }
    
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: UIAlertAction.Style.cancel, handler: nil))
        self.present(alertC, animated: true, completion: nil)
    }
    
    func deletePic(){
        switch self.picTag {
        case 1:
            self.vm.pic1 = ""
            break
        case 2:
            self.vm.pic2 = ""
            break
        case 3:
            self.vm.pic3 = ""
            break
        default:
            break
        }
        self.vm.makeForms()
    }
    
    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) {
                  //上传图片
                    self.requstUploadImage(resultImage)
                }
            }
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func showBigImage(_ url:String){
        var picList = [String]()
        let picUrl = kGetServerPicUrl(url)
        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 SettlementOrderSureVc: 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?()
    }
}

