//
//  YHResignAppointTimeMultipleCell.swift
//  galaxy
//
//  Created by edy on 2024/10/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHResignAppointTimeMultipleCell: UITableViewCell {

    static let cellReuseIdentifier = "YHResignAppointTimeMultipleCell"
    
    var model: YHResignAppointTimeSettingModel = YHResignAppointTimeSettingModel()
    
    var arr:[YHResignAppointMember] = []
    
    // param 选中的用户 是否选中 选中的用户是第几批
    var selectUserBlock: ((_ member: YHResignAppointMember, _ isSelect: Bool, _ groupIndex: Int)->())?
    // switch按钮点击事件
    var switchBlock: ((Bool)->())?
    var refreshBlock: (()->())?

    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let titleLabel = UILabel(frame: CGRect(x: 18, y: 16, width: KScreenWidth, height: 24.0))
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.PFSC_M(ofSize: 17)
        let mustTag: ASAttributedString = .init("* ", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.failColor))
        var title: ASAttributedString = .init("请确认第?批递交信息", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.mainTextColor))
        title = mustTag + title
        titleLabel.attributed.text = title
        return titleLabel
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = UIColor.mainTextColor
        label.text = "选择第?批赴港递交的申请人"
        return label
    }()
    
    lazy var selectBgView: UIView = {
        let groupBgview = UIView()
        groupBgview.backgroundColor = .init(hex: 0xF8F9FB)
        groupBgview.layer.cornerRadius = kCornerRadius3
        groupBgview.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(0)
            make.top.equalTo(14)
            make.bottom.equalTo(-14)
        }
        
        return groupBgview
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 0.0
        layout.minimumLineSpacing = 16.0
        
        let collectView = UICollectionView(frame:.zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .clear
        // 注册自定义单元格
        collectView.register(YHResignAppointApplicantCell.self, forCellWithReuseIdentifier: YHResignAppointApplicantCell.cellReuseIdentifier)
        return collectView
    }()
    
    lazy var submitTimeItemView: YHResignAppointSelectTimeItemView = {
        let view = YHResignAppointSelectTimeItemView(frame: .zero)
        view.title = "预约在港递交时间"
        view.placeHolder = "请选择"
        view.isNeedShowErrorTips = false
        view.errorTips = "请选择在港递交时间"
        view.detail = ""
        view.updateLineMargin(-18.0)
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
            self.selectDetailDate(title: "选择在港递交时间") {
                [weak self] dateStr in
                guard let self = self else { return }
                self.model.ready_to_submit_at = "2024-11-04 14:00"
                self.refreshBlock?()
            }
        }
        return view
    }()
    
    lazy var leaveTimeItemView: YHResignAppointSelectTimeItemView = {
        let view = YHResignAppointSelectTimeItemView(frame: .zero)
        view.title = "预计离港时间"
        view.placeHolder = "请选择"
        view.errorTips = "请选择离港时间"
        view.isNeedShowErrorTips = false
        view.detail = ""
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
            self.selectDetailDate(title: "选择离港时间") {
                [weak self] dateStr in
                guard let self = self else { return }
                self.model.leave_hk_at = "2024-12-04 17:00"
                self.refreshBlock?()
            }
        }
        return view
    }()
    
    lazy var leaveHKSwithView: YHResignLeaveHKSwitchItemView = {
        let view = YHResignLeaveHKSwitchItemView()
        view.title = "暂不离港"
        view.selectBlock = {
            [weak self] on in
            guard let self = self else { return }
            self.switchBlock?(on)
        }
        return view
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func updateModel(_ model: YHResignAppointTimeSettingModel) {
        
        self.model = model
        
        let mustTag: ASAttributedString = .init("* ", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.failColor))
        var title: ASAttributedString = .init("请确认第\(String.convertNumberToChineseText(model.itemIndex+1))批赴港递交信息", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.mainTextColor))
        title = mustTag + title
        titleLabel.attributed.text = title
        subTitleLabel.text =  "选择第\(String.convertNumberToChineseText(model.itemIndex+1))批赴港递交的申请人"
        self.leaveHKSwithView.switchBtn.setOn(self.model.notleaveHK, animated: false)

        self.arr.removeAll()
        self.arr.append(contentsOf: model.users)
        
        // 预计离港时间控件显示逻辑
        let isHiddenLeaveHKTime = self.model.notleaveHK
        
        // 时间控件显示
        submitTimeItemView.detail = model.getSubmitHKTime()
        leaveTimeItemView.detail = model.getLeaveHKTime()
        
        // 时间控件红色提示显示
        submitTimeItemView.isNeedShowErrorTips = (model.isClickSubmit && model.ready_to_submit_at.isEmpty)
        leaveTimeItemView.isNeedShowErrorTips = (model.isClickSubmit && model.leave_hk_at.isEmpty)
                
        leaveTimeItemView.removeFromSuperview()
        leaveTimeItemView.snp.removeConstraints()
        
        if isHiddenLeaveHKTime {
            leaveHKSwithView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(submitTimeItemView.snp.bottom)
                make.bottom.equalToSuperview()
            }
            
        } else {
            
            whiteContentView.addSubview(leaveTimeItemView)
            leaveTimeItemView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(submitTimeItemView.snp.bottom)
            }
            
            leaveHKSwithView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(leaveTimeItemView.snp.bottom)
                make.bottom.equalToSuperview()
            }
        }
        
        // 申请人选择列表高度显示
        collectionView.reloadData()
        collectionView.snp.updateConstraints { make in
            make.height.equalTo(self.getCollectionViewHeight())
        }
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    
    func selectDetailDate(title: String, selectBlock:((_ dateStr: String)->())?) {
        YHDatePickView.show(type: .yyyymmdd, title:title, lastIsTaday: false, currentDay:"") {
            [weak self] dateStr in
            guard let self = self else { return }
            selectBlock?(dateStr)
        }
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(lineView)
        whiteContentView.addSubview(subTitleLabel)
        whiteContentView.addSubview(selectBgView)
        whiteContentView.addSubview(submitTimeItemView)
        whiteContentView.addSubview(leaveTimeItemView)
        whiteContentView.addSubview(leaveHKSwithView)

        whiteContentView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(-16)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(16)
            make.height.equalTo(24)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.height.equalTo(0.5)
        }
        
        subTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(lineView.snp.bottom).offset(16)
        }
        
        selectBgView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(subTitleLabel.snp.bottom).offset(12)
        }
        
        submitTimeItemView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(selectBgView.snp.bottom).offset(16)
        }
        
        leaveTimeItemView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(submitTimeItemView.snp.bottom)
        }
        
        leaveHKSwithView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(leaveTimeItemView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
    
    func getCollectionViewHeight() -> CGFloat {
        
        let rowHeight = 20.0
        let gap = 16.0
        var rowCount = arr.count/3
        if arr.count%3 != 0 {
            rowCount += 1
        }
        var height = 0.0
        if rowCount > 0 {
            height = rowHeight * Double(rowCount) + gap * Double(rowCount-1)
        }
        return height
    }
}

extension YHResignAppointTimeMultipleCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout  {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return arr.count
        }
        
        // 返回每个单元格的大小
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            let listWidth = KScreenWidth-(14.0+18.0+16.0)*2.0
            return CGSize(width: floorl(listWidth/3.0), height: 20)
        }
        
        // 返回自定义单元格
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHResignAppointApplicantCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointApplicantCell
            if 0 <= indexPath.item && indexPath.item < arr.count {
                let applicant = arr[indexPath.item]
                cell.updateApplicantInfo(applicant)
            }
            return cell
        }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if 0 <= indexPath.item && indexPath.item < arr.count {
            let member = arr[indexPath.item]
            let selectArr = arr.filter {
                return $0.isSelected == true
            }
            if selectArr.count == 1, member.isSelected == true, member.id == selectArr[0].id {
                // 分组中仅有一个选中用户 且点击的是该用户
                YHHUD.flash(message: "每一批赴港申请人不可为空，请确保每位申请人都在列")
                return
            }
            selectUserBlock?(member, !member.isSelected, self.model.itemIndex)
        }
    }
}
