//
//  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()
    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.
    }

    func getData() {
        viewModel.getAssistList {[weak self] success, error in
            guard let self = self else { return }
            if success {
                if model.id != -1 {
                    dataSource.append(model)
                }
                for item in self.viewModel.arrContactList {
                    dataSource.append(item)
                }
                if dataSource.count != 0 {
                    self.noDataView.isHidden = true
                    self.tableView.isHidden = false
                    self.tableView.reloadData()
                } else {
                    self.noDataView.isHidden = false
                    self.tableView.isHidden = true
                }
            }
        }
    }
    
    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]
        if model.id != -1 && indexPath.row == 0 {
            cell.otherTypeView.isHidden = false
            cell.otherTypeView.image = UIImage(named: "service_my_order")
        } else {
            cell.otherTypeView.isHidden = false
        }
        cell.cellBlock = {[weak self] model in
            guard let self = self else { return }
            if self.backDate != nil {
                self.backDate?(model)
            }
            self.navigationController?.popViewController()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 255
    }
    
    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 orderLabel: UILabel!
    var orderNumLabel: UILabel!
    var phoneLabel: UILabel!
    var phoneNumLabel: UILabel!
    var copyButton: UIButton!
    var phoneCopyButton: UIButton!
    var nameLabel: UILabel!
    var nameValueLabel: UILabel!
    var showDetailButton: UIButton!
    var otherTypeView: UIImageView!
    
    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.height.equalTo(24)
        }
        
        otherTypeView = {
            let view = UIImageView()
            view.image = UIImage(named: "service_other_order")
            view.isHidden = true
            return view
        }()
        centerView.addSubview(otherTypeView)
        otherTypeView.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.left.equalTo(titleLabel.snp.right).offset(8)
            make.height.equalTo(18)
            make.width.equalTo(48)
        }
        
        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(1)
        }
        
        orderLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "合同编号： "
            return label
        }()
        centerView.addSubview(orderLabel)
        orderLabel.snp.makeConstraints { make in
            make.top.equalTo(72.5)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        phoneLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "签约手机号："
            return label
        }()
        centerView.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { make in
            make.top.equalTo(110.5)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        nameLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.textColor = UIColor.mainTextColor.withAlphaComponent(0.5)
            label.text = "签约人姓名："
            return label
        }()
        centerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(149.5)
            make.left.equalTo(16)
            make.height.equalTo(20)
        }
        
        nameValueLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(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(149.5)
            make.right.equalTo(-16)
            make.height.equalTo(20)
        }
        
        orderNumLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(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(72.5)
            make.right.equalTo(-58)
            make.height.equalTo(20)
        }
        
        phoneNumLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(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(110.5)
            make.right.equalTo(-58)
            make.height.equalTo(20)
        }
        
        copyButton = {
            let button = UIButton(type: .custom)
            button.setTitle("复制", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(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(72.5)
            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_M(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(112.5)
            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)
        }
        
        let bottomLineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(bottomLineView)
        bottomLineView.snp.makeConstraints { make in
            make.top.equalTo(197)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        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_M(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 }
        titleLabel.text = model.productName
        orderNumLabel.text = model.orderSn
        phoneNumLabel.text = model.mobile
        nameValueLabel.text = model.username
    }
}
