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

import UIKit
import AttributedString
import SwifterSwift

// 之前从未分过批的情况 可用此VC
// 之前单人或多人一批的情况 需要编辑时 可用此VC

class YHResignAppointTimeViewController: YHBaseViewController {

    var isUpdate: Bool = false // 是否是编辑已有信息
    // 订单ID
    var orderId: Int = 0
    // 批次ID
    var renewalId: Int = 0

    // 所有预约人员
    var allAppointUsers = [YHResignAppointMember]() {
        didSet {
            
            self.updateUI()
        }
    }
    // 预约在港递交时间
    var defaultSubmitTime: String = ""
    // 预计离港时间
    var defaultLeaveHKTime: String = ""
    
    let viewModel = YHResignAppointViewModel()
    // 申请人是否在港
    var togetherArr: [YHResignAppointTogetherSetting] = []
    // 是否一起在港递交
    lazy var togetherSetting = {
        let model = YHResignAppointTogetherSetting()
        model.is_together = 1
        return model
    }()

    // 分组信息
    var selectGroupArr: [YHResignAppointTimeSettingModel] = []
    // 是否单人
    private var isOnyOne: Bool {
        get {
            return allAppointUsers.count <= 1
        }
    }

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style:.grouped)
        if #available(iOS 15.0, *) {
           tableView.sectionHeaderTopPadding = 0.0
        }
        tableView.estimatedSectionHeaderHeight = 0.1
        tableView.estimatedSectionFooterHeight = 0.1
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHResignAppointOptionCell.self, forCellReuseIdentifier: YHResignAppointOptionCell.cellReuseIdentifier)
        tableView.register(YHResignAppointOptionResultCell.self, forCellReuseIdentifier: YHResignAppointOptionResultCell.cellReuseIdentifier)
        tableView.register(YHResignAppointTimeSingleCell.self, forCellReuseIdentifier: YHResignAppointTimeSingleCell.cellReuseIdentifier)
        tableView.register(YHResignAppointTimeMultipleCell.self, forCellReuseIdentifier: YHResignAppointTimeMultipleCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var tipsBtn: UIButton = {
        let button = UIButton()
        button.setTitle("递交提示", for: .normal)
        button.titleLabel?.font = .PFSC_R(ofSize: 11)
        button.setTitleColor(UIColor.mainTextColor, for: .normal)
        button.setImage(UIImage(named: "resign_appoint_tips_btn"), for: .normal)
        button.centerTextAndImage(imageAboveText: true, spacing: 0.0)
        button.addTarget(self, action: #selector(didTipsBtnClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var submitBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认提交", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        btn.addTarget(self, action: #selector(didSubmitBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(tipsBtn)
        view.addSubview(submitBtn)
        tipsBtn.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.width.equalTo(44)
            make.height.equalTo(48)
            make.centerY.equalTo(submitBtn)
        }
        submitBtn.snp.makeConstraints { make in
            make.left.equalTo(tipsBtn.snp.right).offset(22)
            make.right.equalTo(-20)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "预约在港递交时间"
        self.gk_navigationBar.backgroundColor = .white
        self.view.backgroundColor = .init(hex: 0xF8F9FB)
        self.view.addSubview(tableView)
        self.view.addSubview(bottomView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+16)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
        self.updateUI()
    }
    
    @objc func didTipsBtnClicked() {
        YHResignAppointSubmitTipsView.alertView().show()
    }
    
    func updateUI() {
        
        togetherArr.removeAll()
        selectGroupArr.removeAll()
        
        if isOnyOne { // 只有一个人
            // togetherArr 不放元素 则不展示是否一起递交cell
            let model1 = YHResignAppointTimeSettingModel()
            model1.ready_to_submit_at = defaultSubmitTime
            model1.leave_hk_at = defaultLeaveHKTime
            model1.notleaveHK = defaultLeaveHKTime.isEmpty && self.isUpdate
            let users = allAppointUsers.deepCopy().map {
                let item = $0
                item.isSelected = true
                return item
            }
            model1.users = users
            model1.isShowUsers = false
            selectGroupArr.append(model1)
            self.tableView.reloadData()
            return
        }
        
        // 有多人
        // 默认一起递交数据
        togetherArr.append(self.togetherSetting)
        // 分组数据
        let model1 = YHResignAppointTimeSettingModel()
        model1.isShowUsers = true
        model1.ready_to_submit_at = defaultSubmitTime
        model1.leave_hk_at = defaultLeaveHKTime
        model1.notleaveHK = defaultLeaveHKTime.isEmpty && self.isUpdate
        let users = allAppointUsers.deepCopy().map {
            let item = $0
            item.isSelected = true
            return item
        }
        model1.users = users
        if self.togetherSetting.is_together == 2 { // 不一起递交 需显示候选人列表
            model1.isShowUsers = true
        } else {
            model1.isShowUsers = false
        }
        selectGroupArr.append(model1)
        self.tableView.reloadData()
    }
    
    // memberId 申请人id
    // select 点击选择
    // groupLevel 是分的第几组 从0开始计数
    func selectMember(_ currentMember: YHResignAppointMember, select:Bool, groupLevel:Int) {
        
        // 获取当前批的成员组
        var currentMembers:[YHResignAppointMember] = []
        
        // 先改变点击当前批的选择状态
        if 0 <= groupLevel, groupLevel < selectGroupArr.count {
            let item = selectGroupArr[groupLevel]
            let members = item.users
            currentMembers = members
            for member in members {
                if member.id == currentMember.id {
                    member.isSelected = select
                }
            }
        }
        
        if !select { // 如果操作是取消
            // 如果操作的当前批次是最后一批，则需要分新批次
            if groupLevel == selectGroupArr.count-1 {
                // 进行分批
                let newItem = YHResignAppointTimeSettingModel()
                newItem.isShowUsers = true
                // 批次+1
                newItem.itemIndex = groupLevel+1
                // 找出上一批未选中的人
                let needMembers = currentMembers.filter {
                    return $0.isSelected == false
                }
                // 在下一批中默认全选中
                let nextMembers = needMembers.deepCopy().map {
                    let item = $0
                    item.isSelected = true
                    return item
                }
                newItem.users = nextMembers
                selectGroupArr.append(newItem)
                
            } else { // 如果操作的当前批次不是最后一批 需要更新后面几批的选中状态
                
                let nextGroupIndex = groupLevel+1
                let newMember = currentMember.copy() as! YHResignAppointMember
                newMember.isSelected = true
                if 0 <= groupLevel, groupLevel < selectGroupArr.count {
                    let item = selectGroupArr[nextGroupIndex]
                    var members = item.users
                    members.append(newMember)
                    item.users = members
                }
            }
        } else { // 如果操作是选中
            
            // 肯定会有下一层因为之前取消过
            let nextGroupIndex = groupLevel+1
            if 0 <= nextGroupIndex, nextGroupIndex < selectGroupArr.count {
                for i in nextGroupIndex..<selectGroupArr.count {
                    let item = selectGroupArr[i]
                    var members = item.users
                    // 下几批的组员中都要删除该人
                    members = members.filter { $0.id != currentMember.id }
                    item.users = members
                }
            }
        }
        
        //  无论是选中还是反选 检测下面所有批次有无全未选数组，有则删除该批
        let nextGroupIndex = groupLevel+1
        if 0 <= nextGroupIndex, nextGroupIndex < selectGroupArr.count {
            var i = nextGroupIndex
            while i < selectGroupArr.count {
                let item = selectGroupArr[i]
                let members = item.users
                let a = members.filter {
                   return $0.isSelected == true
                }
                // 数组中全未选
                if a.count <= 0 {
                    selectGroupArr.remove(at: i)
                    
                } else {
                    i += 1
                }
            }
        }
        
        // 重新进行批次排号
        for (index, group) in selectGroupArr.enumerated() {
            group.itemIndex = index
        }
        self.tableView.reloadData()
    }
    
    
    @objc func didSubmitBtnClicked() {
        
        // 判断是否有分组没有选择时间
        var isNoSelectTime = false
        for group in self.selectGroupArr {
            group.isClickSubmit = true
            var noSeletTime = false
            if group.notleaveHK {
                noSeletTime = group.ready_to_submit_at.isEmpty
            } else {
                noSeletTime = (group.ready_to_submit_at.isEmpty || group.leave_hk_at.isEmpty)
            }
            if noSeletTime {
                isNoSelectTime = true
            }
        }
        
        if isNoSelectTime { // 有分组没有选择时间
            self.tableView.reloadData()
            return
        }
        
        requestSubmit()
    }
    
    func requestSubmit() {
        
        var batchs: [[String : Any]] = []
        for group in self.selectGroupArr {
            group.isClickSubmit = false
            if !group.isShowUsers { // 说明是一起递交
                let allUserInfoArr = allAppointUsers.map {
                    let dict = ["member_id" : "\($0.id)"]
                    return dict
                }
                let dict = ["ready_to_submit_at" : group.getSubmitHKTime(),
                            "leave_hk_at" : group.notleaveHK ? "" : group.getLeaveHKTime(),
                            "users" : allUserInfoArr] as! [String : Any]
                batchs.append(dict)
                
                if allAppointUsers.count <= 0 {
                    // 人员列表不可为空
                    YHHUD.flash(message: "预约人员列表不可为空")
                    return
                }
                
            } else { // 说明是分批递交
                let selectUser = group.users.filter {
                    let item = $0
                    return item.isSelected
                }
                let allUserInfoArr = selectUser.map {
                    let dict = ["member_id" : "\($0.id)"]
                    return dict
                }
                let dict = ["ready_to_submit_at" : group.getSubmitHKTime(),
                            "leave_hk_at" : group.notleaveHK ? "" : group.getLeaveHKTime(),
                            "users" : allUserInfoArr] as! [String : Any]
                batchs.append(dict)
                if allUserInfoArr.count <= 0 {
                    // 人员列表不可为空
                    YHHUD.flash(message: "预约人员列表不可为空")
                    return
                }
            }
        }
        
        let param: [String : Any] = ["renewal_id" :  renewalId,
                                     "is_together" : (self.isOnyOne ? 0 : self.togetherSetting.is_together),
                                     "batch" : batchs]
        printLog(param)
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.submitAppointInfo(params: param) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if success {
                if self.isUpdate { // 是行程修改
                    YHHUD.flash(message: "提交成功")
                    self.navigationController?.popViewController(animated: true)
                    return
                }
                // 是首次预约 需要刷新展示行程安排列表
                NotificationCenter.default.post(name: YhConstant.YhNotification.didUpdateResignAppointStatusList, object: nil)
                return
            }
            let msg = error?.errorMsg ?? "提交失败"
            YHHUD.flash(message: msg)
        }
    }
}

