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

import UIKit

enum YHAppointButtnStatus: Int {
    case hidden = 0  // 隐藏按钮
    case confirmSubmitAppoint = 1 // 显示确认提交
    case nextStepToPay = 2 // 显示下一步去缴费
}

class YHCertificateAppointViewController: YHBaseViewController {

    var orderId: Int = 0
    var bottomStatus: YHAppointButtnStatus = .hidden
    var sections: [[YHAppointItem]] = []
    // 第一个section数据组
    var normalAppointInfoArr: [YHAppointItem] = []
    // 第二个section 只装选人的cell
    var selectMemberGroupArr: [YHAppointItem] = []
    // 第三个section 只装抢号中、已抢号
    var grabbingNumInfoArr: [YHAppointItem] = []
    // 第四个section 只装已抢号
    var grabbedNumInfoArr:[YHAppointItem] = []

    // 需要继续预约人员
    var waitList: [YHAppointMemberGroupModel] = []
    // 预约成功人员
    var successList: [YHAppointMemberGroupModel] = []
    
    // 无需预约办证人员
    var noNeedAppointMembers:[YHHKMemberModel] = []
    
    // 需要预约办证人员
    var waitAppointMembers:[YHHKMemberModel] = []
    var viewModel = YHCerAppointViewModel()
    let bottomViewHeight = 98.0
    
