//
//  YHOrderDetailViewController.swift
//  galaxy
//
//  Created by EDY on 2024/4/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHOrderDetailViewController: YHBaseViewController {
    var backDate: ((YHContactItemModel) -> Void)?
    var model: YHContactItemModel = YHContactItemModel()
    var tableView: UITableView!
    var viewModel: YHServiceOrderSearchViewModel = YHServiceOrderSearchViewModel()
    let serviceCenterMainReqVM : YHServiceCenterViewModel = YHServiceCenterViewModel()
    var dataSource: [YHContactItemModel] = []
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无", kEmptyCommonBgName)
        view.backgroundColor = .clear
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getWhiteList()
        getData()
        // Do any additional setup after loading the view.
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController?.setNeedsStatusBarAppearanceUpdate()
        
        let orientation = UIInterfaceOrientation.landscapeLeft
        UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
    }

    func getData() {
        serviceCenterMainReqVM.getContactList {[weak self] success, error in
            guard let self = self else { return }
            if success == true {
                dataSource = serviceCenterMainReqVM.arrContactList
                viewModel.getAssistList {[weak self] success, error in
                    guard let self = self else { return }
                    if success {
                        for item in self.viewModel.arrContactList {
                            var model = item
                            model.isOther = true
                            dataSource.append(model)
                        }
                        if dataSource.count != 0 {
                            self.noDataView.isHidden = true
                            self.tableView.isHidden = false
                            self.tableView.reloadData()
                        } else {
                            self.noDataView.isHidden = false
                            self.tableView.isHidden = true
                        }
                    }
                }
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "请求出错")
            }
        }
    }
    
    func getWhiteList() {
        viewModel.getWhitelist {[weak self] success, error in
            guard let self = self else { return }
            if success {
                let searchButton = {
                    let button = UIButton(type: .custom)
                    button.frame = CGRect(x: 0, y: 0, width: 81, height: 21)
                    button.setImage(UIImage(named: "service_detail_search"), for: .normal)
                    button.setTitleColor(UIColor.mainTextColor, for: .normal)
                    button.setTitle("订单搜索", for: .normal)
                    button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
                    button.contentHorizontalAlignment = .right
                    button.addTarget(self, action: #selector(self.searchButtonClick), for: .touchUpInside)
                    button.isSelected = false
                    button.iconInLeft(spacing: 4)
                    return button
                }()
                let rightButtonItem =  UIBarButtonItem(customView: searchButton)
                gk_navRightBarButtonItem = rightButtonItem
                gk_navItemRightSpace = 16
            }
        }
    }
    
    @objc func searchButtonClick() {
        let vc = YHOrderSearchViewController()
        vc.mobile = model.mobile
        self.navigationController?.pushViewController(vc)
    }
    
    func setView() {
        gk_navTitle = "服务进度"
        gk_navBackgroundColor = UIColor.white
        gk_navBarAlpha = 1
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHOrderDetailTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.bottom.equalTo(view)
        }
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(150)
        }
    }

}