extension YHResignAppointTimeViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 { // 是否一起在港递交的section
            return togetherArr.count
        }
        // 分组section
        return selectGroupArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 { // 是否一起在港递交的cell
            if self.togetherSetting.isCanEdit {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHResignAppointOptionCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointOptionCell
                if self.togetherSetting.is_together == 1 {
                    cell.isSelectTogether = true
                    
                } else if self.togetherSetting.is_together == 2 {
                    cell.isSelectTogether = false
                    
                } else {
                    cell.isSelectTogether = nil
                }
                cell.selectBlock = {
                   [weak self] index in
                    guard let self = self else { return }
                    // index == 1 表示否
                    self.togetherSetting.is_together = (index == 1 ? 2 : 1)
                    self.updateUI()
                }
                return cell
            }
            // 不能编辑是否一起递交 只展示
            let cell1 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointOptionResultCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointOptionResultCell
            cell1.isTogether = (self.togetherSetting.is_together == 1)
            return cell1
        }
        
        // 时间选择cell
        if 0 <= indexPath.row && indexPath.row < selectGroupArr.count {
            let model = selectGroupArr[indexPath.row]
            if !model.isShowUsers || self.togetherSetting.is_together == 1 { // 不分组选择cell
                let cell2 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointTimeSingleCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointTimeSingleCell
                cell2.updateModel(model)
                cell2.switchBlock = {
                    [weak self] isOn in
                    guard let self = self else { return }
                    model.notleaveHK = isOn
                    self.tableView.reloadData()
                }
                cell2.refreshBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    self.tableView.reloadData()
                }
                return cell2
            }
            // 分组选择cell
            let cell3 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointTimeMultipleCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointTimeMultipleCell
            cell3.updateModel(model)
            cell3.selectUserBlock = {
               [weak self] member, isSelect, groupIndex in
                guard let self = self else { return }
                self.selectMember(member, select: isSelect, groupLevel: groupIndex)
            }
            cell3.switchBlock = {
                [weak self] isOn in
                guard let self = self else { return }
                model.notleaveHK = isOn
                self.tableView.reloadData()
            }
            cell3.refreshBlock = {
                [weak self] in
                guard let self = self else { return }
                self.tableView.reloadData()
            }
            return cell3
        }
        
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
}
