//
//  TWSheetPicker.swift
//  VattiCSS
//
//  Created by fishxiaou on 2023/8/24.
//

import UIKit
import SnapKit

class TWSheetPicker: UIViewController, UIGestureRecognizerDelegate {
    
    // 数据
    var dataList = [(String,String)]()
    var isSingle = true
    var call:(([Int])->())?
    var cancelCall:(()->())?
    var selIndexArr = [Int]()
    
    lazy var view_main: UIView = {
        let v = UIView(frame: CGRect.zero)
        v.backgroundColor = UIColor.white
        v.layer.masksToBounds = true
        return v
    }()
    
    lazy var lab_title: UILabel = {
        let l = UILabel(frame: CGRect.zero)
        l.textAlignment = .center
        l.text = "请选择".languageString()
        l.font = UIFont.boldSystemFont(ofSize: 16)
        return l
    }()
    
    lazy var btn_submit: UIButton = {
        let b = UIButton(type: .custom)
        b.setTitle("确定".languageString(), for: .normal)
        b.setTitleColor(UIColor.white, for: .normal)
        b.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        b.backgroundColor = KMainColour
        b.addTarget(self, action: #selector(submitAction(send:)), for: .touchUpInside)
        b.makeLayerRadius(value: 20)
        return b
    }()
    
    lazy var maskBtn:UIButton = {
        let b = UIButton(type: .custom)
        b.backgroundColor = .clear
        b.addTarget(self, action: #selector(maskCancelAction(send:)), for: .touchUpInside)
        return b
    }()
    
    lazy var tableView_picker: UITableView = {
        let tb = UITableView(frame: CGRect.zero, style: .grouped)
        tb.backgroundColor = UIColor.white
        tb.separatorStyle = .none
        tb.showsHorizontalScrollIndicator = false
        tb.showsVerticalScrollIndicator = false
        //        tb.bounces = false
        return tb
    }()
    
    // 显示
    class func showActionSheet(titleStr:String, singleType:Bool, dataArr:[(String,String)], action:@escaping (([Int])->())) -> TWSheetPicker  {
        let curView = TWSheetPicker(nibName: nil, bundle: nil)
        curView.lab_title.text = titleStr
        curView.dataList = dataArr
        curView.isSingle = singleType
        curView.call = action
        return curView
    }
    // 显示
    func config(cancelAction:(()->())?) -> TWSheetPicker {
        self.cancelCall = cancelAction
        return self
    }
    
    func show(_ from:UIViewController) {
        self.modalPresentationStyle = .overFullScreen
        self.modalTransitionStyle = .crossDissolve
        from.present(self, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView_picker.reloadData()
        animateShow()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    func configUI() {
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        view.addSubview(maskBtn)
        maskBtn.snp.makeConstraints {
            $0.top.left.right.equalToSuperview()
            $0.height.equalTo(SCREEN_H-365)
        }
        
        let bgView = UIView(frame: CGRect.zero)
        bgView.backgroundColor = UIColor.white
        view.addSubview(bgView)
        bgView.snp.makeConstraints {
            $0.left.right.bottom.equalToSuperview()
            $0.height.equalTo(50)
        }
        
        view.addSubview(view_main)
        
        view_main.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                $0.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(365)
            } else {
                $0.bottom.equalToSuperview().offset(365)
            }
            $0.height.equalTo(365)
        }
        
        view_main.addSubview(btn_submit)
        btn_submit.snp.makeConstraints {
            $0.bottom.equalToSuperview().offset(-20)
            $0.left.equalToSuperview().offset(16)
            $0.right.equalToSuperview().offset(-16)
            $0.height.equalTo(40)
        }
        
        view_main.addSubview(lab_title)
        lab_title.snp.makeConstraints {
            $0.top.left.right.equalToSuperview()
            $0.height.equalTo(48)
        }
        
        let closeB = UIButton(frame: CGRect.zero)
        closeB.setImage(UIImage(named: "icon_close"), for: .normal)
        closeB.addTarget(self, action: #selector(self.closeAction(send:)), for: .touchUpInside)
        view_main.addSubview(closeB)
        
        closeB.snp.makeConstraints {
            $0.height.width.equalTo(22)
            $0.right.equalToSuperview().offset(-12)
            $0.centerY.equalTo(lab_title)
        }
        
        tableView_picker.delegate = self
        tableView_picker.dataSource = self
        view.addSubview(tableView_picker)
        
        tableView_picker.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.top.equalTo(lab_title.snp.bottom)
            $0.bottom.equalTo(btn_submit.snp.top).offset(-10)
        }
        self.view.layoutIfNeeded()
    }
    
    @objc func closeAction(send: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func submitAction(send: UIButton) {
        if selIndexArr.isEmpty {
            cancelCall?()
        }else{
            call?(selIndexArr)
        }
        dismiss(animated: true, completion: nil)
    }
    
    @objc func maskCancelAction(send: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    func animateShow()  {
        UIView.animate(withDuration: 0.5, delay: 0, options: UIView.AnimationOptions.allowAnimatedContent, animations: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.view_main.snp.updateConstraints {(make) in
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(weakSelf.view.safeAreaLayoutGuide.snp.bottom)
                } else {
                    make.bottom.equalToSuperview()
                }
            }
            weakSelf.view.layoutIfNeeded()
        }) { [weak self] _ in
            self?.view_main.addCorner(conrners: [.topLeft,.topRight], radius: 8)
        }
    }
    
}

extension TWSheetPicker: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "TSOrderActionsheetCell") as? TSOrderActionsheetCell
        if cell == nil {
            cell = TSOrderActionsheetCell(style: .default, reuseIdentifier: "TSOrderActionsheetCell")
        }
        let model = dataList[indexPath.row]
        cell?.lab_title.text = model.0
        cell?.lab_info.text = model.1
        cell?.lab_info.isHidden = model.1.isEmpty
        if isSingle {
            cell?.view_check.image = UIImage(named: "icon_mark")
            let hasSel = selIndexArr.contains(indexPath.row)
            cell?.view_check.isHidden = !hasSel
            cell?.lab_title.textColor = hasSel ? KMainColour : UIColor(hexString: "#2D3132")
        }else{
            cell?.view_check.isHidden = false
            if selIndexArr.contains(indexPath.row) {
                cell?.view_check.image = UIImage(named: "icon_circle_sel")
                cell?.lab_title.textColor = KMainColour
            }else{
                cell?.view_check.image = UIImage(named: "icon_circle")
                cell?.lab_title.textColor = UIColor(hexString: "#2D3132")
            }
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let theInex = selIndexArr.firstIndex(of: indexPath.row) {
            selIndexArr.remove(at: theInex)
        }else{
            if isSingle {
                selIndexArr = [indexPath.row]
            }else{
                selIndexArr.append(indexPath.row)
            }
        }
        tableView.reloadData()
    }
    
}


