//
//  YHInvitationWithGiftsSelectItemView.swift
//  galaxy
//
//  Created by EDY on 2024/8/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHInvitationWithGiftsSelectItemView: UIView {
    var backDate: ((Int,Int,String,String) -> Void)?
    var centerView: UIView!
    var titleLabel: UILabel!
    var closeButton: UIButton!
    var resetButton: UIButton!
    var sureButton: UIButton!
    var lineView: UIView!
    var tableView: UITableView!
    var selectOne: Int?
    var selectTwo: Int?
    var startTime: String = ""
    var endTime: String = ""
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(484)
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            label.text = "筛选"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.height.equalTo(24)
            make.width.equalTo(200)
            make.centerX.equalToSuperview()
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.width.equalTo(24)
            make.top.equalTo(16)
        }
        resetButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("重置", for: .normal)
            button.setTitleColor(UIColor(hex: 0x222222), for: .normal)
            button.backgroundColor = UIColor.contentBkgColor
            button.layer.cornerRadius = 3
            button.addTarget(self, action: #selector(reset), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(resetButton)
        resetButton.snp.makeConstraints { make in
            make.width.equalTo(86)
            make.height.equalTo(44)
            make.left.equalTo(16)
            make.bottom.equalTo(-46)
        }
        
        sureButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确定", for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor = UIColor.brandMainColor
            button.layer.cornerRadius = 3
            button.addTarget(self, action: #selector(sure), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(sureButton)
        sureButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.height.equalTo(44)
            make.left.equalTo(112)
            make.bottom.equalTo(-46)
        }
                
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHInvitationWithGiftsSelectItemCell.self)
            return tableView
        }()
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom)
            make.bottom.equalTo(-98)
            make.left.right.equalToSuperview()
        }
        
        centerView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(8, 8))
        let layer = CAShapeLayer()
        layer.frame = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        print("处理点击手势")
        dismiss()
    }
    
    static func show(selectOne: Int = 100, selectTwo: Int = 100, startTime: String = "", endTime: String = "",callBack: @escaping ((Int,Int,String,String) -> Void)) {
        let view = YHInvitationWithGiftsSelectItemView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.backDate = callBack
        view.selectOne = selectOne
        view.selectTwo = selectTwo
        view.startTime = startTime
        view.endTime = endTime
        view.tableView.reloadData()
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func sure() {
        if selectOne == 3 {
            if startTime.count == 0 {
                YHHUD.flash(message: "请选择开始时间")
                return
            }
            if endTime.count == 0 {
                YHHUD.flash(message: "请选择截止时间")
                return
            }
        }
        if let block = backDate {
            block(selectOne ?? 100,selectTwo ?? 100,startTime,endTime)
        }
        dismiss()
    }
    
    @objc func reset() {
        self.selectOne = 100
        self.selectTwo = 100
        self.startTime = ""
        self.endTime = ""
        self.tableView.reloadData()
    }
}

extension YHInvitationWithGiftsSelectItemView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer:UIGestureRecognizer, shouldReceive touch:UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHInvitationWithGiftsSelectItemView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHInvitationWithGiftsSelectItemCell.self)
        if indexPath.section == 0 {
            cell.selectIndex = selectOne
            cell.dataSource = ["近一个月", "近半年", "近一年", "自定义"]
            cell.startTime = startTime
            cell.endTime = endTime
        } else {
            cell.selectIndex = selectTwo
            cell.dataSource = ["已签约", "已测评", "已注册"]
        }
        cell.block = {[weak self] index in
            if indexPath.section == 0 {
                self?.selectOne = index
                self?.tableView.reloadData()
            } else {
                self?.selectTwo = index
            }
        }
        cell.timeBlock = { [weak self] tag in
            self?.isHidden = true
            var title = "选择开始日期"
            var time = self?.startTime
            if tag == 1 {
                title = "选择开始日期"
                time = self?.startTime ?? ""
            } else {
                title = "选择截止日期"
                time = self?.endTime ?? ""
            }
            YHDatePickView.show(type: .yyyymmdd, title: title, lastIsTaday: true, currentDay: time ?? "") { date in
                if tag == 1 {
                    self?.startTime = date
                } else {
                    self?.endTime = date
                }
                self?.isHidden = false
                self?.tableView.reloadData()
            } dismiss: {
                self?.isHidden = false
            }
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if selectOne == 3, indexPath.section == 0 {
            return 154
        }
        return 62
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 40))
        let label = UILabel(frame: CGRect(x: 20, y: 20, width: 200, height: 20))
        if section == 0 {
            label.text = "注册时间"
        } else {
            label.text = "状态"
        }
        label.textColor = UIColor(hex: 0x222222)
        label.font = UIFont.PFSC_M(ofSize: 14)
        view.addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

class YHInvitationWithGiftsSelectItemCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHInvitationWithGiftsSelectItemCell"
    typealias Block = (Int) -> ()
    var block: Block?
    var timeBlock: Block?
    var centerView: UIView!
    var timeView: YHInvitationWithGiftsSelectTimeView!
    var startTime: String? {
        didSet {
            if startTime?.count != 0 {
                timeView.valueOneLabel.text = startTime
            }
        }
    }
    var endTime: String? {
        didSet {
            if endTime?.count != 0 {
                timeView.valueTwoLabel.text = endTime
            }
        }
    }
    var selectIndex: Int? {
        didSet {
            if selectIndex == 3 {
                timeView.isHidden = false
            } else {
                timeView.isHidden = true
            }
        }
    }
    var dataSource: [String]? {
        didSet {
            updateViews()
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    
    func setupUI() {
        
        self.selectionStyle = .none
        contentView.backgroundColor = .white
        
        centerView = {
            let view = UIView()
            return view
        }()
        contentView.addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(66)
        }

        timeView = {
            let view = YHInvitationWithGiftsSelectTimeView()
            view.block = { [weak self] tag in
                guard let self = self else { return }
                if let block = timeBlock {
                    block(tag)
                }
            }
            view.isHidden = true
            return view
        }()
        contentView.addSubview(timeView)
        timeView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(66)
            make.height.equalTo(88)
        }

    }
    
    func updateViews() {
        guard let data = dataSource else { return }
        centerView.removeSubviews()
        let width = (KScreenWidth - 78)/4.0
        var x = 21
        var index = 0
        for item in data {
            let button = UIButton(type: .custom)
            button.setTitle(item, for: .normal)
            button.setTitleColor(UIColor(hex: 0x222222), for: .normal)
            button.setTitleColor(UIColor.brandMainColor, for: .selected)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
            button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
            button.setBackgroundColor(color: UIColor.tipsColor.withAlphaComponent(0.08), forState: .selected)
            button.layer.cornerRadius = kCornerRadius3
            button.layer.borderWidth = 0
            button.layer.borderColor = UIColor.brandMainColor.cgColor
            button.layer.masksToBounds = true
            button.tag = 1000 + index
            if index == selectIndex {
                button.isSelected = true
                button.layer.borderWidth = 1
            }
            button.addTarget(self, action: #selector(click(sender:)), for: .touchUpInside)
            centerView.addSubview(button)
            button.snp.makeConstraints { make in
                make.left.equalTo(x)
                make.height.equalTo(36)
                make.width.equalTo(width)
                make.top.equalTo(16)
            }
            x = x + Int(width) + 12
            index = index + 1
        }
    }
    
    @objc func click(sender: UIButton) {
        if selectIndex == sender.tag - 1000 {
            sender.isSelected = false
            sender.layer.borderWidth = 0
            if let block = block {
                block(100)
            }
            return
        }
        guard let data = dataSource else { return }
        for i in 0..<data.count {
            let button = centerView.viewWithTag(1000+i) as! UIButton
            if sender.tag == 1000 + i {
                button.isSelected = true
                button.layer.borderWidth = 1
            } else {
                button.isSelected = false
                button.layer.borderWidth = 0
            }
        }
        selectIndex = sender.tag - 1000
        if let block = block {
            block(sender.tag - 1000)
        }
    }
}