    // 是否赴港办证
    var isNeedGoHK: Int = 2 // 0不需要 1需要赴港  2没有选择
    // 有没有预约人员
    var reservationToHK: Int = 0 // 0没有预约 1已经预約
    // 申请人是否统一赴港激活签证 本地记录的开关
    var isAllMembersGo: Bool = true // 默认一起去
        
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8F9FB)
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateAppointOptionCell.self, forCellReuseIdentifier: YHCertificateAppointOptionCell.cellReuseIdentifier)
        tableView.register(YHSelectApplicantGroupCell.self, forCellReuseIdentifier: YHSelectApplicantGroupCell.cellReuseIdentifier)
        tableView.register(YHAppointWarmTipsCell.self, forCellReuseIdentifier: YHAppointWarmTipsCell.cellReuseIdentifier)
        tableView.register(YHGrabingNumberListCell.self, forCellReuseIdentifier: YHGrabingNumberListCell.cellReuseIdentifier)
        tableView.register(YHActivateHKVisaCell.self, forCellReuseIdentifier: YHActivateHKVisaCell.cellReuseIdentifier)
        tableView.register(YHWaitAppointMembersCell.self, forCellReuseIdentifier: YHWaitAppointMembersCell.cellReuseIdentifier)
        tableView.register(YHNoNeedAppointMembersCell.self, forCellReuseIdentifier: YHNoNeedAppointMembersCell.cellReuseIdentifier)
        tableView.register(YHHaveGrabbedNumberListCell.self, forCellReuseIdentifier: YHHaveGrabbedNumberListCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认提交", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didBottomBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.isHidden = true
        view.backgroundColor = .white
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !viewModel.isHKHolidaysOKFlag {
            loadHKHolidays()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadHKHolidays()
        
        createUI()
    }
    
    func createUI() {
        
        super.viewDidLoad()
        self.gk_navTitle = "赴港办证预约"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)
        
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0)
        }
        
        requetHKPlaceList()
        requestData()
    }
    
    func requestData(completion:(()->())? = nil) {
        YHHUD.show(.progress(message: "加载中..."))
        self.requetIsGoToHK { // 请求是否赴港办证选项和是否已预约过
            self.requetAppointMembers { // 请求赴港办证人员名单
                YHHUD.hide()
                if self.reservationToHK == 1 { // 有历史预约人员
                    YHHUD.show(.progress(message: "加载中..."))
                    self.requestAppointResultList { // 请求预约结果
                        YHHUD.hide()
                        self.updateData()
                        completion?()
                        self.requestSuccessScriptUrls()

                    }
                } else { // 没有预约过
                    YHHUD.hide()
                    self.updateData()
                    completion?()
                }
            }
        }
    }
    
    func updateData() {
        
        YHHUD.hide()

        sections.removeAll()
        normalAppointInfoArr.removeAll()
        selectMemberGroupArr.removeAll()
        grabbingNumInfoArr.removeAll()
        grabbedNumInfoArr.removeAll()

        // *赴港办证
        let item1 = YHAppointItem(type: .goHKMakeCertificate)
        normalAppointInfoArr.append(item1)
        
        if self.isNeedGoHK != 1 { // 是否赴港办证没有选择是
            refreshData()
            return
        }
        // 赴港办证选择了是
        // *温馨提示
        let item2 = YHAppointItem(type: .warmTips)
        normalAppointInfoArr.append(item2)
        
        // *无需预约办证成员（未满11岁）
        if self.noNeedAppointMembers.count > 0 {
            let item3 = YHAppointItem(type: .noNeedMakeCertificateMembers)
            normalAppointInfoArr.append(item3)
        }
        
        if self.reservationToHK == 0 { // 没有预约过人员
            
            // 赴港激活签证 申请人是否统一赴港激活签证
            let item4 = YHAppointItem(type: .activeVisa)
            normalAppointInfoArr.append(item4)
            
            if self.isAllMembersGo { // 申请人统一赴港激活签证
                
                if self.waitAppointMembers.count > 0 {
                    let item5 = YHAppointItem(type: .confirmGoHKInfo)
                    item5.itemIndex = 0
                    let group1 = YHSelectGroupMemberModel()
                    group1.isAllMembersGoHK = true
                    group1.arr = waitAppointMembers.deepCopy().map {
                        let member = $0
                        member.isSelected = true
                        return member
                    }
                    item5.model = group1
                    item5.placeList = self.viewModel.placeList
                    item5.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
                    selectMemberGroupArr.append(item5)
                }
                
            } else { // 申请人不是统一赴港激活签证
                
                if self.waitAppointMembers.count > 0 {
                    let item6 = YHAppointItem(type: .confirmGoHKInfo)
                    item6.itemIndex = 0
                    let group1 = YHSelectGroupMemberModel()
                    group1.arr = waitAppointMembers.deepCopy().map {
                        let member = $0
                        member.isSelected = true
                        return member
                    }
                    item6.model = group1
                    item6.placeList = self.viewModel.placeList
                    item6.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
                    selectMemberGroupArr.append(item6)
                }
            }
            
        } else { // 有预约过的人员
            
            // 待预约的赴港成员
            if waitAppointMembers.count > 0 {
                let item5 = YHAppointItem(type: .needReAppointMembers)
                normalAppointInfoArr.append(item5)
            }
            
            // 赴港办理抢号中批次
            if self.waitList.count > 0 {
                let item6 = YHAppointItem(type: .grabingNumberBatch)
                grabbingNumInfoArr.append(item6)
            }
            
            // 赴港办理已抢号批次
            if self.successList.count > 0 {
                let item7 = YHAppointItem(type: .haveGrabedNumberBatch)
                grabbedNumInfoArr.append(item7)
            }
        }
        refreshData()
    }
    
    func refreshData() {
        
        sections.removeAll()
        
        if normalAppointInfoArr.count > 0 {
            sections.append(normalAppointInfoArr)
        }
        
        if selectMemberGroupArr.count > 0 {
            sections.append(selectMemberGroupArr)
        }
        
        if grabbingNumInfoArr.count > 0 {
            sections.append(grabbingNumInfoArr)
        }
        
        if grabbedNumInfoArr.count > 0 {
            sections.append(grabbedNumInfoArr)
        }
        self.tableView.reloadData()
        
        // 底部按钮更新
        self.bottomStatus = .hidden
        
        if self.reservationToHK == 0 { // 没有预约人员
            if self.isNeedGoHK == 1 { // 赴港办证选是
                // 底部按钮显示确认提交
                self.bottomStatus = .confirmSubmitAppoint
                
            } else if self.isNeedGoHK == 0 { // 赴港办证选否
                    // 底部按钮显示下一步去缴费
                    self.bottomStatus = .nextStepToPay
                
            } else { // 赴港办证未选择
                // 不显示底部按钮
                self.bottomStatus = .hidden
            }
            
        } else { // 有预约过
            if waitAppointMembers.count <= 0 { // 全部都预约完了
                self.bottomStatus = .nextStepToPay

            } else { // 还有未预约人员
                // 不显示底部按钮
                self.bottomStatus = .hidden
                if self.successList.count > 0 || self.waitList.count > 0 { // 有部分成功预约人员或抢号中的人员
                    // 底部按钮显示下一步去缴费
                    self.bottomStatus = .nextStepToPay
                }
            }
        }
        
        bottomView.isHidden = (self.bottomStatus == .hidden)
        if self.bottomStatus == .confirmSubmitAppoint {
            bottomBtn.setTitle("确认提交", for: .normal)
        } else if self.bottomStatus == .nextStepToPay {
            bottomBtn.setTitle("下一步，去缴费", for: .normal)
        }
        
        self.bottomView.snp.updateConstraints { make in
            make.height.equalTo((self.bottomStatus == .hidden) ? 0 : bottomViewHeight)
        }
        
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
    }
}

