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

import UIKit
import JXSegmentedView

class FinishOrdeFeeVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var vm = FinishOrdeFeeVm()
    var state = 0
    var updateCallback:((M_FinishOrder)->())?
    
    var orderNoStr = ""
    var picTag = 1
    var isClickUserPic = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .groupTableViewBackground
        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.imageCallback = { (flag ,theTag) in
            self.isClickUserPic = flag
            self.picTag = theTag
            self.showImageAlert()
        }
        
        vm.getCodeCallback = { str in
            self.requestGetCode()
        }
        
        vm.addCallback = {[weak self] (flag) in
            guard let weakSelf = self else { return }
            R_FeesCategory.router(weakSelf.vm.model.orderId, feeType: flag, guaranteeType: weakSelf.vm.model.guaranteeType.stringValue, itemCategoryId: weakSelf.vm.model.itemCategoryId, serviceTypeId: weakSelf.vm.model.serviceTypeId, itemId: weakSelf.vm.model.itemid) {[weak self] selArr in
                guard let weakSelf = self else {return}
                let selItems = selArr.compactMap({M_FinishOrder.M_FeeItem(json: $0)})
                for item in selItems {

                    var newItem = item
                    //公司收费
                    if flag == 1 {
                        //判断是否已有明细
                        var isExst = false
                        var exstIndex = 0
                        for (index,item) in weakSelf.vm.model.specailFeeList.enumerated() {
                            if item.subjectId == newItem.subjectId {
                                isExst = true
                                exstIndex = index
                            }
                        }
                        if !isExst {
                            weakSelf.vm.model.specailFeeList.append(newItem)
                        }else{
                            //数量加1
                            var old = weakSelf.vm.model.specailFeeList[exstIndex]
                            let oldQty = old.qty.intValue
                            old.qty = String(oldQty+newItem.qty.intValue())

                            weakSelf.vm.model.specailFeeList[exstIndex] = old
                        }

                    }else{
                        //判断是否已有明细
                        var isExst = false
                        var exstIndex = 0
                        for (index,item) in weakSelf.vm.model.userPayList.enumerated() {
                            if item.subjectId == newItem.subjectId {
                                isExst = true
                                exstIndex = index
                            }
                        }
                        if !isExst {
                            if newItem.subjectName == "其他" {
                                newItem.isOther = 1
                            }
                            weakSelf.vm.model.userPayList.append(newItem)
                        }else{
                            //数量加1
                            var old = weakSelf.vm.model.userPayList[exstIndex]
                            let oldQty = old.qty.intValue
                            old.qty = String(oldQty+newItem.qty.intValue())

                            weakSelf.vm.model.userPayList[exstIndex] = old
                        }

                        weakSelf.vm.setUserAmount()
                    }
                }
                weakSelf.vm.makeForms()
            }
        }
        
//        vm.addCallback = { (flag) in
//            let vc = UIStoryboard(name: "FinishOrder", bundle: nil).instantiateViewController(withIdentifier: "FinishOrderSelectFeeVc") as! FinishOrderSelectFeeVc
//            vc.title = "费用类别"
//            vc.isShowHeader = true
//            vc.loadMore = true
//            vc.getDataUrl = "app/v2/orderFinishDo/searchFeeType"
//            vc.subJoinParam = ["orderId":self.vm.model.orderId,"itemId":self.vm.model.itemid,"itemCategoryId":self.vm.model.itemCategoryId,"feeType":flag,"serviceTypeId":self.vm.model.serviceTypeId,"guaranteeType":self.vm.model.guaranteeType]
//
//            vc.didSelCallback = { (selItems) in
//                for item in selItems {
//
//                    var newItem = item
//                    newItem.qty = "1"
//                    //公司收费
//                    if flag == 1 {
//                        //判断是否已有明细
//                        var isExst = false
//                        var exstIndex = 0
//                        for (index,item) in self.vm.model.specailFeeList.enumerated() {
//                            if item.subjectId == newItem.subjectId {
//                                isExst = true
//                                exstIndex = index
//                            }
//                        }
//                        if !isExst {
//                            self.vm.model.specailFeeList.append(newItem)
//                        }else{
//                            //数量加1
//                            var old = self.vm.model.specailFeeList[exstIndex]
//                            let oldQty = old.qty.intValue
//                            old.qty = String(oldQty+1)
//
//                            self.vm.model.specailFeeList[exstIndex] = old
//                        }
//
//                    }else{
//                        //判断是否已有明细
//                        var isExst = false
//                        var exstIndex = 0
//                        for (index,item) in self.vm.model.userPayList.enumerated() {
//                            if item.subjectId == newItem.subjectId {
//                                isExst = true
//                                exstIndex = index
//                            }
//                        }
//                        if !isExst {
//                            self.vm.model.userPayList.append(newItem)
//                        }else{
//                            //数量加1
//                            var old = self.vm.model.userPayList[exstIndex]
//                            let oldQty = old.qty.intValue
//                            old.qty = String(oldQty+1)
//
//                            self.vm.model.userPayList[exstIndex] = old
//                        }
//
//                        self.vm.setUserAmount()
//                    }
//                }
//                self.vm.makeForms()
//            }
//
//            CD.visibleVC?.navigationController?.pushViewController(vc, animated: true)
//        }
        
        vm.makeForms()
    }
}