class YHInvitationWithGiftsSelectTimeView: UIView {
    typealias Block = (Int) -> ()
    var block: Block?
    var titleOneLabel: UILabel!
    var valueOneLabel: UILabel!
    var titleTwoLabel: UILabel!
    var valueTwoLabel: UILabel!
    var oneImageView: UIImageView!
    var twoImageView: UIImageView!
    var lineView: UIView!
    var oneButton: UIButton!
    var twoButton: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor.contentBkgColor
        layer.cornerRadius = kCornerRadius3
        titleOneLabel = {
            let label = UILabel()
            label.text = "开始日期"
            label.font = UIFont.PFSC_M(ofSize: 13)
            label.textColor = UIColor.mainTextColor70
            return label
        }()
        addSubview(titleOneLabel)
        titleOneLabel.snp.makeConstraints { make in
            make.left.equalTo(11)
            make.top.equalTo(12)
            make.height.equalTo(20)
            make.width.equalTo(100)
        }
        
        titleTwoLabel = {
            let label = UILabel()
            label.text = "截止日期"
            label.font = UIFont.PFSC_M(ofSize: 13)
            label.textColor = UIColor.mainTextColor70
            return label
        }()
        addSubview(titleTwoLabel)
        titleTwoLabel.snp.makeConstraints { make in
            make.left.equalTo(11)
            make.bottom.equalTo(-12)
            make.height.equalTo(20)
            make.width.equalTo(100)
        }
        
        valueOneLabel = {
            let label = UILabel()
            label.text = "选择开始日期"
            label.font = UIFont.PFSC_M(ofSize: 13)
            label.textColor = UIColor.mainTextColor70
            label.textAlignment = .right
            return label
        }()
        addSubview(valueOneLabel)
        valueOneLabel.snp.makeConstraints { make in
            make.right.equalTo(-33)
            make.top.equalTo(12)
            make.height.equalTo(20)
            make.width.equalTo(100)
        }
        
        valueTwoLabel = {
            let label = UILabel()
            label.text = "选择截止日期"
            label.font = UIFont.PFSC_M(ofSize: 13)
            label.textColor = UIColor.mainTextColor70
            label.textAlignment = .right
            return label
        }()
        addSubview(valueTwoLabel)
        valueTwoLabel.snp.makeConstraints { make in
            make.right.equalTo(-33)
            make.bottom.equalTo(-12)
            make.height.equalTo(20)
            make.width.equalTo(100)
        }
        
        oneImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "form_right_arrow")
            return imageView
        }()
        addSubview(oneImageView)
        oneImageView.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.top.equalTo(12)
            make.right.equalTo(-12)
        }
        
        twoImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "form_right_arrow")
            return imageView
        }()
        addSubview(twoImageView)
        twoImageView.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.bottom.equalTo(-12)
            make.right.equalTo(-12)
        }
        
        oneButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(start), for: .touchUpInside)
            return button
        }()
        addSubview(oneButton)
        oneButton.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.top.equalTo(12)
            make.right.equalTo(-12)
            make.width.equalTo(150)
        }
        
        twoButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(end), for: .touchUpInside)
            return button
        }()
        addSubview(twoButton)
        twoButton.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.bottom.equalTo(-12)
            make.right.equalTo(-12)
            make.width.equalTo(150)
        }
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor(hex: 0xf0f0f0)
            return view
        }()
        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.height.equalTo(1)
            make.left.equalTo(12)
            make.right.equalTo(-12)
        }
        
    }
    
    @objc func start() {
        if let block = block {
            block(1)
        }
    }
    
    @objc func end() {
        if let block = block {
            block(2)
        }
    }
}
