//
//  ReviewFailedController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/14.
//

import Foundation
import DDAutoUIKit_Private
import DDControlsKit_Private
import SnapKit
import RxSwift
import RxRelay
import RxCocoa
import MJRefresh
import ESTabBarController_swift
import PopupDialog

extension ReviewFailedController {
    func addActions() {
        MCOUNT.messageCountRelay
            .observe(on: MainScheduler.instance)
            .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
//            .observe(on: MainScheduler.instance)
//            .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)
        
        reviewFailedView.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.pageNum = 1
            self?.refreshRelay.accept(self?.pageNum ?? 1)
        })
        
        reviewFailedView.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: self?.conditionalSearchTool.getParameters(pageNum: pageNum,queryType:  .TO_AUDIT_FAILED) ?? OrderListParameters(pageNum: pageNum, queryType: .TO_AUDIT_FAILED)).asObservable(), Observable.just(pageNum))
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] (response, pageNum) in
                if response?.success == true {
                    if pageNum == 1 {
                        self?.resultArr.removeAll()
                        self?.reviewFailedView.tableView.mj_footer?.resetNoMoreData()
                        self?.reviewFailedView.tableView.mj_header?.endRefreshing()
                    }else{
                        if response?.data?.isEmpty == false {
                            self?.reviewFailedView.tableView.mj_footer?.endRefreshing()
                        }else{
                            self?.reviewFailedView.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    }
                    
                    if let array = response?.data {
                        self?.resultArr.append(contentsOf: array)
                    }
                    
                    if self?.resultArr.isEmpty == false {
                        self?.emptyView.isHidden = true
                    }else{
                        self?.emptyView.isHidden = false
                    }
                    
                    self?.reviewFailedView.tableView.reloadData()
                }else{
                    if pageNum == 1 {
                        self?.reviewFailedView.tableView.mj_header?.endRefreshing()
                    }else{
                        self?.reviewFailedView.tableView.mj_footer?.endRefreshing()
                    }
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        messageTapGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                MESSAGETOOL.openMessageCenter(by: self?.navigationController)
            })
            .disposed(by: disposeBag)
        
//        pendingTapGes.rx.event
//            .observe(on: MainScheduler.instance)
//            .subscribe(onNext: { _ in
//                WEBTOOL.open(name: .todoList,appending: nil)
//            })
//            .disposed(by: disposeBag)
        
        filterButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.conditionalSearchTool.showFilterView()
            })
            .disposed(by: disposeBag)
        
        conditionalSearchTool.isFilterSub
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] isFilter in
                ConditionalSearchTool.resetFilterButton(self?.filterButton, filterState: isFilter, type: .reviewFailed)
            })
            .disposed(by: disposeBag)
        
        conditionalSearchTool.searchSub
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.reviewFailedView.tableView.mj_header?.beginRefreshing()
            })
            .disposed(by: disposeBag)
        
        preRefreshRelay
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                NewTraining.default.newTrainingRelay.accept(nil)
                MCOUNT.newestMessage()
                self?.reviewFailedView.tableView.mj_header?.beginRefreshing()
                /// 点击tabbar item重置
                ConditionalSearchTool.resetFilterButton(self?.filterButton, filterState: false, type: .reviewFailed)
            })
            .disposed(by: disposeBag)
        
        USERP.userPermissionRelay
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.reviewFailedView.tableView.reloadData()
            })
            .disposed(by: disposeBag)
    }
}

// MARK: UITableViewDelegate,UITableViewDataSource
extension ReviewFailedController : UITableViewDelegate,UITableViewDataSource {
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return resultArr.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ReviewFailedCell
        if cell == nil {
            cell = ReviewFailedCell(style: .default, reuseIdentifier: "cell")
        }
        let model = resultArr[indexPath.row]
        cell!.orderStatusTitleLabel.text = "状态:"
        cell!.orderStatusLabel.text = model.taskOrderStatusString
        cell!.descLabel.text = "不通过原因:" + (model.auditFailReason ?? "")
        cell!.typeLabel.text = model.taskServiceName
        cell!.orderNumLabel.text = model.orderCode
        cell!.dateLabel.text = model.createTime
        
