//
//  LogisticsListVC.swift
//  XWProject
//
//  Created by Sweet on 2020/12/14.
//  Copyright © 2020 yangwang. All rights reserved.
//

import UIKit

/// 小件物流订单列表
class LogisticsListVC: YYTableViewController {
				let cancelViewModel = TravelServiceViewModel()
				/// viewModel
				let viewModel = TaxiOrderViewModel()

				init(orderType: Int) {
								super.init(nibName: nil, bundle: nil)
								viewModel.type.accept(orderType)
				}

				required init?(coder: NSCoder) {
								fatalError("init(coder:) has not been implemented")
				}

				override func viewDidLoad() {
								super.viewDidLoad()

								// Do any additional setup after loading the view.

								viewModel.configure(tableView: tableView)
								tableView.mj_header?.beginRefreshing()

								NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).take(until: self.rx.deallocated).subscribe(onNext: { [weak self] _ in
												self?.tableView.mj_header?.beginRefreshing()
								}).disposed(by: disposeBag)
				}

				override func viewWillAppear(_ animated: Bool) {
								super.viewWillAppear(animated)

				}

				//MARK: - UI
				override func setupViews() {
								super.setupViews()
								tableView.separatorStyle = .none
								tableView.delegate = self
								tableView.dataSource = self
								tableView.register(cellName: "LogisticsListCell", identifier: "item")
				}

				//MARK: - Rx
				override func bindRx() {
								super.bindRx()
								NotificationCenter.default.rx.notification(Notification.Name(rawValue: YYOrderListRefresh), object: nil).subscribe(onNext: {[unowned self] (_) in
												self.tableView.mj_header?.beginRefreshing()
								}).disposed(by: disposeBag)
				}

				//MARK: - Layouts
				override func defineLayouts() {
								super.defineLayouts()
								tableView.snp.makeConstraints { (make) in
												if #available(iOS 11.0, *) {
																make.edges.equalTo(view.safeAreaLayoutGuide)
												} else {
																make.edges.equalToSuperview()
												}
								}
				}
				@objc func cancle(sender:UIButton){
								let model = viewModel.dataSource.value[sender.tag]

								show()
								APIManager.shared.provider.rx
												.request(.queryOrderInfo(orderId: model.orderId, orderType: 4))
												.map(YYModel<TravelServiceModel>.self)
												.validate()
												.subscribe(onSuccess: {[unowned self]  (m) in
																self.hide()
																guard let data = m.data else{return}
																let vc = storyBoard(name: "Home", identifier: "TravelServiceCancelVC") as! TravelServiceCancelVC
																vc.orderId = model.orderId
																vc.orderType = .cityLogistics
																vc.driverTimeOutTime = data.driverTimeOutTime
																vc.driverTimeOut = data.driverTimeOut
																vc.didPressPay.delegate(on: self) { (self,arge) in
																				self.cancelPay(model: model)
																}
																self.yy_push(vc: vc)

												}) {[unowned self]  (error) in
																self.hide()
												}
												.disposed(by: disposeBag)
				}
				/// 添加小件物流取消记录
				func cancelPay(model:TaxiOrderModel)  {
								// 添加取消记录
								var type:OrderType?
								if model.orderType == 4 {
												type = .cityLogistics
								}else if model.orderType == 5{
												type = .acrossLogistics
								}
								cancelViewModel.orderType.accept(type!)
								cancelViewModel.orderId.accept(model.orderId)
								cancelViewModel.addCancle()
								YYAlertKit.displayActivity()
								cancelViewModel.addCancleSubject
												.subscribe(onNext: { [unowned self](status) in
																YYAlertKit.dismiss()
																switch status{
																				case .loading:
																								break
																				case .success(_ ):
																								alert(text: localized("取消成功"))
																								self.tableView.mj_header?.beginRefreshing()
																								break
																				case .error(let error):
																								alert(text: error.localizedDescription)
																								break
																}
												}).disposed(by: disposeBag)
				}
				@objc func pay(sender:UIButton){
								let model = viewModel.dataSource.value[sender.tag]
								var type:OrderType?
								if model.orderType == 4 {
												type = .cityLogistics
								}else if model.orderType == 5{
												type = .acrossLogistics
								}
								//支付差价
								if model.state == 13 {
												let vc = TravelServicePayVC.init(orderId: model.orderId, money: model.differenceMoney.wy_toDouble(), orderType:type!,isLogisicUgentPay: true)
                                    
												let nav = YYNavigationController.init(rootViewController: vc)
                                    nav.modalPresentationStyle = .overFullScreen
                                    nav.modalTransitionStyle = .crossDissolve
												self.present(nav, animated: false, completion: nil)
												vc.refresh.delegate(on: self) { (self, _) in
																self.tableView.mj_header?.beginRefreshing()
												}
								}else if model.state == 8{
												
								}else {

												let vc = YYSpecialCarViewController.init(orderId: model.orderId,showPay: true)
												vc.viewModel.orderType.accept(OrderType(rawValue: model.orderType)!)
												self.yy_push(vc: vc)

//												APIManager.shared.provider.rx.request(.redenvelopeDeductionAmount(orderId: model.orderId, orderType: OrderType(rawValue: model.orderType)!)).mapThenValidate(RedenvelopeModel.self).subscribe(onSuccess: {[unowned self] data in
//																switch  data {
//																				case .success(let m):
//																								let vc = TravelServicePayVC.init(orderId: model.orderId, money: model.orderMoney.wy_toDouble(), orderType: type!,redenvelopeModel: m)
//																								vc.discountMoney =  0
//																								let nav = YYNavigationController.init(rootViewController: vc)
//																								self.present(nav, animated: false, completion: nil)
//																								vc.refresh.delegate(on: self) { (self, _) in
//																												self.tableView.mj_header?.beginRefreshing()
//																								}
//																				default:break
//																}
//
//												}).disposed(by: disposeBag)


//												let vc = TravelServicePayVC.init(orderId: model.orderId, money: model.orderMoney.wy_toDouble(), orderType:type!,isLogisicUgentPay: false)
//												let nav = YYNavigationController(rootViewController: vc)
//												vc.modalPresentationStyle = .custom
//												self.present(nav, animated: false, completion: nil)
//												vc.refresh.delegate(on: self) { (self, _) in
//																self.tableView.mj_header?.beginRefreshing()
//												}


								}
				}

				@objc func receipt(_ btn:UIButton){
								let index = btn.tag - 1000
								if let receipt = viewModel.dataSource.value[index].receipt{
												UIApplication.shared.open(URL(string: receipt)!)

								}
				}
}

