//
//  OrderDetailInfoVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/8/28.
//

import Foundation
import TWOCNetwork
import Utility

class OrderDetailInfoVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var viewType = 0   //0、工单信息；1、服务工程
    
    var model = M_OrderDetailInfo()
    
    var callBack:((String)->Void)?
    
    var isOpenLocation = false
    
    lazy var locationManager: AMapLocationManager = {
        let curL = AMapLocationManager()
        curL.delegate = self
        curL.desiredAccuracy = kCLLocationAccuracyHundredMeters
        curL.pausesLocationUpdatesAutomatically = false
        curL.allowsBackgroundLocationUpdates = true
        curL.locationTimeout = 10
        curL.reGeocodeTimeout = 10
        return curL
    }()
    
    var curLocation:CLLocationCoordinate2D?
}

extension OrderDetailInfoVm {
    func makeForms() {
        switch viewType {
        case 0:
            makeInfoForms()
        case 1:
            makeServiceProcessForms()
        default:
            break
        }
    }
    
    func makeInfoForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(type: .clear)
        do{
            let rowCell = TCFormCellModel<OrderDetailUserInfoCell>.init(data: model, frameh: UITableView.automaticDimension) { [weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    switch txt {
                    case "phone":
//                        if let callUrl = URL(string :"tel://"+"\(weakSelf.model.userMobile)") , UIApplication.shared.canOpenURL(callUrl) {
//                            if #available(iOS 10.0, *) {
//                                UIApplication.shared.open(callUrl)
//                            }else{
//                                UIApplication.shared.openURL(callUrl)
//                            }
//                        }else{
//                            hud_error("联系电话错误！")
//                        }
                        CD.visibleVC?.callUserPhone(weakSelf.model.userMobile, orderId: weakSelf.model.orderId)
                    case "address":
                        weakSelf.mapAction(weakSelf.model)
                    default:
                        break
                    }
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeProductCellForm(hh:10)
        for (i,item) in model.itemList.enumerated() {
            if i > 0 {
                newForms += makeProductCellForm(hh:8)
            }
            newForms += makeProductCellForm(nameStr: "\(item.itemName) \(item.categoryName)", qtyStr: "x\(item.qty)")
        }
        newForms += makeProductCellForm(corner: (8, [.bottomLeft, .bottomRight]), hh: 16)
        
        newForms += makeLineCellForm(type: .clear)
        newForms += makeTitleCellForm(titleStr: "\(model.orderNo)", statusStr: "  \(model.orderStatName)  ", corner: (8, [.topLeft, .topRight]), isCopy: true)
        newForms += makeLineCellForm(type: .line, height: 1)
        newForms += makeLineCellForm(type: .white, height: 12)
        newForms += makeInfoCellForm(titleStr: "服务派工时间".languageString(), detailStr: model.takeTime)
        newForms += makeLineCellForm(type: .white, height: 8)
        newForms += makeInfoCellForm(titleStr: "用户期望时间".languageString(), detailStr: model.wishBookDate)
        newForms += makeLineCellForm(type: .white, height: 8)
        newForms += makeInfoCellForm(titleStr: "预约上门时间".languageString(), detailStr: model.bookDate)
        newForms += makeLineCellForm(type: .white, height: 8)
        newForms += makeInfoCellForm(titleStr: "工单服务诉求".languageString(), detailStr: model.appeals)
        newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 16)
        
        if !model.showDataList.isEmpty {
            newForms += makeLineCellForm(type: .clear)
            newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMinYCorner, .layerMaxXMinYCorner]), height: 16)
            for (i,item) in model.showDataList.enumerated() {
                if i > 0 {
                    newForms += makeLineCellForm(type: .white, height: 8)
                }
                newForms += makeInfoCellForm(titleStr: item.name, detailStr: item.value)
            }
            newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 16)
        }
        
        if !model.operateButtonList.isEmpty {
            newForms += makeLineCellForm(type: .clear)
            newForms += makeTitleCellForm(titleStr: "其他操作".languageString(), statusStr: "", corner: (8, [.topLeft, .topRight]))
            newForms += makeLineCellForm(type: .line, height: 1)
            do{
                let rowCell = TCFormCellModel<OrderDetailActionCell>.init(data: model.operateButtonList.compactMap({$0.buttonName}), frameh: UITableView.automaticDimension) { [weak self] txt in
                    guard let weakSelf = self else { return }
                    guard let str = txt as? String else { return }
                    weakSelf.clickButton(str)
                }
                newForms.append(rowCell)
            }
        }
        
        forms = newForms
        reloadData?()
    }
    
    func makeServiceProcessForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(type: .clear)
        newForms += makeTitleCellForm(titleStr: "\("服务工单编号".languageString())  \(model.orderNo)", statusStr: "", corner: (8, [.topLeft, .topRight]))
        newForms += makeLineCellForm(type: .line, height: 1)
        newForms += makeLineCellForm(type: .white, height: 16)
        for item in model.processList {
            newForms += makeServiceProcessCellForm(titleStr: item.processName, detailStr: item.content, stat: item.processStat, timeStr: item.processTime, didSelect: {
//                switch self.model.processType {
//                case 1:
//                    hud_info(item.content)
//                case 2:
//                    R_Web.push(.http(self.model.mainButtonSkipH5Page+"&token=\(MyInfo.shareInstance().token)"))
//                default:
//                    break
//                }
            })
        }
        newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 16)
        forms = newForms
        reloadData?()
    }
    
    enum LineCellType {
        case line
        case clear
        case white
    }
    func makeLineCellForm(type:LineCellType, corners:(CGFloat, CACornerMask)? = nil, hideLine:Bool? = nil, hideView:Bool? = nil, height:CGFloat? = nil) -> [TCCellBaseProtocol] {
        var corner:(CGFloat, CACornerMask) = (0,[])
        var isLineHidden = true
        var isViewHidden = false
        var hh:CGFloat = 12
        switch type {
        case .line:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? false
            isViewHidden = hideView ?? false
            hh = height ?? 13
        case .clear:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? true
            hh = height ?? 8
        case .white:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? false
            hh = height ?? 8
        }
        let rowCell = TCFormCellModel<WorkbenchTitleCell>.init(data: "", config: (corner, isLineHidden, isViewHidden), frameh: hh)
        return [rowCell]
    }
    
    func makeProductCellForm(nameStr:String = "", qtyStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailPruductCell>.init(data: (nameStr, qtyStr), config: corner, frameh: hh ?? UITableView.automaticDimension )
        return [rowCell]
    }
    
    func makeTitleCellForm(titleStr:String = "", statusStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), isCopy:Bool = false, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailTitleCell>.init(data: (titleStr, statusStr), config: (isCopy, corner), frameh: hh ?? UITableView.automaticDimension )
        return [rowCell]
    }
    
    func makeInfoCellForm(titleStr:String, detailStr:String, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailInfoCell>.init(data: (titleStr, detailStr), frameh: hh ?? UITableView.automaticDimension )
        return [rowCell]
    }
    
    func makeServiceProcessCellForm(titleStr:String, detailStr:String, stat:Int, timeStr:String = "", hh:CGFloat? = nil, didSelect:TCRowDidSelectBlock? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailServiceProcessCell>.init(data: (titleStr, detailStr, stat, timeStr), frameh: hh ?? UITableView.automaticDimension,didSelect: didSelect)
        return [rowCell]
    }
}

