//
//  YHSelectApplicantGroupCell.swift
//  galaxy
//
//  Created by edy on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHSelectApplicantGroupCell: UITableViewCell {

    static let cellReuseIdentifier = "YHSelectApplicantGroupCell"
    var detailText = "选择第一批赴港激活签证的申请人"
    
    var refreshBlock: (() -> Void)?
    
    var dataModel: YHAppointItem? {
        didSet {
            updateUI()
        }
    }
    
    // param 选中的用户 是否选中 选中的用户是第几批
    var selectBlock: ((_ member: YHHKMemberModel, _ isSelect: Bool, _ groupIndex: Int) -> Void)?
    
    var isShowSelectUserView: Bool = true {
        
        didSet {
            
            selectPanelView.isHidden = !isShowSelectUserView
            selectPanelView.snp.remakeConstraints { make in
                make.top.equalTo(reAppontNameView.snp.bottom)
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.bottom.equalTo(optionsView.snp.top)

                if !isShowSelectUserView {
                    make.height.equalTo(0)
                }
            }
            
            reAppontNameView.isHidden = !isShowRepointNameView
            reAppontNameView.snp.remakeConstraints { make in
                make.top.equalTo(lineView.snp.bottom)
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.bottom.equalTo(selectPanelView.snp.top)
                if !isShowRepointNameView {
                    make.height.equalTo(0)
                }
            }
            
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(isShowSelectUserView ? self.getCollectionViewHeight() : 0)
            }
            
            optionsView.lineView.isHidden = (!isShowSelectUserView && !isShowRepointNameView)
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    var isShowRepointNameView: Bool = false {
        didSet {
            
            selectPanelView.isHidden = !isShowSelectUserView
            selectPanelView.snp.remakeConstraints { make in
                make.top.equalTo(reAppontNameView.snp.bottom)
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.bottom.equalTo(optionsView.snp.top)
                if !isShowSelectUserView {
                    make.height.equalTo(0)
                }
            }
            
            optionsView.lineView.isHidden = (!isShowSelectUserView && !isShowRepointNameView)

            reAppontNameView.isHidden = !isShowRepointNameView
            reAppontNameView.snp.remakeConstraints { make in
                make.top.equalTo(lineView.snp.bottom)
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.bottom.equalTo(selectPanelView.snp.top)
                if !isShowRepointNameView {
                    make.height.equalTo(0)
                }
            }
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        let a: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.failColor))
        let b: ASAttributedString = .init("请您确认第一批赴港信息", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
        label.attributed.text = a+b
        return label
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    lazy var selectPanelView: UIView = {
        let panelView = UIView()
        
        panelView.addSubview(selecPanelTitleLabel)
        
        let groupBgview = UIView()
        groupBgview.backgroundColor = .init(hex: 0xF8F9FB)
        groupBgview.layer.cornerRadius = kCornerRadius3
        groupBgview.addSubview(collectionView)
        panelView.addSubview(groupBgview)
        
        selecPanelTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        groupBgview.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(selecPanelTitleLabel.snp.bottom).offset(12)
            make.bottom.equalTo(-16)
        }
        
        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 panelView
    }()
    
    lazy var selecPanelTitleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = .mainTextColor
        label.text = self.detailText
        return label
    }()
    
    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(YHSelectApplicantCell.self, forCellWithReuseIdentifier: YHSelectApplicantCell.cellReuseIdentifier)
        return collectView
    }()
    
    lazy var optionsView: YHInfoItemOptionView = {
        let view = YHInfoItemOptionView(frame: .zero)
        view.titleGap = 22.0
        view.title = "赴港办证时间"
        view.options = ["具体日期", "具体时段"]
        view.selectIndex = 0
        view.selectBlock = {
            [weak self] index in
            guard let self = self else { return }
            if let model = dataModel?.model {
                model.dateTye = index
                refreshBlock?()
            }
        }
        return view
    }()
    
    lazy var timeSelectView: YHInfoItemSelectSheetView = {
        let view = YHInfoItemSelectSheetView(frame: .zero)
//        view.isShowDetailOneline = true
        view.title = "具体日期"
        view.placeHolder = "请选择具体日期"
        view.detail = ""
        view.isNeedShowErrorTips = false
        view.errorTips = "请选择具体日期"
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
            if let model = dataModel?.model {
                if model.dateTye == 0 { // 选择具体时间
                    self.selectDetailDate()

                } else { // 具体时段
                    self.selectDurationTime()
                }
            }
        }
        return view
    }()
    
    lazy var locationSelectView: YHInfoItemSelectSheetView = {
        let view = YHInfoItemSelectSheetView(frame: .zero)
//        view.isShowDetailOneline = false
        view.title = "港府办证地点"
        view.placeHolder = "请选择"
        view.errorTips = "请选择港府办证地点"
        view.isNeedShowErrorTips = false
        view.detail = ""
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
            if let arr = dataModel?.placeList, arr.count > 0 {
                let listView =  YHSelectHKPlaceListView.listView()
                listView.listArr = arr
                
                if let place = dataModel?.model?.hkPlace {
                    if place.id >= 0 && !place.name.isEmpty {
                        listView.selectModel = place
                    } else {
                        listView.selectModel = arr[0]
                    }

                } else {
                    listView.selectModel = arr[0]
                }
                
                listView.selectBlock = {
                    [weak self] selectPlace in
                    guard let self = self else { return }
                    view.detail = selectPlace.name
                    if let model = dataModel?.model {
                        model.hkPlace = selectPlace
                        refreshBlock?()
                    }
                }
                listView.show()
            }
        }
        return view
    }()
    
    lazy var reAppontNameView: UIView = {
        let view = UIView()
        
        let grayView = UIView()
        grayView.backgroundColor = .init(hex: 0xF8F9FB)
        grayView.addSubview(repointMembersNameLabel)
        view.addSubview(grayView)
        
        grayView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(12)
            make.bottom.equalTo(-12)
        }
        repointMembersNameLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalTo(14)
            make.bottom.equalTo(-14)
        }
        return view
    }()
    
    lazy var repointMembersNameLabel: UILabel =  {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 13)
        label.textColor = .mainTextColor
        label.text = "成员："
        return label
    }()
    
    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
        contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(lineView)
        whiteContentView.addSubview(reAppontNameView)
        whiteContentView.addSubview(selectPanelView)
        whiteContentView.addSubview(optionsView)
        whiteContentView.addSubview(timeSelectView)
        whiteContentView.addSubview(locationSelectView)

        whiteContentView.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(0)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(18)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        lineView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(0.5)
        }
        
        reAppontNameView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.height.equalTo(0)
        }
        
        selectPanelView.snp.makeConstraints { make in
            make.top.equalTo(reAppontNameView.snp.bottom)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(optionsView.snp.top)
        }

        optionsView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        timeSelectView.snp.makeConstraints { make in
            make.top.equalTo(optionsView.snp.bottom).offset(0)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        locationSelectView.snp.makeConstraints { make in
            make.top.equalTo(timeSelectView.snp.bottom).offset(0)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.bottom.equalToSuperview()
        }
    }

}

extension YHSelectApplicantGroupCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return (dataModel?.model?.arr.count) ?? 0
        }
        
        // 返回每个单元格的大小
        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: YHSelectApplicantCell.cellReuseIdentifier, for: indexPath) as? YHSelectApplicantCell else { return UICollectionViewCell() }
            if let arr = dataModel?.model?.arr {
                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 let dataModel = self.dataModel, let model = dataModel.model {
            if 0 <= indexPath.item && indexPath.item < model.arr.count {
                let member = model.arr[indexPath.item]
                let selectArr = model.arr.filter {
                    return $0.isSelected == true
                }
                if selectArr.count == 1, member.isSelected == true, member.id == selectArr[0].id {
                    // 分组中仅有一个选中用户 且点击的是该用户
                    YHHUD.flash(message: "每一批赴港申请人不可为空，请确保每位申请人都在列")
                    return
                }
                selectBlock?(member, !member.isSelected, dataModel.itemIndex)
            }
        }
    }
}

private extension YHSelectApplicantGroupCell {
    func updateUI() {
        guard let model = dataModel else {
            return
        }
    
        let batchNumberText = self.convertNumberToChineseText(model.itemIndex+1)
        let a: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.failColor))
        let b: ASAttributedString = .init("请您确认第\(batchNumberText)批赴港信息", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
        titleLabel.attributed.text = a+b
        
        selecPanelTitleLabel.text = "选择第\(batchNumberText)批赴港激活签证的申请人"
        
        collectionView.reloadData()
        
        // 时间选择UI更新
        optionsView.selectIndex = 0
        var isSelectDate = false
        
        if let model = dataModel?.model {
            
            self.isShowSelectUserView = !model.isAllMembersGoHK
            self.isShowRepointNameView = model.isShowReAppointView
            
            if model.isAllMembersGoHK {
                let a: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.failColor))
                let b: ASAttributedString = .init("请您确认以下赴港信息", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
                titleLabel.attributed.text = a+b
            }
            
            timeSelectView.title = model.dateTye == 0 ? "具体日期" : "具体时段"

            if model.dateTye == 0 { // 具体时间
                optionsView.selectIndex = 0
                timeSelectView.placeHolder = "请选择具体日期"
                timeSelectView.errorTips = "请选择具体日期"
                timeSelectView.detail = model.detailDateStr
                if !model.detailDateStr.isEmpty {
                    isSelectDate = true
                }

            } else { // 具体时段
                optionsView.selectIndex = 1
                timeSelectView.placeHolder = "请选择具体时段"
                timeSelectView.errorTips = "请选择具体时段"
                if !model.startDateStr.isEmpty, !model.endDateStr.isEmpty {
                    self.timeSelectView.detail = "\(model.startDateStr) ~ \(model.endDateStr)"
                    isSelectDate = true
                    
                } else {
                    self.timeSelectView.detail = ""
                }
            }
            
            // 办证地点更新
            locationSelectView.detail = model.hkPlace.name
            // 办证地点是否显示红色错误提示
            locationSelectView.isNeedShowErrorTips = (model.isNeedCheck && model.hkPlace.name.isEmpty)
            // 办证地点是否显示红色错误提示
            timeSelectView.isNeedShowErrorTips = (model.isNeedCheck && !isSelectDate)
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    func getCollectionViewHeight() -> CGFloat {
        
        if let arr = dataModel?.model?.arr {
            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
        }
        return 0.0
    }
    
    // 选择具体日期
    func selectDetailDate() {
        
        YHDatePickView.show(type: .yyyymmdd, title: "选择意向赴港时间".local, lastIsTaday: false, currentDay: "") {
            
            [weak self] dateStr in
            guard let self = self else { return }
            
            // 1.判断选择的日期是否不在今天之前
            if !dateLessGreatToday(date: dateStr) {
                YHHUD.flash(message: "不能选择今天及之前的日期")
                return
            }
            
            // 2.
            if let model = dataModel?.model {
                if !showHKHolidayWarmTips(startDateStr: dateStr, endDateStr: nil) {
                    model.detailDateStr = dateStr
                    timeSelectView.detail = dateStr
                }
            }
            refreshBlock?()
        }
    }
    
    func dateLessGreatToday(date: String) -> Bool {
        
        if date.count == "2022.02.02".count {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            
            // 假设我们有两个日期
            if let date1 = dateFormatter.date(from: date) {
                
                let today = Date()
                // 使用Calendar比较两个日期
                let calendar = Calendar(identifier: .chinese)
                let comparisonResult = calendar.compare(today, to: date1, toGranularity: .day)

                switch comparisonResult {
                case .orderedAscending:
                    return true
                case .orderedDescending:
                    print("第一个日期在第二个日期之后")
                    return false
                case .orderedSame:
                    return false
                }
            }
            
        }
        
        return false
    }
    
    // 选择时间段
    func selectDurationTime() {
        let view = YHRangeDatePickerSheetView.sheetView()
        view.block = { 
            
            [weak self] (startDate, endDate) in
            guard let self = self else { return }
            
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM-dd"
            let startDateStr = format.string(from: startDate)
            let endDateStr = format.string(from: endDate)
            printLog("\(startDateStr) ~ \(endDateStr)")
            
            if !startDateStr.isEmpty, !endDateStr.isEmpty {
                self.timeSelectView.detail = "\(startDateStr) ~ \(endDateStr)"
            } else {
                self.timeSelectView.detail = ""
            }

            if let model = dataModel?.model {
                model.startDateStr = startDateStr
                model.endDateStr = endDateStr
                
                _ = showHKHolidayWarmTips(startDateStr: startDateStr, endDateStr: endDateStr)
            }
            refreshBlock?()
        }
        view.show()
    }
    
    func showHKHolidayWarmTips(startDateStr: String?, endDateStr: String?) -> Bool {
        if let start = startDateStr, let end = endDateStr {
            // 时间段
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            
            if let startDate = dateFormatter.date(from: start),
               let endDate = dateFormatter.date(from: end) {
                let (arrString, allDates) = getAllDates(from: startDate, to: endDate)
                
                if let model = dataModel, let arr = model.arrHkHolidays, arr.count > 0 {
                    // 判断是否有交集
                    if haveCommonElements(array1: arrString, array2: arr) {
                        YHHUD.flash(message: "周日或法定节假日不可预约")
                        return true
                    }
                }
                
                // 判断 周日
                
                if hasSunday(in: allDates) {
                    YHHUD.flash(message: "周日或法定节假日不可预约")
                    return true
                }
            }
        } else if let start = startDateStr {
            // 时间点
            
            // 时间段
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            
            if let startDate = dateFormatter.date(from: start) {
                let (arrString, allDates) = getAllDates(from: startDate, to: startDate)
                
                if let model = dataModel, let arr = model.arrHkHolidays, arr.count > 0 {
                    // 判断是否有交集
                    if haveCommonElements(array1: arrString, array2: arr) {
                        YHHUD.flash(message: "周日或法定节假日不可预约")
                        return true
                    }
                }
                
                // 判断 周日
                
                if hasSunday(in: allDates) {
                    YHHUD.flash(message: "周日或法定节假日不可预约")
                    return true
                }
            }
        } else {
            
        }
        return false
    }
}

