//
//  MineCertificatePicVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/10/12.
//

import UIKit
import JXSegmentedView

class MineCertificatePicVc: UIViewController {
   
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var btn_save: UIButton!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var height_bottomView: NSLayoutConstraint!
    
    var requestUrl = "/app/v2/personal/updateEngineerPic"
    var vm = MineCertificatePicVm()
    var settleId = ""
    var picTag = 1
    var updateCallback:((M_MineInfo)->())?
 
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavigationBackButton()
        self.view.backgroundColor = UIColor(hexString: "f8f8f8")
        self.cd.navigationBar(hidden: false)
        
        if MyInfo.shareInstance().userRole != .Engineer {
            btn_save.isHidden = true
            bottomView.isHidden = true
            height_bottomView.constant = 0
        }
       
        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()
            self.updateCallback?(self.vm.model)
        }
        
        vm.imageCallback = { (theTag) in
            self.picTag = theTag
            self.showImageAlert()
        }
        
        vm.makeForms()
    }

    @IBAction func submitAction(_ sender: UIButton) {
       
        self.requstData()
    }
    
    
}


//网络请求
extension MineCertificatePicVc{
    
    func requstData(){
        var param = [String:Any]()
        
        param["engineerPidPic1"] = vm.model.pic1
        param["engineerPidPic2"] = vm.model.pic2
        param["engineerPic"] = vm.model.pic3
        param["engineerCertificateNoPic"] = vm.model.pic4
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: requestUrl,andParam: param)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            DispatchQueue.main.async(execute: {
                hud_info("保存成功~")
            })
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            SVProgressHUD.dismiss()
            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:
                    self?.vm.model.pic1 = iconUrl
                    break
                case 2:
                    self?.vm.model.pic2 = iconUrl
                    break
                case 3:
                    self?.vm.model.pic3 = iconUrl
                    break
                case 4:
                    self?.vm.model.pic4 = iconUrl
                    break
                default:
                    break
                }
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.upLoad(image)
    }
    
}



extension MineCertificatePicVc: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func showImageAlert() {
        var picUrl = ""
       
        switch self.picTag {
        case 1:
            picUrl = self.vm.model.pic1
            break
        case 2:
            picUrl = self.vm.model.pic2
            break
        case 3:
            picUrl = self.vm.model.pic3
            break
        case 4:
            picUrl = self.vm.model.pic4
            break
        default:
            break
        }
        
        //其他角色不可编辑
        guard MyInfo.shareInstance().userRole == .Engineer else {
            self.showBigImage(picUrl)
            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)
            })
        }
        
            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()
            })

    
        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) {
    
                  //上传图片
                    self.requstUploadImage(resultImage)
                }
            }
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    func showBigImage(_ url:String){
        guard url != "" else {
            return
        }
        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 MineCertificatePicVc: 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 MineCertificatePicVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}