extension OrderDetailInfoVm {
    func pushToWebView() {
        
    }
    
    func clickButton(_ str:String) {
        var code = ""
        for item in model.operateButtonList {
            if item.buttonName == str {
                code = item.buttonCode
            }
        }
        callBack?(code)
    }
}
extension OrderDetailInfoVm: AMapLocationManagerDelegate {
    func amapLocationManager(_ manager: AMapLocationManager!, doRequireLocationAuth locationManager: CLLocationManager!) {
        locationManager.requestAlwaysAuthorization()
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
        
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didFailWithError error: Error!) {
        print("error==",error.localizedDescription)
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didChange status: CLAuthorizationStatus) {
        if [.authorizedWhenInUse, .notDetermined, .authorizedAlways].contains(status) {
            isOpenLocation = true
        }else if status == .denied {
            isOpenLocation = false
        }else{
            isOpenLocation = false
        }
        if !isOpenLocation {
            showLocationTips()
        }
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, locationManagerDidChangeAuthorization locationManager: CLLocationManager!) {
        if [.authorizedWhenInUse, .notDetermined, .authorizedAlways].contains(CLLocationManager.authorizationStatus()) {
            isOpenLocation = true
        }else if CLLocationManager.authorizationStatus() == .denied {
            isOpenLocation = false
        }else{
            isOpenLocation = false
        }
        if !isOpenLocation {
            showLocationTips()
        }
    }
    
