//
//  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

extension ReviewFailedController {
    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)
        
        messageCenterView.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.pageNum = 1
            self?.refreshRelay.accept(self?.pageNum ?? 1)
        })
        
        messageCenterView.tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: {[weak self] in
            self?.pageNum+=1
            self?.refreshRelay.accept(self?.pageNum ?? 1)
        })

        refreshRelay
            .flatMapLatest { pageNum in
                return Observable.zip(RQ.orderList(parameters: 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 {
                        if response?.data?.isEmpty == false {
                            self?.resultArr.removeAll()
                            self?.messageCenterView.tableView.mj_footer?.resetNoMoreData()
                        }
                        self?.messageCenterView.tableView.mj_header?.endRefreshing()
                    }else{
                        if response?.data?.isEmpty == false {
                            self?.messageCenterView.tableView.mj_footer?.endRefreshing()
                        }else{
                            self?.messageCenterView.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    }
                    
                    if let array = response?.data {
                        self?.resultArr.append(contentsOf: array)
                        self?.messageCenterView.tableView.reloadData()
                    }
                }else{
                    if pageNum == 1 {
                        self?.messageCenterView.tableView.mj_header?.endRefreshing()
                    }else{
                        self?.messageCenterView.tableView.mj_footer?.endRefreshing()
                    }
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        messageCenterView.tableView.mj_header?.beginRefreshing()
    }
}

// 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!.descLabel.text = model.auditFailReason
        cell!.typeLabel.text = model.taskServiceName
        cell!.stateLabel.text = model.taskOrderStatusString
        cell!.orderNumLabel.text = model.orderCode
        cell!.dateLabel.text = model.createTime
        
        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)
                self?.navigationController?.pushViewController(vc, animated: true)
            })
            .disposed(by: cell!.disposeBag)
        return cell!
    }
}

open class ReviewFailedController : DDViewController {
    private let messageCenterView = ReviewFailedView()
    private var pageNum : Int = 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()
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        dd_navigationItemTitle = "审核失败"
        dd_navigationBarBackgroundColor = .hex("354683")
        dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        navigationItem.leftBarButtonItems = nil
        
        addSubviews()
        addActions()
    }
    
    func addSubviews() {
        view.backgroundColor = .hex("F4F5F7")
        view.addSubview(messageCenterView)
        messageCenterView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
        
        messageCenterView.tableView.delegate = self
        messageCenterView.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)
        }
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

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("F4F5F7")
        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")
    }
}

open class ReviewFailedCell : DDTableViewCell {
    public let radiusView : DDView
    public let typeLabel : DDLabel
    public let orderNumLabel : DDLabel
    public let stateLabel : DDLabel
    public let descLabel : DDLabel
    public let dateLabel : DDLabel
    public let additionalButton : DDButton
    public var additionalLayer : CAGradientLayer = {
        var layer = CAGradientLayer.init()
        layer.startPoint = CGPoint(x: 0, y: 0)
        layer.endPoint = CGPoint(x: 1, y: 1)
        layer.locations = [0.0,1.0]
        layer.colors = [UIColor.hex("FF5A2C").cgColor,UIColor.hex("FE9D4D").cgColor]
        layer.cornerRadius = auto(4)
        layer.masksToBounds = true
        return layer
    }()
    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))
        stateLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("09B820"))
        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))
        additionalButton = DDButton.dd_initCustom()
        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(stateLabel)
        descLabel.numberOfLines = 0
        radiusView.addSubview(descLabel)
        radiusView.addSubview(dateLabel)
        additionalButton.setTitle("补充", for: .normal)
        additionalButton.setTitleColor(.white, for: .normal)
        additionalButton.titleLabel?.font = .mediumFont(auto(13))
        additionalButton.layer.cornerRadius = auto(4)
        additionalButton.layer.masksToBounds = true
        radiusView.addSubview(additionalButton)
        additionalButton.layer.insertSublayer(additionalLayer, at: 0)

        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(20))
            make.centerY.equalTo(typeLabel)
        }
        
        stateLabel.snp.makeConstraints { make in
            make.right.equalTo(-auto(10))
            make.centerY.equalTo(typeLabel)
        }
        
        descLabel.snp.makeConstraints { make in
            make.top.equalTo(typeLabel.snp.bottom).offset(auto(10))
            make.left.equalTo(typeLabel)
            make.right.equalTo(stateLabel)
        }
        
        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(descLabel)
            make.top.equalTo(descLabel.snp.bottom).offset(auto(10))
            make.bottom.equalTo(-auto(15))
        }
        
        additionalButton.snp.makeConstraints { make in
            make.right.equalTo(stateLabel)
            make.centerY.equalTo(dateLabel)
            make.width.equalTo(auto(50))
            make.height.equalTo(auto(20))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        additionalLayer.frame = CGRectMake(0, 0, auto(50), auto(20))
    }
}
