//
//  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 renewalId: Int = 0
    let viewModel = YHResignAppointViewModel()

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

    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(YHResignSelectApplicantCollectCell.self, forCellWithReuseIdentifier: YHResignSelectApplicantCollectCell.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.getDateInfo { [weak self] startDate, endDate in
                guard let self = self else { return }
                let view = YHRangeDatePickerSheetView2.sheetView()
                view.viewTitle = "选择预约在港递交时间"
                view.minDateStr = startDate
                view.maxDateStr = endDate
                view.block = {
                    [weak self] (selectDateStr, hourTime) in
                    guard let self = self else { return }
                    let selectTimeStr = "\(selectDateStr) \(hourTime)"
                    printLog("\(selectTimeStr)")
                    // 选择在港递交时间
                    if self.model.leave_hk_at.isEmpty {
                        self.model.ready_to_submit_at = selectTimeStr
                    } else {
                        if !self.model.notleaveHK { // 离港才比较日期
                            if self.compareDates(selectTimeStr, self.model.leave_hk_at) != .small {
                                // selectTimeStr >= leave_hk_at
                                YHHUD.flash(message: "预约在港递交时间必须早于预计离港时间")
                                return
                            }
                        }
                        self.model.ready_to_submit_at = selectTimeStr
                    }
                    self.refreshBlock?()
                }
                view.show()
            }
        }
        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.getDateInfo {
//                [weak self] startDate, endDate in
//                guard let self = self else { return }
            
                //  离港时间选择区间从预约在港递交时间到2029-12-31 若在港递交时间为空则离港时间选择最早为今天
                var startDate: String = self.model.getSubmitHKTime()
                let format = "yyyy-MM-dd"
                if startDate.count >= format.count {
                    startDate = String(startDate.prefix(format.count))
                }
                if startDate.isEmpty {
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = format
                    startDate = dateFormatter.string(from: Date())
                }
                var endDate = "2029-12-31"
            
                let view = YHRangeDatePickerSheetView2.sheetView()
                view.viewTitle = "选择预计离港时间"
                view.minDateStr = startDate
                view.maxDateStr = endDate
                view.showBestFlag = false
                view.block = {
                    [weak self] (selectDateStr, hourTime) in
                    guard let self = self else { return }
                    let selectTimeStr = "\(selectDateStr) \(hourTime)"
                    printLog("\(selectTimeStr)")
                    // 选择离港时间
                    if self.model.ready_to_submit_at.isEmpty {
                        self.model.leave_hk_at = selectTimeStr
                    } else {
                        
                        if self.compareDates(selectTimeStr, self.model.ready_to_submit_at) != .large {
                            // selectTimeStr <= ready_to_submit_at
                            YHHUD.flash(message: "预计离港时间预约必须晚于在港递交时间")
                            return
                        }
                        self.model.leave_hk_at = selectTimeStr
                    }
                    self.refreshBlock?()

                }
                view.show()
//            }
        }
        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 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
    }
    
    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()
        
        // 时间控件红色提示显示
        var isNeeShowSubmitTimeError = false
        if model.isClickSubmit {
            if model.ready_to_submit_at.isEmpty {
                isNeeShowSubmitTimeError = true
                submitTimeItemView.errorTips = "请选择在港递交时间"
                
            } else if !model.server_submit_deadLine_start.isEmpty, !model.server_submit_deadLine_end.isEmpty {
                if !model.checkSubmitTime() {
                    isNeeShowSubmitTimeError = true
                    submitTimeItemView.errorTips = "递交时间不在允许的范围内"
                }
            }
        }
        submitTimeItemView.isNeedShowErrorTips = isNeeShowSubmitTimeError
        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 getDateInfo(_ result: ((_ startTime: String, _ endTime: String) -> Void)?) {
        
        /*
        // 开始时间和结束时间 都有则都取服务器model时间
        // 若开始时间为空则取当前时间
        // 若结束时间为空则取当前时间+28天的时间
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        var startTimeStr = formatter.string(from: Date())
        var endTimeStr = ""
        if let date = formatter.date(from: startTimeStr) {
            let endTimeStamp = date.timeIntervalSince1970 + (28.0 * 24.0 * 60.0 * 60.0)
            endTimeStr = formatter.string(from: Date(timeIntervalSince1970: endTimeStamp))
        }
        
        if let firstUser = self.model.users.first {
            if !firstUser.stay_deadline_start.isEmpty { // 服务器起始时间不为空
                startTimeStr = firstUser.stay_deadline_start
            }
            
            if !firstUser.stay_deadline.isEmpty { // 服务器结束时间不为空
                endTimeStr = firstUser.stay_deadline
                
            } else {
                // 结束时间为空 则设置为开始时间后的28天
                // 将字符串转换为 Date 对象
                if let date = formatter.date(from: startTimeStr) {
                    let endTimeStamp = date.timeIntervalSince1970 + (28.0 * 24.0 * 60.0 * 60.0)
                    endTimeStr = formatter.string(from: Date(timeIntervalSince1970: endTimeStamp))
                }
            }
        }
        let duration = "START_DATE: \(startTimeStr) END_DATE: \(endTimeStr)"
        printLog("\(duration)")
        result?(startTimeStr, endTimeStr)
         */
        
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getResignSubmitTime(renewalId: self.renewalId, userIds: self.model.users.filter { $0.isSelected }.map { return $0.id }) { model in
            YHHUD.hide()
            if let model = model {
                result?(model.stay_deadline_start, model.stay_deadline)
            }
        }
    }
    
    func compareDates(_ dateStr1: String, _ dateStr2: String) -> YHDateCompareResult {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        let dateFormatCount = dateFormatter.dateFormat.count
        
        var dateString1 = dateStr1
        if dateString1.count > dateFormatCount {
            dateString1 = String(dateString1.prefix(dateFormatCount))
        }
        var dateString2 = dateStr2
        if dateString2.count > dateFormatCount {
            dateString2 = String(dateString2.prefix(dateFormatCount))
        }
        
        // 将字符串转换为 Date 对象
        guard let date1 = dateFormatter.date(from: dateString1),
              let date2 = dateFormatter.date(from: dateString2) else {
            print("日期格式错误")
            YHHUD.flash(message: "日期格式错误")
            return .same
        }
        
        // 比较日期
        if date1 < date2 {
            return .small
        } else if date1 > date2 {
            return .large
        }
        return .same
    }
}

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 {
            
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHResignSelectApplicantCollectCell.cellReuseIdentifier, for: indexPath) as? YHResignSelectApplicantCollectCell else {
                return UICollectionViewCell()
            }
            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)
        }
    }
}