//网络请求
extension FinishOrdeFeeVc{
    
    func requestGetCode(){
       self.view.endEditing(true)
       
        var paramDict = [String:Any]()
        paramDict["mobile"] = vm.model.userMobile
        paramDict["orderId"] = vm.model.orderId
        
        let payAmount = vm.model.userPayAmount.doubleValue() - vm.model.userPayDiscount.doubleValue()
        
        paramDict["userFee"] = payAmount
        
        MineGetCodeTool.defaultTool().starRequestVerificationCode(theParam: paramDict,timerCount: 300,path: "app/v2/orderFinishDo/getUserFeeVerification")
   }
    
    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")
                if weakSelf.isClickUserPic{
                    //用户收费凭证
                    switch weakSelf.picTag {
                    case 1:
                        weakSelf.vm.model.userPayPic1 = iconUrl
                        break
                    case 2:
                        weakSelf.vm.model.userPayPic2 = iconUrl
                        break
                    case 3:
                        weakSelf.vm.model.userPayPic3 = iconUrl
                        break
                    default:
                        break
                    }
                }
                else{
                    //公司收费凭证
                    switch weakSelf.picTag {
                    case 1:
                        weakSelf.vm.model.specailAmountPic1 = iconUrl
                        break
                    case 2:
                        weakSelf.vm.model.specailAmountPic2 = iconUrl
                        break
                    case 3:
                        weakSelf.vm.model.specailAmountPic3 = iconUrl
                        break
                    default:
                        break
                    }
                }
                weakSelf.vm.makeForms()
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.upLoad(image)
    }
    
}


extension FinishOrdeFeeVc: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func showImageAlert() {
        var picUrl = ""
        if isClickUserPic {
            switch self.picTag {
            case 1:
                picUrl = self.vm.model.userPayPic1
                break
            case 2:
                picUrl = self.vm.model.userPayPic2
                break
            case 3:
                picUrl = self.vm.model.userPayPic3
                break
            default:
                break
            }
        }
        else{
            switch self.picTag {
            case 1:
                picUrl = self.vm.model.specailAmountPic1
                break
            case 2:
                picUrl = self.vm.model.specailAmountPic2
                break
            case 3:
                picUrl = self.vm.model.specailAmountPic3
                break
            default:
                break
            }
            
        }
    
        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: "删除", 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(){
        if self.isClickUserPic{
            //用户收费凭证
            switch self.picTag {
            case 1:
                self.vm.model.userPayPic1 = ""
                break
            case 2:
                self.vm.model.userPayPic2 = ""
                break
            case 3:
                self.vm.model.userPayPic3 = ""
                break
            default:
                break
            }
        }
        else{
            //公司收费凭证
            switch self.picTag {
            case 1:
                self.vm.model.specailAmountPic1 = ""
                break
            case 2:
                self.vm.model.specailAmountPic2 = ""
                break
            case 3:
                self.vm.model.specailAmountPic3 = ""
                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){
        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 FinishOrdeFeeVc: 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 FinishOrdeFeeVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}


