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

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

extension MineController {
    func addActions() {
        mineView.logoutButton.rx.tap
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_showHUD()
            })
            .flatMapLatest({ _ in
                return RQ.logout(parameters: LogoutParameters(deviceId: 1))
            })
            .observe(on: MainScheduler.instance)
            .do(onNext: {[weak self] _ in
                self?.view.dd_hideHUD()
            })
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    USER.clear()
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification_logoutSuccessToLoginController), object: nil)
                }else{
                    self?.view.dd_makeToast(response?.msg)
                }
            })
            .disposed(by: disposeBag)
                
          refreshRelay
                .flatMapLatest { _ in
                    return RQ.generalInfo()
                }
                .observe(on: MainScheduler.instance)
                .subscribe(onNext: {[weak self] response in
                    if response?.success == true {
                        self?.mineView.carInfoView.descLabel.text = String(response?.data?.vehicleCount ?? 0)+"台"
                        self?.mineView.driverInfoView.descLabel.text = String(response?.data?.driverCount ?? 0)+"台"
                        if let icon = response?.data?.icon {
                            self?.mineView.avatar.sd_setImage(with: URL(string: icon))
                        }
                        if let phone = response?.data?.phone{
                            self?.mineView.accountLabel.text = "账号:\(phone)"
                        }
                        if let company = response?.data?.supplierName {
                            self?.mineView.companyLabel.text = company
                        }
                    }else{
                        self?.view.dd_makeToast(response?.msg)
                    }
                })
                .disposed(by: disposeBag)
        
        refreshRelay.accept(nil)
        
        mineView.tongzhitixingGes.rx.event
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { _ in
                let url = URL(string: UIApplication.openSettingsURLString)!
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url)
                }
            })
            .disposed(by: disposeBag)
    }
}

open class MineController : DDViewController {
    private let mineView = MineView()
    private let disposeBag = DisposeBag()
    private let refreshRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    
    open 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
        
        view.addSubview(mineView)
        mineView.snp.makeConstraints { make in
            make.top.equalTo(CGRectGetHeight(UIApplication.shared.dd_statusBarFrame) + CGRectGetHeight(navigationController?.navigationBar.frame ?? .zero))
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-view.safeAreaInsets.bottom - CGRectGetHeight(tabBarController?.tabBar.frame ?? .zero))
        }
        
        mineView.carInfoView.titleLabel.text = "车辆管理"
        mineView.carInfoView.imageView.image = UIImage(named: "mine_info_car")
        mineView.driverInfoView.titleLabel.text = "师傅管理"
        mineView.driverInfoView.imageView.image = UIImage(named: "mine_info_driver")

        mineView.gongdanduizhang.titleLabel.text = "工单对账"
        mineView.kaipiaotongzhi.titleLabel.text = "开票通知"
        mineView.peixunwendang.titleLabel.text = "培训文档"
        mineView.wendangziliao.titleLabel.text = "文档资料"
        mineView.banbenjiance.titleLabel.text = "版本检测"
        mineView.tongzhitixing.titleLabel.text = "通知提醒"
        
        addActions()
    }
}

open class MineView : DDView {
    private let scrollView : DDScrollView
    private let scrollContentView : DDView
    private let topBackgroundImageView : DDImageView
    public let avatar : DDImageView
    public let accountLabel : DDLabel
    public let companyLabel : DDLabel
    public let carInfoView : MineInfoView
    public let driverInfoView : MineInfoView
    public let infoRadiusView : DDView
    public let infoRadiusSeparate : DDImageView
    public let orderRadiusView : DDView
    public let materialRadiusView : DDView
    public let settingsRadiusView : DDView
    public let gongdanduizhang : MineCell
    public let kaipiaotongzhi : MineCell
    public let peixunwendang : MineCell
    public let wendangziliao : MineCell
    public let banbenjiance : MineCell
    public let tongzhitixingGes : UITapGestureRecognizer
    public let tongzhitixing : MineCell
    public let logoutButton : DDButton
    
