//
//  HistoryController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/18.
//

import Foundation
import DDAutoUIKit_Private
import DDControlsKit_Private
import RxSwift
import RxRelay
import RxCocoa
import JXCategoryView
import DDToastKit_Private
import MJRefresh

extension HistoryController {
    func addActions() {
        MCOUNT.messageCountRelay
            .subscribe(onNext: {[weak self] count in
                if count > 0 {
                    self?.messageView.countLabel.isHidden = false
                    self?.messageView.countLabel.text = String(count)
                    self?.messageView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(20)
                    })
                }else{
                    self?.messageView.countLabel.isHidden = true
                    self?.messageView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(0)
                    })
                }
            })
            .disposed(by: disposeBag)
        
        MCOUNT.pendingCountRelay
            .subscribe(onNext: {[weak self] count in
                if count > 0 {
                    self?.pendingView.countLabel.isHidden = false
                    self?.pendingView.countLabel.text = String(count)
                    self?.pendingView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(20)
                    })
                }else{
                    self?.pendingView.countLabel.isHidden = true
                    self?.pendingView.countLabel.snp.updateConstraints({ make in
                        make.width.equalTo(0)
                    })
                }
            })
            .disposed(by: disposeBag)
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_reloadRescusControolerToDoMessageCount), object: nil)
    }
}


extension HistoryItemController  {
    func addActions() {
        historyItemView.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.pageNum = 1
            self?.refreshRelay.accept(self?.pageNum ?? 1)
        })
        
        historyItemView.tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {[weak self] in
            self?.pageNum+=1
            self?.refreshRelay.accept(self?.pageNum ?? 1)
        })

        refreshRelay
            .flatMapLatest {[weak self] pageNum in
                return Observable.zip(RQ.orderList(parameters: OrderListParameters(pageNum: pageNum, queryType: (self?.type)!)).asObservable(), Observable.just(pageNum))
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] (response, pageNum) in
                if response?.success == true {
                    if pageNum == 1 {
                        if response?.data?.isEmpty == false {
                            self?.resultArr.removeAll()
                            self?.historyItemView.tableView.mj_footer?.resetNoMoreData()
                        }
                        self?.historyItemView.tableView.mj_header?.endRefreshing()
                    }else{
                        if response?.data?.isEmpty == false {
                            self?.historyItemView.tableView.mj_footer?.endRefreshing()
                        }else{
                            self?.historyItemView.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    }
                    
                    if let array = response?.data {
                        self?.resultArr.append(contentsOf: array)
                        self?.historyItemView.tableView.reloadData()
                    }
                }else{
                    if pageNum == 1 {
                        self?.historyItemView.tableView.mj_header?.endRefreshing()
                    }else{
                        self?.historyItemView.tableView.mj_footer?.endRefreshing()
                    }
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        historyItemView.tableView.mj_header?.beginRefreshing()
    }
}