        if model.taskOrderStatusString == "任务完成" {
            cell?.orderStatusLabel.textColor = .hex("09B820")
        }else{
            cell?.orderStatusLabel.textColor = .hex("E64C0B")
        }
        
        cell!.additionalButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                let vc = AdditionalPhotoController(userOrderId: model.userOrderId, orderCode: model.orderCode, taskOrderId: model.taskOrderId,canModify: true)
                self?.navigationController?.pushViewController(vc, animated: true)
            })
            .disposed(by: cell!.disposeBag)
        
        cell!.appealButton.rx.tap
            .flatMapLatest({ _ in
                return RQ.getAppeal(parameters: GetAppealParameters(orderCode: model.orderCode))
            })
            .flatMapLatest({ [weak self] response -> Observable<String> in
                // 若已有申诉，提示并结束流
                guard response?.data == nil else {
                    DispatchQueue.main.async {
                        self?.view.dd_makeToast("该订单正在申诉中")
                    }
                    return .empty()
                }
                // 否则弹出输入框，异步拿到申诉理由
                return Observable<String>.create { ob in
                    guard let self = self else { return Disposables.create() }
                    DispatchQueue.main.async {
                        self.presentAppealPopup(from: self) { reason in
                            ob.onNext(reason)
                            ob.onCompleted()
                        }
                    }
                    return Disposables.create()
                }
            })
            .flatMapLatest({ reason in
                return RQ.saveAppeal(parameters: SaveAppealParameters(orderCode: model.orderCode, vehicleId: model.taskVehicleId, msg: reason))
            })
            .observe(on: ConcurrentMainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: cell!.disposeBag)
            
        if USERP.canSupplierAuditUploadPhotoBtn == true {
            cell?.additionalButton.isHidden = false
        }else{
            cell?.additionalButton.isHidden = true
        }
        
        if model.showAppealBtn == true {
            cell?.appealButton.isHidden = false
        }else{
            cell?.appealButton.isHidden = true
        }
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = resultArr[indexPath.row]
        WEBTOOL.open(name: .workOrderDetail, appending: "&queryType=\(OrderTypeEnum.TO_AUDIT_FAILED.rawValue)&userOrderId=\(model.userOrderId)&orderCode=\(model.orderCode)&taskOrderId=\(model.taskOrderId)")
    }
}

open class ReviewFailedController : ZDViewController {
    private let reviewFailedView = ReviewFailedView()
    private var pageNum : Int = 1
    private var preRefreshRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private var refreshRelay = ReplayRelay<Int>.create(bufferSize: 1)
    private let disposeBag = DisposeBag()
    private var resultArr : [OrderListDataModel] = []
    private let messageTapGes = UITapGestureRecognizer()
    private let messageView = MessageView()
//    private let pendingTapGes = UITapGestureRecognizer()
//    private let pendingView = MessageView()
    private var emptyView = EmptyView()

    private let filterButton = DDButton.dd_initCustom()
    private lazy var conditionalSearchTool = ConditionalSearchTool()
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        MCOUNT.reviewFailedCountRelay
                .observe(on: MainScheduler.instance)
                .subscribe(onNext: {[weak self] count in
                if let tabBar = self?.tabBarController?.tabBar as? ESTabBar {
                    let tabBarItem = tabBar.items?[1]
                    if count > 0 {
                        tabBarItem?.badgeValue = String(count)
                    }else{
                        tabBarItem?.badgeValue = nil
                    }
                }
            })
            .disposed(by: disposeBag)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "审核失败"
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]
        navigationItem.leftBarButtonItems = nil
        
        addSubviews()
        addActions()
    }
    
    func addSubviews() {
        view.backgroundColor = .hex("FAFAFA")
        view.addSubview(reviewFailedView)
        
        reviewFailedView.tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.equalTo(auto(303))
            make.height.equalTo(auto(94))
        }
        
        reviewFailedView.tableView.delegate = self
        reviewFailedView.tableView.dataSource = self
        
        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)
