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

import UIKit

class YHCertificateAppointViewController: YHBaseViewController {

    var orderId: Int = 0
    var sections: [[YHAppointItem]] = []
    // 第一个section数据组
    var items1: [YHAppointItem] = []
    // 只装选人的cell
    var items2: [YHAppointItem] = []
    // 只装抢号中、已抢号
    var items3: [YHAppointItem] = []

    
    var waitList: [YHAppointMemberGroupModel] = []
    var successList: [YHAppointMemberGroupModel] = []
    
    // 无需预约办证人员
    var noNeedAppointMembers:[YHHKMemberModel] = []
    
    // 需要办证人员
    var waitAppointMembers:[YHHKMemberModel] = []
    let viewModel = YHCerAppointViewModel()
    
    // 是否赴港办证
    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
    }()
    
    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.tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
        requetHKPlaceList()
        requestData()
    }
    
    func requestData() {
        YHHUD.show(.progress(message: "加载中..."))
        self.requetIsGoToHK { // 请求是否赴港办证选项和是否已预约过
            self.requetAppointMembers { // 请求赴港办证人员名单
                if self.reservationToHK == 1 { // 有历史预约人员
                    YHHUD.show(.progress(message: "加载中..."))
                    self.requestAppointResultList { // 请求预约结果
                        YHHUD.hide()
                        self.updateData()
                    }
                } else { // 没有预约过
                    YHHUD.hide()
                    self.updateData()
                }
            }
        }
    }
    
    func updateData() {
        
        YHHUD.hide()

        sections.removeAll()
        items1.removeAll()
        items2.removeAll()
        items3.removeAll()

        // *赴港办证
        let item1 = YHAppointItem(type: .goHKMakeCertificate)
        items1.append(item1)
        
        if self.isNeedGoHK != 1 { // 是否赴港办证没有选择是
            refreshData()
            return
        }
        // 赴港办证选择了是
        // *温馨提示
        let item2 = YHAppointItem(type: .warmTips)
        items1.append(item2)
        
        // *无需预约办证成员（未满11岁）
        if self.noNeedAppointMembers.count > 0 {
            let item3 = YHAppointItem(type: .noNeedMakeCertificateMembers)
            items1.append(item3)
        }
        
        if self.reservationToHK == 0 { // 没有预约过人员
            
            // 赴港激活签证 申请人是否统一赴港激活签证
            let item4 = YHAppointItem(type: .activeVisa)
            items1.append(item4)
            
            if self.isAllMembersGo { // 申请人统一赴港激活签证
                let item5 = YHAppointItem(type: .confirmGoHKInfo)
                let group = YHSelectGroupMemberModel()
                group.arr = waitAppointMembers.deepCopy()
                item5.model = group
                item5.placeList = self.viewModel.placeList
                item5.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
                items2.append(item5)
                
            } else { // 申请人不是统一赴港激活签证
                let item6 = YHAppointItem(type: .confirmGoHKInfo)
                item6.itemIndex = 0
                let group1 = YHSelectGroupMemberModel()
                group1.arr = waitAppointMembers.deepCopy().map {
                    var member = $0
                    member.isSelected = true
                    return member
                }
                item6.model = group1
                item6.placeList = self.viewModel.placeList
                item6.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
                items2.append(item6)
                
            }
            
        } else { // 有预约过的人员
            
            // 待预约的赴港成员
            if waitAppointMembers.count > 0 {
                let item5 = YHAppointItem(type: .needReAppointMembers)
                items1.append(item5)
            }
            
            // 赴港办理抢号中批次
            if self.waitList.count > 0 {
                let item6 = YHAppointItem(type: .grabingNumberBatch)
                items3.append(item6)
            }
            
            // 赴港办理已抢号批次
            if self.successList.count > 0 {
                let item7 = YHAppointItem(type: .haveGrabedNumberBatch)
                items3.append(item7)
            }
        }
        refreshData()
    }
    
    func refreshData() {
        sections.removeAll()
        
        if items1.count > 0 {
            sections.append(items1)
        }
        
        if items2.count > 0 {
            sections.append(items2)
        }
        
        if items3.count > 0 {
            sections.append(items3)
        }
        
        self.tableView.reloadData()
    }
}

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
                    // 此处btnIndex 是从左到右按钮的index从0算起
                    // 按钮排序如下 [是0，否1]
                    var btnIndex = 1000
                    if self.isNeedGoHK == 0 { // 服务端0代表不需要，否
                        btnIndex = 1 // 选中第2个btn
                    } else if self.isNeedGoHK == 1 { // 服务端1代表需要，是
                        btnIndex = 0 // 选中第1个btn
                    }
                    
                    cell.selectIndex = btnIndex
                    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()
                        }
                    }
                    if self.reservationToHK == 1 { // 已经预约过
                        // 是否赴港办证不能点击否  index 0是是按钮 1是否按钮
                        cell.disableBtn(index: 1)
                    }
                    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()
                        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.isShowSelectUserView = !self.isAllMembersGo
                    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
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        self.viewModel.getServicelist { success, error in
//            let view = YHServiceSelectAlertView.alertView()
//            view.items = self.viewModel.serviceArr
//            view.confirmBlock = {
//               [weak self] ids in
//                printLog("\(ids)")
//            }
//            view.show()
//        }
        
        if 0 <= indexPath.section && indexPath.section < items1.count {
            
        }
    }
    
    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 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 < items2.count {
            let item = items2[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 == items2.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 ?? []
                items2.append(newItem)
                
            } else { // 如果操作的当前批次不是最后一批 需要更新后面几批的选中状态
                
                let nextGroupIndex = groupLevel+1
                let newMember = currentMember.copy() as! YHHKMemberModel
                newMember.isSelected = true
                if 0 <= groupLevel, groupLevel < items2.count {
                    let item = items2[nextGroupIndex]
                    if var members = item.model?.arr {
                        members.append(newMember)
                        item.model?.arr = members
                    }
                }
            }
        } else { // 如果操作是选中
            
            // 肯定会有下一层因为之前取消过
            let nextGroupIndex = groupLevel+1
            if 0 <= nextGroupIndex, nextGroupIndex < items2.count {
                for i in nextGroupIndex..<items2.count {
                    let item = items2[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 < items2.count {
            var i = nextGroupIndex
            while i < items2.count {
                let item = items2[i]
                if let members = item.model?.arr {
                    let a = members.filter {
                       return $0.isSelected == true
                    }
                    // 数组中全未选
                    if a.count <= 0 {
                        items2.remove(at: i)
                        
                    } else {
                        i += 1
                    }
                }
            }
        }
        refreshData()
    }
}