extension YHOrderDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHOrderDetailTableViewCell.self)
        cell.dataSource = dataSource[indexPath.row]
        cell.cellBlock = {[weak self] model in
            guard let self = self else { return }
            if model.status == 3 {
                YHServiceOrderInIncubationView.show {
                    if self.backDate != nil {
                        self.backDate?(model)
                    }
                    self.navigationController?.popViewController()
                }
                return
            }
            if self.backDate != nil {
                self.backDate?(model)
            }
            self.navigationController?.popViewController()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 305
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

class YHOrderDetailTableViewCell: UITableViewCell {
    typealias CellBlock = (YHContactItemModel) -> ()
    var cellBlock: CellBlock?
    var centerView: UIView!
    var titleLabel: UILabel!
    var lineView: UIView!
    var orderTitleLabel: UILabel!
    var orderTitleNumLabel: UILabel!
    var orderLabel: UILabel!
    var orderNumLabel: UILabel!
    var phoneLabel: UILabel!
    var phoneNumLabel: UILabel!
    var copyButton: UIButton!
    var phoneCopyButton: UIButton!
    var nameLabel: UILabel!
    var nameValueLabel: UILabel!
    var serviceLabel: UILabel!
    var serviceValueLabel: UILabel!
    var showDetailButton: UIButton!
    var otherTypeView: UILabel!
    var bottomLineView: UIView!
    var dataSource: YHContactItemModel? {
        didSet {
            updateAllViews()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius8
            view.masksToBounds = true
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8)
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
//            label.text = model.productName
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(18)
            make.left.equalTo(16)
            make.right.equalTo(-80)
            make.height.equalTo(24)
        }
        
        otherTypeView = {
            let view = UILabel()
            view.text = "进行中"
            view.backgroundColor = UIColor(hex: 0xf0f4fb)
            view.textColor = UIColor.brandMainColor
            view.textAlignment = .center
            view.font = UIFont.PFSC_M(ofSize: 12)
            view.layer.cornerRadius = 2
            return view
        }()
        centerView.addSubview(otherTypeView)
        otherTypeView.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.right.equalTo(-16)
            make.height.equalTo(24)
            make.width.equalTo(52)
        }
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.equalTo(54.5)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(0.5)
        }
        orderTitleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "订单类型： "
            return label
        }()
        centerView.addSubview(orderTitleLabel)
        orderTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(72)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        orderTitleNumLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
//            label.text = model.orderSn
            label.textAlignment = .right
            return label
        }()
        centerView.addSubview(orderTitleNumLabel)
        orderTitleNumLabel.snp.makeConstraints { make in
            make.top.equalTo(72)
            make.right.equalTo(-16)
            make.height.equalTo(20)
        }
        
        orderLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "合同编号： "
            return label
        }()
        centerView.addSubview(orderLabel)
        orderLabel.snp.makeConstraints { make in
            make.top.equalTo(104)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        phoneLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "签约手机号："
            return label
        }()
        centerView.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { make in
            make.top.equalTo(136)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        nameLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "签约人姓名："
            return label
        }()
        centerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(168)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        nameValueLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
//            label.text = model.orderSn
            label.textAlignment = .right
            return label
        }()
        centerView.addSubview(nameValueLabel)
        nameValueLabel.snp.makeConstraints { make in
            make.top.equalTo(168)
            make.right.equalTo(-16)
            make.height.equalTo(20)
        }
        
        orderNumLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
//            label.text = model.orderSn
            label.textAlignment = .right
            return label
        }()
        centerView.addSubview(orderNumLabel)
        orderNumLabel.snp.makeConstraints { make in
            make.top.equalTo(104)
            make.right.equalTo(-58)
            make.height.equalTo(20)
        }
        
        phoneNumLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
