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

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

extension MessageCenterController {
    func addActions() {
        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.messageReminderList(parameters: MessageReminderListParameters(pageNum: pageNum)).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?.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)
                    }
                    
                    if self?.resultArr.isEmpty == false {
                        self?.emptyView.isHidden = true
                    }else{
                        self?.emptyView.isHidden = false
                    }
                    
                    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)
        
        readRelay
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_showHUD()
            })
            .flatMapLatest { model in
                return Observable.zip(RQ.readMessageReminder(parameters: ReadMessageReminderParameters(id: model.id)).asObservable(), Observable.just(model))
            }
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] (response,model) in
                if response?.success == true {
                    for _model in (self?.resultArr ?? []) {
                        if _model.id == model.id {
                            _model.hasRead.code = .YES
                        }
                    }
                    self?.messageCenterView.tableView.reloadData()
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
        
        refreshRelay.accept(1)
    }
}

// MARK: UITableViewDelegate,UITableViewDataSource
extension MessageCenterController : 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? MessageCenterCell
        if cell == nil {
            cell = MessageCenterCell(style: .default, reuseIdentifier: "cell")
        }
        
        let model = resultArr[indexPath.item]
        let desc = NSMutableAttributedString(string: model.content ?? "",attributes: [.font: UIFont.mediumFont(13),.foregroundColor : UIColor.dd_hex(light: "000000", dark: "000000").withAlphaComponent(0.75)])
        if model.msgType.code == 6 {
            desc.append(NSMutableAttributedString(string: "\n\n为获取更多案件",attributes: [.font : UIFont.mediumFont(16),.foregroundColor: UIColor.dd_hex(light: "000000", dark: "000000").withAlphaComponent(0.9)]))
            desc.append(NSMutableAttributedString(string: "\n\n请提醒在班的师傅登录APP并合理保持在线。",attributes: [.font : UIFont.mediumFont(13),.foregroundColor: UIColor.dd_hex(light: "000000", dark: "000000").withAlphaComponent(0.75)]))
        }
        cell!.descLabel.attributedText = desc
        cell!.noticeLabel.text = " " + model.title + " "
        cell!.noticeLabel.backgroundColor = .hex(model.titleColor)
        cell!.orderNumLabel.text = model.titleContent
        cell!.dateLabel.text = TOOL.getDateStringCompareWithNow(dateFormat:"yyyy-MM-dd HH:mm:ss",dateString: model.createTime)
        if model.imgPath?.isEmpty == false {
            cell?.descImageView.sd_setImage(with: URL(string: model.imgPath ?? ""))
            cell?.descImageView.snp.updateConstraints({ make in
                make.top.equalTo(cell!.descLabel.snp.bottom).offset(auto(5))
                make.height.equalTo(auto(100))
            })
            cell?.readButton.snp.updateConstraints({ make in
                make.top.equalTo(cell!.descImageView.snp.bottom).offset(auto(10))
            })
        }else{
            cell?.descImageView.image = nil
            cell?.descImageView.snp.updateConstraints({ make in
                make.height.equalTo(0)
                make.top.equalTo(cell!.descLabel.snp.bottom).offset(0)
            })
            cell?.readButton.snp.updateConstraints({ make in
                make.top.equalTo(cell!.descImageView.snp.bottom).offset(0)
            })
        }
        if model.hasRead.code == .YES {
            cell?.readButton.isUserInteractionEnabled = false
            cell?.readButton.setTitleColor(.hex("000000").alpha(0.4), for: .normal)
            cell?.readButton.setTitle("已处理", for: .normal)
        }else{
            cell?.readButton.isUserInteractionEnabled = true
            cell?.readButton.setTitleColor(.hex("FA8D14"), for: .normal)
            cell?.readButton.setTitle("点击处理", for: .normal)
        }
        
        cell?.readButton.rx.tap
            .subscribe(onNext: {[weak self] _ in
                self?.readRelay.accept(model)
            })
            .disposed(by: cell!.disposeBag)
        return cell!
    }
}