extension YHCertificateAppointViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if 0 <= section, section < sections.count {
            let arr = sections[section]
            return arr.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) 
        
        if 0 <= indexPath.section, indexPath.section < sections.count {
            let arr = sections[indexPath.section]
            if 0 <= indexPath.row, indexPath.row < arr.count {
                let item = arr[indexPath.row]
                if item.type == .goHKMakeCertificate {
                    // 赴港办证
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateAppointOptionCell.cellReuseIdentifier, for: indexPath) as! YHCertificateAppointOptionCell
            
                    var isGoHK: Bool? = nil
                    if self.isNeedGoHK == 0 {
                        isGoHK = false
                    } else if self.isNeedGoHK == 1 {
                        isGoHK = true
                    }
                    cell.isSelectGoHK = isGoHK
                    cell.selectBlock = {
                        [weak self] index in
                        guard let self = self else { return }
                        // 此处index表示第index个按钮
                        let isNeedHK = (index == 0)
                        self.saveNeedGoToHK(isNeed: isNeedHK) {
                            [weak self] success in
                            guard let self = self else { return }
                            
                            if success {
                                self.isNeedGoHK = isNeedHK ? 1 : 0
                            }
                            self.updateData()
                        }
                    }
                    
                    // 默认设置两个按钮可点击
                    cell.optionsView.setOptionBtnDisabled(index: 0, disabled: false)
                    cell.optionsView.setOptionBtnDisabled(index: 1, disabled: false)

                    if self.reservationToHK == 1 { // 已经预约过
                        // 是否赴港办证不能点击否  index 0是是按钮 1是否按钮
                        // 否按钮不可点击且未选中 标题置灰
                        cell.optionsView.setOptionBtnDisabledAndUnselected(1)
                        cell.optionsView.setOptionBtnDisabled(index: 0, disabled: true)
                    }
                    return cell
                }
                
                if item.type == .warmTips {
                    // 温馨提示
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHAppointWarmTipsCell.cellReuseIdentifier, for: indexPath) as! YHAppointWarmTipsCell
                    return cell
                }
                
                if item.type == .noNeedMakeCertificateMembers {
                    // 无需预约办证成员（未满11岁）
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHNoNeedAppointMembersCell.cellReuseIdentifier, for: indexPath) as! YHNoNeedAppointMembersCell
                    cell.members = noNeedAppointMembers
                    return cell
                }
                
                if item.type == .activeVisa {
                    // 赴港激活签证
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHActivateHKVisaCell.cellReuseIdentifier, for: indexPath) as! YHActivateHKVisaCell
                    cell.isAllGo = self.isAllMembersGo
                    cell.selectBlock = {
                        [weak self] isAllGo in
                        guard let self = self else { return }
                        self.isAllMembersGo = isAllGo
                        self.updateData()
                    }
                    return cell
                }
                
                if item.type == .needReAppointMembers {
                    // 待预约赴港成员
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHWaitAppointMembersCell.cellReuseIdentifier, for: indexPath) as! YHWaitAppointMembersCell
                    cell.members = waitAppointMembers

                    cell.clickBlock = {
                        [weak self] in
                        guard let self = self else { return }
                       let vc = YHReAppointViewController()
                        vc.orderId = self.orderId
                        vc.waitAppointMembers = self.waitAppointMembers.deepCopy()
                        vc.viewModel = self.viewModel
                        vc.updateBlock = {
                            self.requestData()
                        }
                        self.navigationController?.pushViewController(vc)
                    }
                    return cell
                    
                }
                
                if item.type == .confirmGoHKInfo {
                    // 请您确认第X批赴港信息
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHSelectApplicantGroupCell.cellReuseIdentifier, for: indexPath) as! YHSelectApplicantGroupCell
                    cell.dataModel =  arr[indexPath.row]
                    cell.refreshBlock = {
                        [weak self] in
                        guard let self = self else { return }
                        self.tableView.reloadData()
                    }
                    cell.selectBlock = {
                        [weak self] member, isSelect, groupIndex in
                        guard let self = self else { return }
                        self.selectMember(member, select: isSelect, groupLevel: groupIndex)
                    }
                    return cell
                }
                
                if item.type == .grabingNumberBatch {
                    // 赴港办理抢号中批次
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHGrabingNumberListCell.cellReuseIdentifier, for: indexPath) as! YHGrabingNumberListCell
                    cell.listArr = self.waitList
                    cell.cancelAppointBlock = {
                        [weak self] groupModel in
                        guard let self = self else { return }
                        // 抢号中点击取消预约
                        
                           let alert = YHCancelAppointAlertView.alertView()
                           alert.memberNamesText = groupModel.getMemberNames()
                           alert.selectBlock = {
                                [weak self] sure in
                                guard let self = self else { return }
                                
                                if !sure {
                                    return
                                }
                                
                                YHHUD.show(.progress(message: "加载中..."))
                                self.viewModel.cancelAppoint(orderId: orderId, reservationId: groupModel.id) { success in
                                    YHHUD.hide()
                                    if !success {
                                        YHHUD.flash(message: "取消失败")
                                        return
                                    }
                                    self.requestData()
                                }
                            }
                         alert.show()
                    }
                    return cell
                }
                
                if item.type == .haveGrabedNumberBatch {
                   // 赴港办理已抢号批次
                    let cell = tableView.dequeueReusableCell(withIdentifier: YHHaveGrabbedNumberListCell.cellReuseIdentifier, for: indexPath) as! YHHaveGrabbedNumberListCell
                    cell.listArr = self.successList
                    return cell
                }
            }
        }
    
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}