// MARK: - 提示逻辑 辅助函数
private extension YHSelectApplicantGroupCell {
    
    // 获取两个日期直接的全部日期
    
    /* 使用示例
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"

    if let startDate = dateFormatter.date(from: "2024-01-01"),
       let endDate = dateFormatter.date(from: "2024-01-10") {
        let allDates = getAllDates(from: startDate, to: endDate)
        for date in allDates {
            print(dateFormatter.string(from: date))
        }
    }
     */
    func getAllDates(from startDate: Date, to endDate: Date) -> ([String], [Date]) {
        var arrStrings: [String] = []
        var arrDates: [Date] = []
        
        var currentDate = startDate
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        let dateString = dateFormatter.string(from: currentDate)
        arrStrings.append(dateString)
        arrDates.append(currentDate)
        
        while currentDate <= endDate {
            let dateString = dateFormatter.string(from: currentDate)
            arrStrings.append(dateString)
            arrDates.append(currentDate)
            currentDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!
        }
        return (arrStrings, arrDates)
    }
    
    // 判断字符串是否有交集
    /*
     // 使用示例
     let array1 = ["apple", "banana", "cherry"]
     let array2 = ["banana", "kiwi", "mango"]

     let haveCommon = haveCommonElements(array1: array1, array2: array2)
     print(haveCommon) // 输出：true
     */
    func haveCommonElements(array1: [String], array2: [String]) -> Bool {
        let set1 = Set(array1)
        let set2 = Set(array2)
        return !set1.isDisjoint(with: set2)
    }
    
    // 判断日期是否有周日
    /*
     // 使用示例
     let dateFormatter = DateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd"
     dateFormatter.locale = Locale(identifier: "zh_CN") // 设置 locale 以确保周日被正确识别为周末的开始

     let dates = ["2024-01-01", "2024-01-07", "2024-01-08"].map { dateFormatter.date(from: $0)! }
     let isSunday = isSunday(in: dates)

     for (index, date) in dates.enumerated() {
         print("\(dateFormatter.string(from: date)) is Sunday: \(isSunday[index])")
     }
     */
    func hasSunday(in dates: [Date]) -> Bool {
        if dates.isEmpty {
            return false
        }
        
        var returnV = false
        let calendar = Calendar.current
        for(index, date) in dates.enumerated() {
            returnV = (calendar.component(.weekday, from: date) == 1) || returnV
            if returnV {
                return true
            }
        }
        return false
    }
    
    // 阿拉伯数字转文字
    func convertNumberToChineseText(_ number: Int) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: "zh_CN")
        numberFormatter.numberStyle = .spellOut
        return numberFormatter.string(from: NSNumber(value: number)) ?? ""
    }
}