//        }
        ConditionalSearchTool.configFilterButton(filterButton,type: .reviewFailed)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: filterButton)
    }
    
    open override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        // view.safeAreaInsets.bottom为0的时候是hiddenBottomBar的时候，此时不必约束，由于是首页所以view.safeAreaInsets.bottom一定是大于0的
        if view.safeAreaInsets.bottom != 0 {
            reviewFailedView.snp.remakeConstraints { make in
                make.top.equalTo(view.safeAreaInsets.top)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(-view.safeAreaInsets.bottom)
            }
            
            conditionalSearchTool.bottomSafeArea = view.safeAreaInsets.bottom - 49
        }
    }

    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    open override func reloadData() {
        super.reloadData()
        preRefreshRelay.accept(nil)
    }
    
    /// 弹出“申诉理由”输入弹窗
    /// - Parameters:
    ///   - from: 当前控制器
    ///   - prefill: 预填内容
    ///   - onConfirm: 点击【确定】回调（返回填写的文本）
    func presentAppealPopup(from: UIViewController,
                            prefill: String? = nil,
                            onConfirm: @escaping (String) -> Void) {

        // 内容 VC
        let inputVC = AppealInputViewController(prefill: prefill)

        // 弹窗
        let popup = PopupDialog(
            viewController: inputVC,
            buttonAlignment: .horizontal,      // 底部按钮水平排列
            transitionStyle: .bounceDown,      // 动画风格
            tapGestureDismissal: false,        // 点击外部不关闭
            panGestureDismissal: false         // 禁止下拉关闭（避免误触）
        )

        // 取消
        let cancel = CancelButton(title: "取消") {
            // do nothing
        }

        // 确定
        let ok = DefaultButton(title: "确定", dismissOnTap: false) {
            let text = inputVC.textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
            guard text.isEmpty == false else {
                // 简单的必填校验（也可改成 toast / 抖动）
                inputVC.textField.layer.borderColor = UIColor.systemRed.withAlphaComponent(0.6).cgColor
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
                return
            }
            popup.dismiss() {
                onConfirm(text)
            }
        }

        popup.addButtons([cancel, ok])

        // （可选）统一外观：分割线/按钮颜色/标题样式
        let pv = PopupDialogDefaultView.appearance()
        pv.titleFont  = .systemFont(ofSize: 16, weight: .semibold)
        pv.titleTextAlignment = .center
        pv.titleColor = .black
        pv.messageTextAlignment = .center

        let cb = CancelButton.appearance()
        cb.titleColor = UIColor.darkText
        cb.separatorColor = UIColor.systemGray5

        let db = DefaultButton.appearance()
        db.titleColor = UIColor.systemBlue
        db.separatorColor = UIColor.systemGray5

        from.present(popup, animated: true)
    }
}