open class MessageCenterController : ZDViewController {
    private let messageCenterView = MessageCenterView()
    private var emptyView = EmptyView()
    private var pageNum : Int = 1
    private var refreshRelay = ReplayRelay<Int>.create(bufferSize: 1)
    private var readRelay = ReplayRelay<MessageReminderListDataModel>.create(bufferSize: 1)
    private var resultArr : [MessageReminderListDataModel] = []
    private let disposeBag = DisposeBag()
    public var disappearHandler: (() -> Void)?
    
    deinit {
        if disappearHandler != nil {
            disappearHandler!()
        }
    }
    
    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]

        addSubviews()
        addActions()
    }
    
    func addSubviews() {
        view.backgroundColor = .hex("FAFAFA")
        view.addSubview(messageCenterView)

        messageCenterView.tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.equalTo(auto(303))
            make.height.equalTo(auto(94))
        }
        
        messageCenterView.tableView.delegate = self
        messageCenterView.tableView.dataSource = self
    }
    
    open override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        messageCenterView.snp.remakeConstraints { make in
            make.top.equalTo(view.safeAreaInsets.top)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

open class MessageCenterView : 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")
    }
}

open class MessageCenterCell : DDTableViewCell {
    public let radiusView : DDView
    public let noticeLabel : DDLabel
    public let orderNumLabel : DDLabel
    public let dateLabel : DDLabel
    public let descLabel : DDLabel
    public let descImageView : DDImageView
    public let readButton : DDButton
    public var disposeBag : DisposeBag
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        radiusView = DDView()
        noticeLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(10)), textColor: .white)
        orderNumLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("000000").alpha(0.55))
        dateLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(11)), textColor: .hex("000000").alpha(0.55))
        descLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(13)), textColor: .hex("000000").alpha(0.75))
        descImageView = DDImageView()
        readButton = DDButton.dd_initCustom()
        disposeBag = DisposeBag()
        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)
        noticeLabel.layer.cornerRadius = auto(2)
        noticeLabel.layer.masksToBounds = true
        radiusView.addSubview(noticeLabel)
        radiusView.addSubview(orderNumLabel)
        radiusView.addSubview(dateLabel)
        descLabel.numberOfLines = 0
        radiusView.addSubview(descLabel)
        descImageView.contentMode = .scaleAspectFill
        descImageView.layer.masksToBounds = true
        descImageView.layer.cornerRadius = auto(10)
        radiusView.addSubview(descImageView)
        readButton.titleLabel?.textAlignment = .right
        readButton.titleLabel?.font = .mediumFont(auto(13))
        radiusView.addSubview(readButton)
        
        radiusView.snp.makeConstraints { make in
            make.left.top.equalTo(auto(10))
            make.right.equalTo(-auto(10))
            make.bottom.equalTo(0)
        }
        
        noticeLabel.snp.makeConstraints { make in
            make.top.left.equalTo(auto(10))
            make.height.equalTo(auto(15))
        }
        
        orderNumLabel.snp.makeConstraints { make in
            make.left.equalTo(noticeLabel.snp.right).offset(auto(10))
            make.centerY.equalTo(noticeLabel)
        }
        
        dateLabel.snp.makeConstraints { make in
            make.right.equalTo(-auto(10))
            make.centerY.equalTo(noticeLabel)
        }
        
        descLabel.snp.makeConstraints { make in
            make.top.equalTo(noticeLabel.snp.bottom).offset(auto(10))
            make.left.equalTo(noticeLabel)
            make.right.equalTo(dateLabel)
        }
        
        descImageView.snp.makeConstraints { make in
            make.top.equalTo(descLabel.snp.bottom).offset(auto(5))
            make.left.equalTo(descLabel)
            make.right.equalTo(descLabel)
            make.height.equalTo(auto(100))
        }
        
        readButton.snp.makeConstraints { make in
            make.right.equalTo(dateLabel)
            make.top.equalTo(descImageView.snp.bottom).offset(auto(5))
            make.height.equalTo(auto(20))
            make.bottom.equalTo(-auto(5))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
}