extension YHCertificateAppointViewController {
    
    func requetIsGoToHK(completion:(()->())?) {
        viewModel.getIsNeedGoToHK(orderId: orderId) {
            [weak self] needGoHK, reservationToHK in
            guard let self = self else { return }
            self.isNeedGoHK = needGoHK
            self.reservationToHK = reservationToHK
            completion?()
        }
    }
    
    func saveNeedGoToHK(isNeed:Bool, callback:((Bool)->())?) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.saveNeedGoHK(orderId: orderId, need: isNeed) {
            success in
            YHHUD.hide()
            callback?(success)
        }
    }
    
    func requetAppointMembers(completion:(()->())?) {
        viewModel.getGoHKFamilyMembers(orderId: orderId) {
            [weak self] success, error in
            guard let self = self else { return }
            let users = self.viewModel.hkUsers
            noNeedAppointMembers.removeAll()
            waitAppointMembers.removeAll()
            for user in users {
                if user.isAtLeast11Years() { // 不小于11岁的人才能预约赴港
                    user.isSelected = true
                    waitAppointMembers.append(user)
                    
                } else {
                    noNeedAppointMembers.append(user)
                }
            }
            completion?()
        }
    }
    
    func requestAppointResultList(completion:(()->())?) {
        
        viewModel.getAppointResult(orderId: orderId) { success, error in
            self.waitList = self.viewModel.appointResult.waiting
            self.successList = self.viewModel.appointResult.success
            completion?()
        }
    }
    
    
    func requetHKPlaceList() {
        viewModel.getMakeCerPlaceList { success, error in
            
        }
    }
}