open class ReviewFailedView : DDView {
    public let tableView : DDTableView
    public override init(frame: CGRect) {
        tableView = DDTableView(frame: CGRectZero, style: .plain)
        super.init(frame: frame)
        
        tableView.backgroundColor = .hex("FAFAFA")
        tableView.separatorStyle = .none
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// Gradient button subclass for ReviewFailedCell buttons
public final class DDGradientButton: DDButton {
    public override class var layerClass: AnyClass { CAGradientLayer.self }
    var gradientLayer: CAGradientLayer { return self.layer as! CAGradientLayer }

    func configureGradient(start: CGPoint = CGPoint(x: 0, y: 0),
                           end: CGPoint = CGPoint(x: 1, y: 1),
                           locations: [NSNumber] = [0.0, 1.0],
                           colors: [CGColor]) {
        gradientLayer.startPoint = start
        gradientLayer.endPoint = end
        gradientLayer.locations = locations
        gradientLayer.colors = colors
        gradientLayer.masksToBounds = true
        gradientLayer.needsDisplayOnBoundsChange = true
    }
}

open class ReviewFailedCell : DDTableViewCell {
    public let radiusView : DDView
    public let typeLabel : DDLabel
    public let orderNumLabel : DDLabel
    public let orderStatusTitleLabel : DDLabel
    public let orderStatusLabel : DDLabel
    public let descLabel : DDLabel
    public let dateLabel : DDLabel
    public let stackView : UIStackView
    public let appealButton : DDGradientButton
    public let additionalButton : DDGradientButton
    public var disposeBag = DisposeBag()
    
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        radiusView = DDView()
        typeLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(14)), textColor: .hex("000000").alpha(0.85))
        orderNumLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.55))
        orderStatusTitleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.5))
        orderStatusLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("E69B0B"))
        descLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("FF8F37"))
        dateLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000").alpha(0.55))
        stackView = UIStackView()
        additionalButton = DDGradientButton()
        appealButton = DDGradientButton()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        backgroundColor = .hex("F4F5F7")
        selectionStyle = .none
        
        radiusView.backgroundColor = .white
        radiusView.layer.cornerRadius = auto(6)
        radiusView.layer.shadowColor = UIColor.hex("D8D8D8").cgColor
        radiusView.layer.shadowOffset = CGSize(width: 0, height: 3)
        radiusView.layer.shadowRadius = 5
        radiusView.layer.shadowOpacity = 1
        contentView.addSubview(radiusView)
        radiusView.addSubview(typeLabel)
        radiusView.addSubview(orderNumLabel)
        radiusView.addSubview(orderStatusTitleLabel)
        orderStatusLabel.numberOfLines = 0
        radiusView.addSubview(orderStatusLabel)
        descLabel.numberOfLines = 0
        radiusView.addSubview(descLabel)
        radiusView.addSubview(dateLabel)
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        stackView.alignment = .center
        stackView.spacing = 10
        radiusView.addSubview(stackView)
        appealButton.setTitle("申诉", for: .normal)
        appealButton.setTitleColor(.white, for: .normal)
        appealButton.titleLabel?.font = .mediumFont(auto(13))
        appealButton.layer.cornerRadius = auto(4)
        appealButton.layer.masksToBounds = true
        appealButton.contentEdgeInsets = UIEdgeInsets(top: auto(6), left: auto(12), bottom: auto(6), right: auto(12))
        appealButton.configureGradient(colors: [UIColor.hex("FF5A2C").cgColor, UIColor.hex("FE9D4D").cgColor])
        stackView.addArrangedSubview(appealButton)
        additionalButton.setTitle("补充", for: .normal)
        additionalButton.setTitleColor(.white, for: .normal)
        additionalButton.titleLabel?.font = .mediumFont(auto(13))
        additionalButton.layer.cornerRadius = auto(4)
        additionalButton.layer.masksToBounds = true
        additionalButton.contentEdgeInsets = UIEdgeInsets(top: auto(6), left: auto(12), bottom: auto(6), right: auto(12))
        additionalButton.configureGradient(colors: [UIColor.hex("FF5A2C").cgColor, UIColor.hex("FE9D4D").cgColor])
        stackView.addArrangedSubview(additionalButton)

        radiusView.snp.makeConstraints { make in
            make.left.top.equalTo(auto(10))
            make.right.equalTo(-auto(10))
            make.bottom.equalTo(0)
        }
        
        typeLabel.snp.makeConstraints { make in
            make.top.left.equalTo(auto(10))
            make.height.equalTo(auto(15))
        }
        
        orderNumLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel.snp.right).offset(auto(10))
            make.centerY.equalTo(typeLabel)
        }
        
        orderStatusTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel)
            make.top.equalTo(orderNumLabel.snp.bottom).offset(auto(10))
        }
        
        orderStatusLabel.snp.makeConstraints { make in
            make.height.equalTo(orderStatusTitleLabel)
            make.top.equalTo(orderStatusTitleLabel)
            make.left.equalTo(orderStatusTitleLabel.snp.right).offset(auto(10))
        }

        descLabel.snp.makeConstraints { make in
            make.top.equalTo(orderStatusTitleLabel.snp.bottom).offset(auto(10))
            make.left.equalTo(typeLabel)
            make.right.equalTo(-auto(20))
        }
        
        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(descLabel)
            make.top.equalTo(descLabel.snp.bottom).offset(auto(10))
            make.bottom.equalTo(-auto(15))
        }
        
        stackView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-auto(10))
            make.centerY.equalTo(dateLabel)
            make.height.equalTo(auto(50))
            make.left.greaterThanOrEqualTo(dateLabel.snp.right).offset(auto(10))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
        appealButton.isHidden = true
        additionalButton.isHidden = true
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
    }
}