extension HistoryItemController : UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return resultArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? HistoryItemCell
        if cell == nil {
            cell = HistoryItemCell(style: .default, reuseIdentifier: "cell")
            cell?.line.backgroundColor = .hex("E9E9EA").alpha(0.6)
            cell?.orderDateTitleLabel.text = "工单时间:"
            cell?.serviceTitleLabel.text = "故障地:"
            cell?.reportButton.setTitle("报备", for: .normal)
            cell?.additionalButton.setTitle("补结算单", for: .normal)
        }
        let model = resultArr[indexPath.row]
        
        cell?.typeLabel.text = model.taskServiceName
        cell?.orderNumLabel.text = model.orderCode
        cell?.orderStatusLabel.text = model.taskOrderStatusString
        cell?.orderDateLabel.text = model.createTime

        cell?.serviceLabel.text = model.vehiclePointAddress
        if model.destinationAddress?.isEmpty == false {
            cell?.destinationTitleLabel.text = "目的地:"
            cell?.destinationLabel.text = model.destinationAddress
            cell?.destinationTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.serviceLabel.snp.bottom).offset(auto(8))
            })
        }else{
            cell?.destinationTitleLabel.text = nil
            cell?.destinationLabel.text = nil
            cell?.destinationTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.serviceLabel.snp.bottom).offset(0)
            })
        }
        
        if model.isSupplierSettle?.label.isEmpty == false {
            cell?.settlementLabel.text = model.isSupplierSettle?.label
            cell?.settlementTitleLabel.text = "是否结算:"
            cell?.settlementTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.destinationLabel.snp.bottom).offset(auto(8))
            })
        }else{
            cell?.settlementLabel.text = nil
            cell?.settlementTitleLabel.text = nil
            cell?.settlementTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.destinationLabel.snp.bottom).offset(0)
            })
        }
        
        if model.supplierSettleRatio?.label.isEmpty == false {
            cell?.settlementRatioLabel.text = model.supplierSettleRatio?.label
            cell?.settlementRatioTitleLabel.text = "结算比例:"
            cell?.settlementRatioTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.settlementLabel.snp.bottom).offset(auto(8))
            })
        }else{
            cell?.settlementRatioLabel.text = nil
            cell?.settlementRatioTitleLabel.text = nil
            cell?.settlementRatioTitleLabel.snp.updateConstraints({ make in
                make.top.equalTo(cell!.settlementLabel.snp.bottom).offset(0)
            })
        }

        
        return cell!
    }
}

// MARK: JXCategoryViewDelegate,JXCategoryListContainerViewDelegate
extension HistoryController : JXCategoryViewDelegate,JXCategoryListContainerViewDelegate {
    public func number(ofListsInlistContainerView listContainerView: JXCategoryListContainerView!) -> Int {
        return categoryView.titles.count
    }
    
    public func listContainerView(_ listContainerView: JXCategoryListContainerView!, initListFor index: Int) -> JXCategoryListContentViewDelegate! {
        if index == 0 {
            return HistoryItemController(type: .UNCLOSED_ORDER)
        }
        if index == 1 {
            return HistoryItemController(type: .WITHIN_30_DAYS)
        }
        return HistoryItemController(type: .WITHIN_3_MONTHS)
    }
}

open class HistoryController : DDViewController {
    private let categoryView = JXCategoryTitleView()
    private lazy var categoryContainerView = JXCategoryListContainerView(type: .scrollView, delegate: self)
    private let reloadToDoMessageCountRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private let disposeBag = DisposeBag()
    private let messageTapGes = UITapGestureRecognizer()
    private let messageView = MessageView()
    private let pendingTapGes = UITapGestureRecognizer()
    private let pendingView = MessageView()
    
   public override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(auto(15))]
        dd_navigationItemTitle = "救援工单"
        navigationItem.leftBarButtonItems = nil
        addSubviews()
        addActions()
    }
    
    func addSubviews() {
        categoryView.titles = ["未关闭工单","30天内工单","3个月内工单"]
        categoryView.titleColor = .hex("737373").alpha(0.55)
        categoryView.titleSelectedColor = .hex("3678FF")
        categoryView.backgroundColor = .hex("F4F5F7")
        categoryView.delegate = self
        view.addSubview(categoryView)
        categoryView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(CGRectGetMaxY(navigationController?.navigationBar.frame ?? CGRectZero) + CGRectGetHeight(UIApplication.shared.dd_statusBarFrame))
            make.height.equalTo(auto(44))
        }
        // 指示器
        let indicator = JXCategoryIndicatorLineView()
        indicator.indicatorColor = .hex("3678FF")
        indicator.indicatorWidth = JXCategoryViewAutomaticDimension
        indicator.verticalMargin = 7
        categoryView.indicators = [indicator]
        
        // 内容
        view.addSubview(categoryContainerView!)
        categoryView.listContainer = categoryContainerView
        categoryContainerView?.snp.makeConstraints({ make in
            make.top.equalTo(categoryView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-(view.safeAreaInsets.bottom+CGRectGetHeight(tabBarController?.tabBar.frame ?? CGRectZero)))
        })
        
        messageView.titleLabel.text = "消息"
        messageView.addGestureRecognizer(messageTapGes)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: messageView)
        messageView.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(40)
        }

        pendingView.titleLabel.text = "待办"
        pendingView.addGestureRecognizer(pendingTapGes)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: pendingView)
        pendingView.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(40)
        }
    }
}