extension YHCertificateAppointViewController {
    //预约成功后调用
    func showSelectHKServiceAlertView() {
        
        if self.orderId > 0 {
            let key = "hkExpectService_\(self.orderId)"
            if let value = UserDefaults.standard.value(forKey: key) {
                printLog("已经展示过了 兄弟...")
                return
            }
        }
        
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getServicelist {
            success, error in
            
            YHHUD.hide()
            let view = YHServiceSelectAlertView.alertView()
            view.items = self.viewModel.serviceArr
            view.confirmBlock = {
               [weak self] ids in
                if !ids.isEmpty {
                    
                    var str = ""
                    for (index,item) in ids.enumerated() {
                        str = str + (index == 0 ? "" : ",") + String(item)
                    }
                    
                    let param : [String : Any] = ["order_id":self?.orderId as Any,"ids":str]
                    self?.saveHkexpectServic(params: param)
                }
            }
            view.show()
            
            if self.orderId > 0 {
                let key = "hkExpectService_\(self.orderId)"
                UserDefaults.standard.setValue("true", forKey: key)
                UserDefaults.standard.synchronize()
            }
        }
    }
    
    
    func saveHkexpectServic(params : [String : Any]) {
        YHHUD.show(.progress(message: "提交中..."))
        viewModel.saveHkExpectService(params: params) { success, error in
            YHHUD.hide()
            if success {
                YHHUD.flash(message: "提交成功")
                
            } else {
                YHHUD.flash(message: "提交失败")
            }
        }
    }
    
    func loadHKHolidays() {
        viewModel.getHKHolidays { success, error in
        }
    }
    
    // memberId 申请人id
    // select 点击选择
    // groupLevel 是分的第几组 从0开始计数
    func selectMember(_ currentMember: YHHKMemberModel, select:Bool, groupLevel:Int) {
        
        // 获取当前批的成员组
        var currentMembers:[YHHKMemberModel] = []
        
        // 先改变点击当前批的选择状态
        if 0 <= groupLevel, groupLevel < selectMemberGroupArr.count {
            let item = selectMemberGroupArr[groupLevel]
            if let members = item.model?.arr {
                currentMembers = members
                for member in members {
                    if member.id == currentMember.id {
                        member.isSelected = select
                    }
                }
            }
        }
        
        if !select { // 如果操作是取消
            // 如果操作的当前批次是最后一批，则需要分新批次
            if groupLevel == selectMemberGroupArr.count-1 {
                // 进行分批
                let newItem = YHAppointItem(type: .confirmGoHKInfo)
                // 批次+1
                newItem.itemIndex = groupLevel+1
                let group1 = YHSelectGroupMemberModel()
                // 找出上一批未选中的人
                let needMembers = currentMembers.filter {
                    return $0.isSelected == false
                }
                // 在下一批中默认全选中
                group1.arr = needMembers.deepCopy().map {
                    let item = $0
                    item.isSelected = true
                    return item
                }
                newItem.model = group1
                newItem.placeList = self.viewModel.placeList
                newItem.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
                selectMemberGroupArr.append(newItem)
                
            } else { // 如果操作的当前批次不是最后一批 需要更新后面几批的选中状态
                
                let nextGroupIndex = groupLevel+1
                let newMember = currentMember.copy() as! YHHKMemberModel
                newMember.isSelected = true
                if 0 <= groupLevel, groupLevel < selectMemberGroupArr.count {
                    let item = selectMemberGroupArr[nextGroupIndex]
                    if var members = item.model?.arr {
                        members.append(newMember)
                        item.model?.arr = members
                    }
                }
            }
        } else { // 如果操作是选中
            
            // 肯定会有下一层因为之前取消过
            let nextGroupIndex = groupLevel+1
            if 0 <= nextGroupIndex, nextGroupIndex < selectMemberGroupArr.count {
                for i in nextGroupIndex..<selectMemberGroupArr.count {
                    let item = selectMemberGroupArr[i]
                    if var members = item.model?.arr {
                        // 下几批的组员中都要删除该人
                        members = members.filter { $0.id != currentMember.id }
                        item.model?.arr = members
                    }
                }
            }
        }
        
        //  无论是选中还是反选 检测下面所有批次有无全未选数组，有则删除该批
        let nextGroupIndex = groupLevel+1
        if 0 <= nextGroupIndex, nextGroupIndex < selectMemberGroupArr.count {
            var i = nextGroupIndex
            while i < selectMemberGroupArr.count {
                let item = selectMemberGroupArr[i]
                if let members = item.model?.arr {
                    let a = members.filter {
                       return $0.isSelected == true
                    }
                    // 数组中全未选
                    if a.count <= 0 {
                        selectMemberGroupArr.remove(at: i)
                        
                    } else {
                        i += 1
                    }
                }
            }
        }
        
        // 重新进行批次排号
        for (index, group) in selectMemberGroupArr.enumerated() {
            group.itemIndex = index
        }
        refreshData()
    }
}

