//
//  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 dataModel : YHAppointItem? {
        didSet {
            updateUI()
        }
    }
    
    // param 选中的用户 是否选中 选中的用户是第几批
    var selectBlock: ((_ member: YHHKMemberModel, _ isSelect: Bool, _ groupIndex: Int)->())?
    
    var isShowSelectUserView: Bool = true {
        
        didSet {
            
            detailLabel.isHidden = !isShowSelectUserView
            selectGroupView.isHidden = !isShowSelectUserView
            collectionView.isHidden = !isShowSelectUserView
            lineView.isHidden = !isShowSelectUserView
            
            detailLabel.text = isShowSelectUserView ? self.detailText : ""
            detailLabel.snp.updateConstraints { make in
                make.top.equalTo(lineView.snp.bottom).offset(isShowSelectUserView ? 16 : 0)
            }
            
            selectGroupView.snp.updateConstraints { make in
                make.top.equalTo(detailLabel.snp.bottom).offset(isShowSelectUserView ? 12 : 0)
            }
            
            collectionView.snp.updateConstraints { make in
                make.top.equalTo(isShowSelectUserView ? 14 : 0)
                make.bottom.equalTo(isShowSelectUserView ? -14 : 0)
                make.height.equalTo(isShowSelectUserView ? self.getCollectionViewHeight() : 0)
            }
            
            optionsView.snp.updateConstraints { make in
                make.top.equalTo(selectGroupView.snp.bottom).offset(isShowSelectUserView ? 16 : 0)
            }
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        return view
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        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 detailLabel: 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 selectGroupView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(hex: 0xF8F9FB)
        view.layer.cornerRadius = kCornerRadius3
        return view
    }()
    
    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
                self.updateUI()
            }
        }
        return view
    }()
    
    lazy var timeSelectView: YHInfoItemSelectSheetView = {
        let view = YHInfoItemSelectSheetView(frame: .zero)
        view.isShowDetailOneline = true
        view.title = "具体日期"
        view.placeHolder = "请选择具体日期"
        view.detail = ""
        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.title = "港府办证地点"
        view.placeHolder = "请选择"
        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
                listView.selectBlock = {
                    [weak self] selectPlace in
                    guard let self = self else { return }
                    view.detail = selectPlace.name
                    if let model = dataModel?.model {
                        model.hkPlace = selectPlace
                        self.updateUI()
                    }
                }
                listView.show()
            }
        }
        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
        contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(lineView)
        whiteContentView.addSubview(detailLabel)
        whiteContentView.addSubview(selectGroupView)
        selectGroupView.addSubview(collectionView)
        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.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(16)
            make.left.equalTo(18)
            make.right.equalTo(-18)
        }
        
        selectGroupView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(detailLabel.snp.bottom).offset(12)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(40+16)
            make.top.equalTo(14)
            make.bottom.equalTo(-14)
        }
        
        optionsView.snp.makeConstraints { make in
            make.top.equalTo(selectGroupView.snp.bottom).offset(16)
            make.left.equalTo(18)
            make.right.equalTo(0)
        }
        
        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 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHSelectApplicantCell.cellReuseIdentifier, for: indexPath) as! YHSelectApplicantCell
            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 a: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.failColor))
        let b: ASAttributedString = .init("请您确认第\(model.itemIndex + 1)批赴港信息", .font(UIFont.PFSC_M(ofSize: 17)),.foreground(UIColor.mainTextColor))
        titleLabel.attributed.text = a+b
        
        collectionView.reloadData()
        let isShowSelectList = self.isShowSelectUserView
        self.isShowSelectUserView = isShowSelectList
        
        // 时间选择UI更新
        optionsView.selectIndex = 0
        if let model = dataModel?.model {
            if model.dateTye == 0 { // 具体时间
                optionsView.selectIndex = 0
                timeSelectView.placeHolder = "请选择具体日期"
                timeSelectView.detail = model.detailDateStr

            } else { // 具体时段
                optionsView.selectIndex = 1
                
                timeSelectView.placeHolder = "请选择具体时段"
                if !model.startDateStr.isEmpty, !model.endDateStr.isEmpty {
                    self.timeSelectView.detail = "\(model.startDateStr) ~ \(model.endDateStr)"
                } else {
                    self.timeSelectView.detail = ""
                }
            }
            
            // 办证地点更新
            self.locationSelectView.detail = model.hkPlace.name
        }
    }
    
    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 }
            
            timeSelectView.detail = dateStr
            if let model = dataModel?.model {
                model.detailDateStr = dateStr
            }
        }
    }
    
    // 选择时间段
    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
            }
        }
        view.show() //for test hjl
    }
}
