//
//  ConditionalSearchTool.swift
//  OrderScheduling
//
//  Created by 中道 on 2024/1/2.
//

import Foundation
import RxSwift
import RxRelay
import RxCocoa
import SnapKit
import DDControlsKit_Private
import DDAutoUIKit_Private

class ConditionalSearchTool : NSObject {
    enum FilterButtonTypeEnum {
    case rescue,reviewFailed,history
    }
    
    public lazy var searchView = ConditionalSearchView.init()
    public var bottomSafeArea : CGFloat = 0.0 {
        willSet {
            DispatchQueue.main.async {[weak self] in
                self?.searchView.remakeBottomViewConstraints(bottomSafeArea: newValue)
            }
        }
    }
    
    private let disposeBag = DisposeBag()
    
    ///  任务信息
    public var orderCodeItem : String?
    public var carOwnerItem : String?
    public var licenseItem : String?
    
    /// 合同信息
    public var contractNameItem : String?
    public var contractSelectedItem : Int?
    public var contractSelectedItemString : String?
    
    /// 事发时间
    public var fromSelectedItem : String?
    public var toSelectedItem : String?
    
    /// 服务内容
    public var serviceSelectedItem : Int?
    public var serviceSelectedItemString : String?
    public var serviceNameItem : String?
    
    public var searchParameters : OrderListParameters?
    
    public var searchSub = ReplayRelay<Any?>.create(bufferSize: 1)
    
    public var isFilterSub = ReplayRelay<Bool>.create(bufferSize: 1)
    public var isShowed : Bool = false
    