    func showLocationTips() {
        let alertC = UIAlertController(title: "提示".languageString(), message: "您还未开启定位服务，请前往设置开启，以便于准确获取您的位置信息".languageString(), preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: .default))
        alertC.addAction(UIAlertAction(title: "确定".languageString(), style: .default) {(_) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
            }
        })
        CD.visibleVC?.present(alertC, animated: true, completion: nil)
    }
    
    // 获取定位
    func getLocal() {
        locationManager.requestLocation(withReGeocode: true) {[weak self] location, locationReGeocode, error in
            guard let weakSelf = self else {return}
            if let error = error {
                let error = error as NSError
                NSLog("逆地理错误:{\(error.code) - \(error.localizedDescription)};")
            }
            if let location = location?.coordinate {
                weakSelf.curLocation = location
                weakSelf.makeForms()
            }
        }
    }

    // 导航
    func mapAction(_ m:M_OrderDetailInfo) {
        if (m.lat.isEmpty || m.lnt.isEmpty) && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let alertC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertC.addAction(UIAlertAction(title: "高德地图", style: .default) { [weak self] (_) in
            guard let weakSelf = self else { return }
            weakSelf.toGDMap(m)
        })
        alertC.addAction(UIAlertAction(title: "百度地图", style: .default) { [weak self] (_) in
            guard let weakSelf = self else { return }
            weakSelf.toBaiduMap(m)
        })
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: .cancel, handler: nil))
        CD.visibleVC?.present(alertC, animated: true, completion: nil)
    }
    
    // 高德
    func toGDMap(_ m:M_OrderDetailInfo) {
        if (m.lat.isEmpty || m.lnt.isEmpty) && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let userAddress = m.userAddress
        let urlString = "iosamap://path?sourceApplication=&dname=\(userAddress)&dlat=\(m.lat)&dlon=\(m.lnt)&t=0"
        if self.openMap(urlString) == false {
            hud_info("您还没有安装高德地图")
        }
    }
    
    // 百度
    func toBaiduMap(_ m:M_OrderDetailInfo) {
        if (m.lat.isEmpty || m.lnt.isEmpty) && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let coordinate = CLLocationCoordinate2DMake(m.lat.doubleValue(), m.lnt.doubleValue())
        // 将高德的经纬度转为百度的经纬度
        let baiduCoordinate = getBaiDuCoordinateByGaoDeCoordinate(coordinate: coordinate)
        let destination = "\(baiduCoordinate.latitude),\(baiduCoordinate.longitude)"
        
        let userAddress = m.userAddress
        let urlString = "baidumap://map/direction?destination=\(userAddress)&mode=driving&destination=\(destination)|name:\(userAddress)"
        
        let str = urlString as String
        
        if self.openMap(str) == false {
            hud_info("您还没有安装百度地图")
        }
    }
    
    // 打开第三方地图
    private func openMap(_ urlString: String) -> Bool {
        let urlstr =   urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        guard let url = URL(string:urlstr) else {
            return false
        }
        if UIApplication.shared.canOpenURL(url) == true {
            self.openURL(urlString: urlString as String)
            return true
        } else {
            return false
        }
    }
    
    func openURL(urlString:String) {
        let urlstr =   urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        guard let url = URL(string:urlstr) else {
            return
        }
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url )
        }
    }
    
    func canOpenUrl(_ urlString: NSString) -> Bool {
        guard let urlStr = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let opUrl = URL(string: urlStr) else {
            return false
        }
        return UIApplication.shared.canOpenURL(opUrl)
    }
    
    // 高德经纬度转为百度地图经纬度
    func getBaiDuCoordinateByGaoDeCoordinate(coordinate:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        return CLLocationCoordinate2DMake(coordinate.latitude + 0.006, coordinate.longitude + 0.0065)
    }
}