class HistoryItemController : DDViewController {
    private let disposeBag = DisposeBag()
    private let historyItemView = HistoryItemView()
    private var resultArr : [OrderListDataModel] = []
    private var environmentPics : [String] = []
    private var refreshRelay = ReplayRelay<Int>.create(bufferSize: 1)
    private var pageNum : Int = 1
    private var type : OrderTypeEnum
    public init(type:OrderTypeEnum) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        addSubviews()
        addActions()
    }
    
    func addSubviews() {
        view.addSubview(historyItemView)
        historyItemView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        historyItemView.tableView.delegate = self
        historyItemView.tableView.dataSource = self
    }
}

class HistoryItemCell : DDTableViewCell {
    public let radiusView : DDView
    public let typeLabel : DDLabel
    public let orderNumLabel : DDLabel
    public let orderStatusLabel : DDLabel
    public let line : DDView
    public let orderDateTitleLabel : DDLabel
    public let orderDateLabel : DDLabel
    public let serviceTitleLabel : DDLabel
    public let serviceLabel : DDLabel
    public let destinationTitleLabel : DDLabel
    public let destinationLabel : DDLabel
    public let settlementTitleLabel : DDLabel
    public let settlementLabel : DDLabel
    public let settlementRatioTitleLabel : DDLabel
    public let settlementRatioLabel : DDLabel
    public let additionalButton : DDButton
    public let reportButton : DDButton
    public var disposeBag : DisposeBag

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        radiusView = DDView.init()
        typeLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("000000").alpha(0.85))
        orderNumLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(11)), textColor: .hex("000000").alpha(0.55))
        orderStatusLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("E69B0B"))
        line = DDView.init()
        orderDateTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        orderDateLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("252525"))
        serviceTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        serviceLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000"))
        destinationTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        destinationLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000"))
        settlementTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        settlementLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000"))
        settlementRatioTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        settlementRatioLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000"))
        additionalButton = DDButton.dd_initCustom()
        additionalButton.titleLabel?.font = .mediumFont(13)
        additionalButton.setTitleColor(.hex("000000").alpha(0.7), for: .normal)
        reportButton = DDButton.dd_initCustom()
        reportButton.titleLabel?.font = .mediumFont(13)
        reportButton.setTitleColor(.hex("FFFFFF"), for: .normal)
        disposeBag = DisposeBag()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        contentView.backgroundColor = .hex("F4F5F7")
        radiusView.layer.cornerRadius = auto(6)
        radiusView.layer.shadowColor = UIColor.black(alpha: 0.1).cgColor
        radiusView.layer.shadowOpacity = 1.0
        radiusView.layer.shadowRadius = 3
        radiusView.layer.shadowOffset = CGSize(width: 0, height: 3)
        radiusView.backgroundColor = .white
        contentView.addSubview(radiusView)
        radiusView.addSubview(typeLabel)
        radiusView.addSubview(orderNumLabel)
        radiusView.addSubview(orderStatusLabel)
        radiusView.addSubview(line)
        radiusView.addSubview(orderDateTitleLabel)
        radiusView.addSubview(orderDateLabel)
        radiusView.addSubview(serviceTitleLabel)
        serviceLabel.numberOfLines = 0
        radiusView.addSubview(serviceLabel)
        radiusView.addSubview(destinationTitleLabel)
        destinationLabel.numberOfLines = 0
        radiusView.addSubview(destinationLabel)
        radiusView.addSubview(settlementTitleLabel)
        radiusView.addSubview(settlementLabel)
        radiusView.addSubview(settlementRatioTitleLabel)
        radiusView.addSubview(settlementRatioLabel)
        additionalButton.layer.borderColor = UIColor.hex("DDDDDD").cgColor
        additionalButton.layer.borderWidth = 1
        additionalButton.layer.cornerRadius = auto(4)
        radiusView.addSubview(additionalButton)
        reportButton.layer.cornerRadius = auto(4)
        reportButton.layer.masksToBounds = true
        reportButton.backgroundColor = .hex("2A5094")
        radiusView.addSubview(reportButton)
        
        radiusView.snp.makeConstraints { make in
            make.left.equalTo(auto(12))
            make.right.equalTo(-auto(12))
            make.top.equalTo(0)
            make.bottom.equalTo(-auto(12))
        }
        typeLabel.snp.makeConstraints { make in
            make.left.equalTo(auto(18))
            make.top.equalTo(auto(13))
        }
        
        orderNumLabel.snp.makeConstraints { make in
            make.centerY.equalTo(typeLabel)
            make.left.equalTo(typeLabel.snp.right).offset(auto(10))
        }
        
        orderStatusLabel.snp.makeConstraints { make in
            make.right.equalTo(-auto(20))
            make.centerY.equalTo(orderNumLabel)
        }
        
        line.snp.makeConstraints { make in
            make.top.equalTo(typeLabel.snp.bottom).offset(auto(7))
            make.left.right.equalTo(0)
            make.height.equalTo(0.5)
        }
        
        orderDateTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel)
            make.top.equalTo(line.snp.top).offset(auto(5))
            make.width.equalTo(auto(60))
        }
        
        orderDateLabel.snp.makeConstraints { make in
            make.left.equalTo(orderDateTitleLabel.snp.right).offset(auto(10))
            make.top.equalTo(orderDateTitleLabel)
        }

        serviceTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(orderDateLabel.snp.bottom).offset(auto(8))
            make.left.equalTo(typeLabel)
            make.width.equalTo(orderDateTitleLabel)
        }
        
        serviceLabel.snp.makeConstraints { make in
            make.top.equalTo(serviceTitleLabel)
            make.left.equalTo(serviceTitleLabel.snp.right)
            make.right.equalTo(-auto(20))
        }
        
        destinationTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(serviceLabel.snp.bottom).offset(auto(8))
            make.left.equalTo(typeLabel)
            make.width.equalTo(orderDateTitleLabel)
        }
        
        destinationLabel.snp.makeConstraints { make in
            make.top.equalTo(destinationTitleLabel)
            make.left.equalTo(destinationTitleLabel.snp.right)
            make.right.equalTo(-auto(20))
        }

        settlementTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel)
            make.top.equalTo(destinationLabel.snp.bottom)
            make.width.equalTo(orderDateTitleLabel)
        }
        
        settlementLabel.snp.makeConstraints { make in
            make.top.equalTo(settlementTitleLabel)
            make.right.equalTo(-auto(20))
            make.left.equalTo(settlementTitleLabel.snp.right)
        }
        
        settlementRatioTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel)
            make.top.equalTo(settlementLabel.snp.bottom).offset(auto(8))
            make.width.equalTo(orderDateTitleLabel)
        }
        
        settlementRatioLabel.snp.makeConstraints { make in
            make.top.equalTo(settlementRatioTitleLabel)
            make.right.equalTo(-auto(20))
            make.left.equalTo(settlementRatioTitleLabel.snp.right)

        }
        
        reportButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-auto(10))
            make.top.equalTo(settlementRatioLabel.snp.bottom).offset(auto(10))
            make.width.equalTo(auto(80))
            make.height.equalTo(auto(30))
            make.bottom.equalToSuperview().offset(-auto(10))
        }

        additionalButton.snp.makeConstraints { make in
            make.right.equalTo(reportButton.snp.left).offset(-auto(10))
            make.top.equalTo(reportButton)
            make.width.height.equalTo(reportButton)
        }

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

    override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
}

// MARK: View
class HistoryItemView : DDView {
    public let tableView = DDTableView.init(frame: CGRectZero)
    override init(frame: CGRect) {
        super.init(frame: frame)
        tableView.separatorStyle = .none
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: JXCategoryListContentViewDelegate
extension HistoryItemController : JXCategoryListContentViewDelegate {
    func listView() -> UIView! {
        return view
    }
}