    override init() {
        super.init()
        
        searchView.contractTypeButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                CP.showItems(items: [OrderListParameters.ContractTypeEnum.baoxian.rawValue,OrderListParameters.ContractTypeEnum.chechan.rawValue,OrderListParameters.ContractTypeEnum.fours.rawValue,OrderListParameters.ContractTypeEnum.wuliu.rawValue,OrderListParameters.ContractTypeEnum.sanke.rawValue,OrderListParameters.ContractTypeEnum.xuni.rawValue,OrderListParameters.ContractTypeEnum.yiliao.rawValue,OrderListParameters.ContractTypeEnum.zixun.rawValue,OrderListParameters.ContractTypeEnum.huicheng.rawValue],selectedItem: self?.contractSelectedItemString) {[weak self] result in
                    
                    self?.contractSelectedItemString = result?.value
                    self?.contractSelectedItem = OrderListParameters.ContractTypeValue(contractType: OrderListParameters.ContractTypeEnum(rawValue: result?.value ?? OrderListParameters.ContractTypeEnum.none.rawValue) ?? OrderListParameters.ContractTypeEnum.none).value
                    
                    DispatchQueue.main.async {[weak self] in
                        self?.searchView.setButtonValue(button: self?.searchView.contractTypeButton, value: result?.value)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        searchView.serviceAppointButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                CP.showItems(items: [OrderListParameters.ServiceTypeEnum.shi.rawValue,OrderListParameters.ServiceTypeEnum.fou.rawValue], selectedItem: self?.serviceSelectedItemString) {[weak self] result in
                    self?.serviceSelectedItem = OrderListParameters.ServiceTypeValue(serviceType: OrderListParameters.ServiceTypeEnum(rawValue: result?.value ?? OrderListParameters.ServiceTypeEnum.none.rawValue) ?? OrderListParameters.ServiceTypeEnum.none).value
                    self?.serviceSelectedItemString = result?.value
                   
                    DispatchQueue.main.async {[weak self] in
                        self?.searchView.setButtonValue(button: self?.searchView.serviceAppointButton, value: result?.value)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        searchView.fromDateButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                CP.showDate() {[weak self] date, dateString in
                    self?.fromSelectedItem = dateString
                    
                    DispatchQueue.main.async {
                        self?.searchView.setButtonValue(button: self?.searchView.fromDateButton, value: dateString)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        searchView.toDateButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                CP.showDate() {[weak self] date, dateString in
                    self?.toSelectedItem = dateString
                    
                    DispatchQueue.main.async {
                        self?.searchView.setButtonValue(button: self?.searchView.toDateButton, value: dateString)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        searchView.orderCodeTextFiled.rx.text
            .subscribe(onNext: {[weak self] text in
                self?.orderCodeItem = text?.isEmpty == false ? text : nil
            })
            .disposed(by: disposeBag)
        
        searchView.carOwnerTextField.rx.text
            .subscribe(onNext: {[weak self] text in
                self?.carOwnerItem = text?.isEmpty == false ? text : nil
            })
            .disposed(by: disposeBag)
        
        searchView.licenseTextField.rx.text
            .subscribe(onNext: {[weak self] text in
                self?.licenseItem = text?.isEmpty == false ? text : nil
            })
            .disposed(by: disposeBag)
        
        searchView.serviceTextField.rx.text
            .subscribe(onNext: {[weak self] text in
                self?.serviceNameItem = text?.isEmpty == false ? text : nil
            })
            .disposed(by: disposeBag)
        
        searchView.resetButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.searchView.resetAction()
                
                self?.orderCodeItem = nil
                self?.carOwnerItem = nil
                self?.licenseItem = nil
                
                self?.contractSelectedItem = nil
                self?.contractSelectedItemString = nil

                self?.fromSelectedItem = nil
                self?.toSelectedItem = nil
                
                self?.serviceSelectedItem = nil
                self?.serviceSelectedItemString = nil
                self?.serviceNameItem = nil

                /// 重置后直接刷新新数据
                self?.searchSub.accept(nil)
                self?.isFilterSub.accept(self?.isFiltered() ?? false)
            })
            .disposed(by: disposeBag)
        
        searchView.exitButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                 self?.hideFilterView()
            })
            .disposed(by: disposeBag)
        
        searchView.searchButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.hideFilterView()
                self?.searchSub.accept(nil)
                self?.isFilterSub.accept(self?.isFiltered() ?? false)
            })
            .disposed(by: disposeBag)
    }
    
    func getParameters(pageNum: Int,queryType: OrderTypeEnum) -> OrderListParameters {
        return OrderListParameters(pageNum: pageNum, queryType: queryType, searchCode: orderCodeItem, userPhone: carOwnerItem, soleCode: licenseItem, contractName: contractNameItem, contractType:contractSelectedItem,createTimeStart: fromSelectedItem,createTimeEnd: toSelectedItem,isAppoint: serviceSelectedItem,serviceName: serviceNameItem)
    }
    
    func isFiltered() -> Bool {
        if orderCodeItem?.isEmpty == false || carOwnerItem?.isEmpty == false || licenseItem?.isEmpty == false || contractSelectedItem != nil || contractNameItem?.isEmpty == false || fromSelectedItem?.isEmpty == false || toSelectedItem?.isEmpty == false || serviceSelectedItem != nil || serviceNameItem?.isEmpty == false {
            return true
        }
        return false
    }

    @objc func showFilterView() {
        ENTRY.showSearchEntry(view: searchView, name: conditionalSearchEntry, bottomHeight: bottomSafeArea)
    }
    
    func hideFilterView() {
        ENTRY.dismiss(name: conditionalSearchEntry)
    }
    
    class func configFilterButton(_ filterButton: DDButton, type: FilterButtonTypeEnum){
        var backgroundColor : UIColor
        var titleColor : UIColor
        if type == .reviewFailed {
            backgroundColor = .clear
            titleColor = .hex("FFFFFF").alpha(0.7)
            filterButton.titleLabel?.font = .mediumFont(14)
        }else{
            backgroundColor = .hex("FAFAFA")
            titleColor = .hex("737373").alpha(0.55)
            
            let seperateLine = DDView()
            seperateLine.backgroundColor = .hex("737373").alpha(0.3)
            filterButton.addSubview(seperateLine)
            seperateLine.snp.makeConstraints { make in
                make.centerY.equalTo(filterButton)
                make.width.equalTo(1)
                make.height.equalTo(filterButton).multipliedBy(0.5)
                make.left.equalTo(filterButton.snp.left)
            }
            filterButton.titleLabel?.font = .regularFont(auto(12))
        }
        filterButton.dd_setBackgroundColor(backgroundColor)
        filterButton.setTitle("筛选", for: .normal)
        filterButton.setTitleColor(titleColor, for: .normal)
        filterButton.setImage(UIImage(named: "conditional_search_unselected")?.withTintColor(titleColor), for: .normal)
        filterButton.dd_customize(with: .ImageRightPaddingTitleLeftWithWholeCenter, padding: 5)
    }
    
    class func resetFilterButton(_ filterButton: DDButton?, filterState: Bool, type: FilterButtonTypeEnum) {
        var titleColor : UIColor
        if type == .reviewFailed {
            titleColor = .hex("FFFFFF").alpha(0.7)
        }else{
            titleColor = .hex("737373").alpha(0.55)
        }
        if filterState == true {
            filterButton?.setTitleColor(.hex("3678FF"), for: .normal)
            filterButton?.setImage(UIImage(named: "conditional_search"), for: .normal)
            filterButton?.setTitle("已筛选", for: .normal)
            filterButton?.dd_customize(with: .ImageRightPaddingTitleLeftWithWholeCenter, padding: 5)
            filterButton?.sizeToFit()
        }else{
            filterButton?.setTitleColor(titleColor, for: .normal)
            filterButton?.setImage(UIImage(named: "conditional_search_unselected")?.withTintColor(titleColor), for: .normal)
            filterButton?.setTitle("筛选", for: .normal)
            filterButton?.dd_customize(with: .ImageRightPaddingTitleLeftWithWholeCenter, padding: 5)
            filterButton?.sizeToFit()
        }
    }

}