extension YHCertificateAppointViewController {
    
    @objc func didBottomBtnClicked() {
        
        if self.bottomStatus == .confirmSubmitAppoint {
            // 提交预约时间信息
            submitAppointInfo()
            
        } else if self.bottomStatus == .nextStepToPay {
            // 下一步去缴费
            let vc = YHVisaPaymentVC()
            vc.orderID = orderId
            navigationController?.pushViewController(vc)
        }
    }
    
    func submitAppointInfo() {
        
        if self.waitAppointMembers.count <= 0 {
            YHHUD.flash(message: "无赴港人员")
            return
        }
        
        // 检测各批次是否有日期或办证地点未选择
        var isOK = true
        for item in self.selectMemberGroupArr {
            if let groupModel = item.model {
                if groupModel.dateTye == 0 { // 选择具体日期
                    if groupModel.detailDateStr.isEmpty {
                        groupModel.isNeedCheck = true
                        isOK = false
                    }

                } else { // 选择具体时段
                    if groupModel.startDateStr.isEmpty || groupModel.endDateStr.isEmpty {
                        groupModel.isNeedCheck = true
                        isOK = false
                    }
                }
                
                // 办证地点未选
                if groupModel.hkPlace.name.isEmpty {
                    groupModel.isNeedCheck = true
                    isOK = false
                }
            }
        }
        if !isOK { // 检测各批次是否有日期或办证地点未选择
            self.tableView.reloadData()
            return
        }
        
        var batchs:[[String: Any]] = []
        for group in selectMemberGroupArr {
            if let model = group.model {
                var start_time = ""
                var end_time = ""
                if model.dateTye == 0 { // 具体时间
                    start_time = model.detailDateStr
                    end_time = model.detailDateStr
                    
                } else { // 具体时段
                    start_time = model.startDateStr
                    end_time = model.endDateStr
                }
                
                let selectUsers = model.arr.filter {
                    return $0.isSelected == true
                }
                let users = selectUsers.map {
                    let dict = ["id" : $0.id,
                                "type" : $0.type,
                                "name" : $0.name] as! [String : Any]
                    return dict
                }
                
                if users.count > 0 {
                    let batch:[String : Any] = ["start_time" : start_time,
                                                "end_time" : end_time,
                                                "migration_office" : model.hkPlace.name,
                                                "users" : users]
                    batchs.append(batch)
                }
            }
        }
        
        // 请求参数
        let params:[String : Any] = ["order_id": orderId,
                                     "batch": batchs]
        
        printLog("\(params)")
        
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.submitAppoint(params: params) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if success {
                YHHUD.flash(message: "提交成功")
                self.requestData {
                    self.showSelectHKServiceAlertView()
                }
                return
            }
            let msg = error?.errorMsg ?? ""
            YHHUD.flash(message: msg)
        }
    }
    
    // 请求抢号成功后的反馈回执文件私链URL组对应的公链组
    func requestSuccessScriptUrls() {
        
        if self.successList.count <= 0 {
            return
        }
        
        let semaphore = DispatchSemaphore(value: 1)
        
        DispatchQueue.global().async {
            for model in self.successList {
                var publicUrls:[String] = []
                for (index, privateUrl) in model.receipts.enumerated() {
                    // 信号-1 如果信号<0 则阻塞等待
                    semaphore.wait()
            
                    self.viewModel.getPublicImageUrl(privateUrl) { success, error in
                        if let publicUrl = success {
                            publicUrls.append(publicUrl)
                        } else {
                            // 私链转公链失败 只有在点击对应的回执图片的时候再次请求公链
                            publicUrls.append("")
                        }
                        // 释放信号+1
                        semaphore.signal()
                    }
                }
                semaphore.wait()
                model.publicReceipts = publicUrls
                semaphore.signal()
            }
                
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}