// MARK: - UITableViewDelegate
extension LogisticsListVC:UITableViewDelegate{
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = viewModel.dataSource.value[indexPath.row]
        // 8=待评价，9=已完成
        if data.state == 8 || data.state == 9{
            // 新的界面 有轨迹
            let vc = TaxiOrderDetailsVC.init(orderId: data.orderId, orderType: OrderType(rawValue: viewModel.type.value) ?? .cityLogistics)
            self.yy_push(vc: vc)
        }else{
            // 订单流程界面
            if self.viewModel.type.value == 4{
                let vc = YYSpecialCarViewController.init(orderId: data.orderId,fromTripList: true)
                vc.viewModel.orderType.accept(.cityLogistics)
                self.yy_push(vc: vc)
            }else if self.viewModel.type.value == 3{
                if data.state == 7 {
                    //待支付
                    let vc = TravelOrderSuccessVC()
                    vc.id.accept(data.orderId)
                    vc.statusType = .MyOrder
                    self.yy_push(vc: vc)
                    return
                }
                if data.state == 10 {
                    // 取消
                    let vc = YYSpecialCarViewController.init(orderId: data.orderId,fromTripList: true)
                    vc.viewModel.orderType.accept(.cityLogistics)
                    self.yy_push(vc: vc)
                    return
                }
                let vc = YYSpecialCarViewController.init(orderId: data.orderId,fromTripList: true)
                vc.viewModel.orderType.accept(.cityLogistics)
                self.yy_push(vc: vc)
            }else{
                let vc = TravelServiceVC.init(orderId: data.orderId, orderType: OrderType(rawValue: viewModel.type.value) ?? .cityLogistics)
                self.yy_push(vc: vc)
            }
        }
    }
}

// MARK: - UITableViewDelegate
extension LogisticsListVC:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.dataSource.value.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "item", for: indexPath) as! LogisticsListCell
        cell.selectionStyle = .none
        if viewModel.type.value == 4 {
            cell.cancle_bt.tag = indexPath.row
            cell.cancle_bt.addTarget(self, action: #selector(cancle(sender:)), for: .touchUpInside)
            cell.pay_bt.tag = indexPath.row
            cell.pay_bt.addTarget(self, action: #selector(pay(sender:)), for: .touchUpInside)
            cell.setModel(model: viewModel.dataSource.value[indexPath.row])
        }else {
            cell.cancle_bt.tag = indexPath.row
            cell.cancle_bt.addTarget(self, action: #selector(cancle(sender:)), for: .touchUpInside)
            cell.setCharterModel(model: viewModel.dataSource.value[indexPath.row])
        }
        cell.receipt_bt.addTarget(self, action: #selector(receipt), for: .touchUpInside)
        cell.receipt_bt.tag = 1000+indexPath.row
        return cell
    }
    
    
}