class TSOrderActionsheetCell: UITableViewCell {
    
    lazy var view_main: UIStackView = {
        let s = UIStackView()
        s.axis = .vertical
        s.spacing = 8
        return s
    }()
    
    lazy var lab_title: UILabel = {
        let l = UILabel(frame: CGRect.zero)
        l.textAlignment = .left
        l.numberOfLines = 0
        l.font = UIFont.systemFont(ofSize: 14)
        return l
    }()
    
    lazy var lab_info: UILabel = {
        let l = UILabel(frame: CGRect.zero)
        l.textAlignment = .left
        l.font = UIFont.systemFont(ofSize: 13)
        return l
    }()
    
    lazy var view_check: UIImageView = {
        let i = UIImageView(frame: CGRect.zero)
        return i
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        configUI()
    }
    
    func configUI() {
        selectionStyle = .none
        contentView.addSubview(view_check)
        view_check.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.right.equalToSuperview().offset(-15)
            $0.width.height.equalTo(20)
        }
        
        contentView.addSubview(view_main)
        view_main.snp.makeConstraints {
            $0.top.equalToSuperview().offset(10)
            $0.left.equalToSuperview().offset(15)
            $0.right.equalTo(view_check.snp.left).offset(-10)
            $0.bottom.equalToSuperview().offset(-10)
        }
        
        view_main.addArrangedSubview(lab_title)
        lab_title.snp.makeConstraints {
            $0.height.greaterThanOrEqualTo(20)
        }
        
        view_main.addArrangedSubview(lab_info)
        lab_info.snp.makeConstraints {
            $0.height.equalTo(18)
        }
        
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
    }
    
}