    public override init(frame: CGRect) {
        scrollView = DDScrollView()
        scrollContentView = DDView()
        topBackgroundImageView = DDImageView()
        avatar = DDImageView()
        accountLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(15)), textColor: .hex("FFFFFF").alpha(0.8))
        companyLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(12)), textColor: .hex("FFFFFF").alpha(0.5))
        carInfoView = MineInfoView()
        driverInfoView = MineInfoView()
        infoRadiusView = DDView()
        infoRadiusSeparate = DDImageView(image: UIImage(named: "mine_info_separate"))
        orderRadiusView = DDView()
        materialRadiusView = DDView()
        settingsRadiusView = DDView()
        gongdanduizhang = MineCell()
        kaipiaotongzhi = MineCell()
        peixunwendang = MineCell()
        wendangziliao = MineCell()
        banbenjiance = MineCell()
        tongzhitixingGes = UITapGestureRecognizer()
        tongzhitixing = MineCell()
        logoutButton = DDButton.dd_initCustom()
        super.init(frame: frame)
        
        backgroundColor = .hex("F4F5F7")
        
        addSubview(scrollView)
        scrollView.addSubview(scrollContentView)
        
        topBackgroundImageView.backgroundColor = .hex("354683")
        scrollContentView.addSubview(topBackgroundImageView)
        avatar.layer.cornerRadius = auto(27)
        avatar.layer.masksToBounds = true
        scrollContentView.addSubview(avatar)
        scrollContentView.addSubview(accountLabel)
        scrollContentView.addSubview(companyLabel)
        infoRadiusView.backgroundColor = .hex("FFFFFF")
        infoRadiusView.layer.cornerRadius = auto(12)
        scrollContentView.addSubview(infoRadiusView)
        infoRadiusView.addSubview(carInfoView)
        infoRadiusView.addSubview(driverInfoView)
        scrollContentView.addSubview(infoRadiusSeparate)
        orderRadiusView.backgroundColor = .hex("FFFFFF")
        orderRadiusView.layer.cornerRadius = auto(6)
        scrollContentView.addSubview(orderRadiusView)
        materialRadiusView.backgroundColor = .hex("FFFFFF")
        materialRadiusView.layer.cornerRadius = auto(6)
        scrollContentView.addSubview(materialRadiusView)
        settingsRadiusView.backgroundColor = .hex("FFFFFF")
        settingsRadiusView.layer.cornerRadius = auto(6)
        scrollContentView.addSubview(settingsRadiusView)
        orderRadiusView.addSubview(gongdanduizhang)
        kaipiaotongzhi.line.isHidden = true
        orderRadiusView.addSubview(kaipiaotongzhi)
        materialRadiusView.addSubview(peixunwendang)
        wendangziliao.line.isHidden = true
        materialRadiusView.addSubview(wendangziliao)
        settingsRadiusView.addSubview(banbenjiance)
        tongzhitixing.line.isHidden = true
        settingsRadiusView.addSubview(tongzhitixing)
        tongzhitixing.addGestureRecognizer(tongzhitixingGes)
        logoutButton.backgroundColor = .hex("545D78").alpha(0.25)
        logoutButton.layer.cornerRadius = auto(17.5)
        logoutButton.setTitle("退出登录", for: .normal)
        logoutButton.setTitleColor(.white, for: .normal)
        logoutButton.titleLabel?.font = .mediumFont(auto(13))
        scrollContentView.addSubview(logoutButton)
        
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        scrollContentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        topBackgroundImageView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(auto(130))
        }
        
        avatar.snp.makeConstraints { make in
            make.top.equalTo(auto(20))
            make.left.equalTo(auto(25))
            make.width.height.equalTo(auto(54))
        }
        
        accountLabel.snp.makeConstraints { make in
            make.centerY.equalTo(avatar).offset(-auto(10))
            make.left.equalTo(avatar.snp.right).offset(auto(15))
        }
        
        companyLabel.snp.makeConstraints { make in
            make.left.equalTo(avatar.snp.right).offset(auto(15))
            make.centerY.equalTo(avatar).offset(auto(10))
        }
        
        infoRadiusView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(topBackgroundImageView.snp.bottom).offset(-auto(37.5))
            make.height.equalTo(auto(73))
            make.width.equalTo(auto(350))
        }
        
        carInfoView.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        driverInfoView.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        infoRadiusSeparate.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        orderRadiusView.snp.makeConstraints { make in
            make.top.equalTo(infoRadiusView.snp.bottom).offset(auto(10))
            make.width.equalTo(infoRadiusView)
            make.centerX.equalToSuperview()
            make.height.equalTo(auto(110))
        }
        
        materialRadiusView.snp.makeConstraints { make in
            make.top.equalTo(orderRadiusView.snp.bottom).offset(auto(10))
            make.width.equalTo(infoRadiusView)
            make.centerX.equalToSuperview()
            make.height.equalTo(auto(110))
        }
        
        settingsRadiusView.snp.makeConstraints { make in
            make.top.equalTo(materialRadiusView.snp.bottom).offset(auto(10))
            make.width.equalTo(infoRadiusView)
            make.centerX.equalToSuperview()
            make.height.equalTo(auto(110))
        }
        
        gongdanduizhang.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(auto(55))
        }
        
        kaipiaotongzhi.snp.makeConstraints { make in
            make.top.equalTo(gongdanduizhang.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
        
        peixunwendang.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(auto(55))
        }
        
        wendangziliao.snp.makeConstraints { make in
            make.top.equalTo(peixunwendang.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
        
        banbenjiance.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(auto(55))
        }
        
        tongzhitixing.snp.makeConstraints { make in
            make.top.equalTo(banbenjiance.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
        
        logoutButton.snp.makeConstraints { make in
            make.top.equalTo(settingsRadiusView.snp.bottom).offset(auto(20))
            make.bottom.equalToSuperview().offset(-auto(20))
            make.centerX.equalToSuperview()
            make.width.equalTo(auto(110))
            make.height.equalTo(auto(35))
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

open class MineCell : DDView {
    public let titleLabel : DDLabel
    public let arrow : DDImageView
    public let line : DDView
    
    override init(frame: CGRect) {
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(14)), textColor: .hex("323643"))
        arrow = DDImageView(image: UIImage(named: "mine_info_arrow"))
        line = DDView()
        super.init(frame: frame)
        addSubview(titleLabel)
        addSubview(arrow)
        line.backgroundColor = .hex("E9E9EA")
        addSubview(line)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(auto(20))
            make.centerY.equalToSuperview()
        }
        
        arrow.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(-auto(20))
        }
        
        line.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalTo(titleLabel)
            make.right.equalTo(arrow)
            make.height.equalTo(1)
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public class MineInfoView : DDView {
    public let imageView : DDImageView
    public let titleLabel : DDLabel
    public let descLabel : DDLabel
    public let arrow : DDImageView
    public override init(frame: CGRect) {
        imageView = DDImageView()
        titleLabel = DDLabel.dd_init(withText: "", font: .mediumFont(auto(14)), textColor: .hex("203152"))
        descLabel = DDLabel.dd_init(withText: "", font: .regularFont(auto(12)), textColor: .hex("000000").alpha(0.55))
        arrow = DDImageView(image: UIImage(named: "mine_info_arrow"))
        super.init(frame: frame)
        
        addSubview(imageView)
        addSubview(titleLabel)
        addSubview(descLabel)
        addSubview(arrow)
        
        imageView.snp.makeConstraints { make in
            make.left.top.equalTo(auto(20))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(imageView.snp.right).offset(auto(10))
            make.top.equalTo(imageView.snp.top).offset(auto(5))
        }
        
        descLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(auto(5))
        }
        
        arrow.snp.makeConstraints { make in
            make.right.equalTo(-auto(20))
            make.centerY.equalTo(titleLabel)
        }
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