//            label.text = model.mobile
            label.textAlignment = .right
            return label
        }()
        centerView.addSubview(phoneNumLabel)
        phoneNumLabel.snp.makeConstraints { make in
            make.top.equalTo(136)
            make.right.equalTo(-58)
            make.height.equalTo(20)
        }
        
        copyButton = {
            let button = UIButton(type: .custom)
            button.setTitle("复制", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            button.setTitleColor(UIColor.brandMainColor, for: .normal)
            button.addTarget(self, action: #selector(copyButtonClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(copyButton)
        copyButton.snp.makeConstraints { make in
            make.top.equalTo(104)
            make.right.equalTo(-16)
            make.height.equalTo(18)
            make.width.equalTo(26)
        }
        
        phoneCopyButton = {
            let button = UIButton(type: .custom)
            button.setTitle("复制", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            button.setTitleColor(UIColor.brandMainColor, for: .normal)
            button.addTarget(self, action: #selector(phoneCopyButtonClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(phoneCopyButton)
        phoneCopyButton.snp.makeConstraints { make in
            make.top.equalTo(136)
            make.right.equalTo(-16)
            make.height.equalTo(18)
            make.width.equalTo(26)
        }
        
        let subLineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(subLineView)
        subLineView.snp.makeConstraints { make in
            make.centerY.equalTo(copyButton.snp.centerY)
            make.right.equalTo(-50)
            make.width.equalTo(1)
            make.height.equalTo(6)
        }
        
        let subLine1View = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(subLine1View)
        subLine1View.snp.makeConstraints { make in
            make.centerY.equalTo(phoneCopyButton.snp.centerY)
            make.right.equalTo(-50)
            make.width.equalTo(1)
            make.height.equalTo(6)
        }
        
        bottomLineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(bottomLineView)
        bottomLineView.snp.makeConstraints { make in
            make.bottom.equalTo(-52)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        serviceLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "服务内容"
            return label
        }()
        centerView.addSubview(serviceLabel)
        serviceLabel.snp.makeConstraints { make in
            make.top.equalTo(200)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        serviceValueLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
//            label.text = model.orderSn
            label.textAlignment = .right
            return label
        }()
        centerView.addSubview(serviceValueLabel)
        serviceValueLabel.snp.makeConstraints { make in
            make.top.equalTo(200)
            make.right.equalTo(-16)
            make.left.equalTo(serviceLabel.snp.right).offset(20)
        }
        
        showDetailButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "service_right_icon"), for: .normal)
            button.setTitleColor(UIColor.brandMainColor, for: .normal)
            button.setTitle("查看详情", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
            button.contentHorizontalAlignment = .right
            button.addTarget(self, action: #selector(showDetailClick), for: .touchUpInside)
            button.isSelected = false
            return button
        }()
        centerView.addSubview(showDetailButton)
        showDetailButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(52)
            make.width.equalTo(76)
        }
        showDetailButton.iconInRight(with: 2)
    }
    
    @objc func copyButtonClick() {
        let textToCopy = orderNumLabel.text
        UIPasteboard.general.string = textToCopy
        YHHUD.flash(message: "复制成功")
    }
    @objc func phoneCopyButtonClick() {
        let textToCopy = phoneNumLabel.text
        UIPasteboard.general.string = textToCopy
        YHHUD.flash(message: "复制成功")
    }
    
    @objc func showDetailClick() {
        guard let model = dataSource else { return }
        if let block = cellBlock {
            block(model)
        }
    }
    
    func updateAllViews() {
        guard let model = dataSource else { return }
        bottomLineView.isHidden = false
        showDetailButton.isHidden = false
        if model.status == 0 {
            otherTypeView.text = "进行中"
            otherTypeView.backgroundColor = UIColor(hex: 0xf0f4fb)
            otherTypeView.textColor = UIColor.brandMainColor
        }
        if model.status == 1 {
            otherTypeView.text = "退款中"
            otherTypeView.backgroundColor = UIColor.failColor.withAlphaComponent(0.3)
            otherTypeView.textColor = UIColor.failColor
        }
        if model.status == 2 {
            otherTypeView.text = "已完成"
            otherTypeView.backgroundColor = UIColor(hex:0xf0fbf7)
            otherTypeView.textColor = UIColor(hex:0x3cc694)
            bottomLineView.isHidden = true
            showDetailButton.isHidden = true
        }
        if model.status == 3 {
            otherTypeView.text = "孵化中"
            otherTypeView.backgroundColor = UIColor(hex:0xfff5eb)
            otherTypeView.textColor = UIColor(hex:0xff8000)
        }
        titleLabel.text = model.productName
        orderNumLabel.text = model.orderSn
        var title = "主申订单"
        if model.isOther {
            title = "协作订单"
        }
        orderTitleNumLabel.text = title
        phoneNumLabel.text = model.mobile
        nameValueLabel.text = model.username
        serviceValueLabel.text = model.service_name
    }
}
