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

import UIKit
import AttributedString
import SwifterSwift

class YHResignAppointTimeModifyViewController: YHBaseViewController {

    var renewalId: Int = 0
    var oneGroupTimeSetting = YHResignAppointTimeSettingModel()
    var selectGroupArr: [YHResignAppointTimeSettingModel] = []
    // 所有未预约人员
    var allAppointUsers: [YHResignAppointMember] = []
    var isCanEditTogether: Bool = false
    let viewModel = YHResignAppointViewModel()
    
    // 是否一起在港递交
    var isTogether: Bool = false
    
    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(YHResignAppointOptionCell.self, forCellReuseIdentifier: YHResignAppointOptionCell.cellReuseIdentifier)
        tableView.register(YHResignAppointOptionResultCell.self, forCellReuseIdentifier: YHResignAppointOptionResultCell.cellReuseIdentifier)
        tableView.register(YHResignHaveAppointedApplicantsInfoCell.self, forCellReuseIdentifier: YHResignHaveAppointedApplicantsInfoCell.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)
        }
        
        if let firstUser = self.allAppointUsers.first {
            let users = allAppointUsers.deepCopy().map {
                let item = $0
                item.isSelected = true
                return item
            }
            oneGroupTimeSetting.users = users
            oneGroupTimeSetting.isShowUsers = false
        }
        self.tableView.reloadData()
    }
    
    @objc func didTipsBtnClicked() {
        YHResignAppointSubmitTipsView.alertView().show()
    }
    
    
}

extension YHResignAppointTimeModifyViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 { // 是否一起在港递交的section
            return 1
        }
        // 分组section
        if self.isTogether {
            return 1
        }
        return selectGroupArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            // 不能编辑是否一起递交 只展示
            if !self.isCanEditTogether {
                let cell1 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointOptionResultCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointOptionResultCell
                cell1.isTogether = self.isTogether
                return cell1
            }
            // 可编辑是否一起递交
            let cell = tableView.dequeueReusableCell(withIdentifier: YHResignAppointOptionCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointOptionCell
            cell.isSelectTogether = self.isTogether
            cell.selectBlock = {
               [weak self] index in
                guard let self = self else { return }
                // index == 1 表示否
                self.isTogether = (index == 1 ? false : true)
                self.tableView.reloadData()
            }
            return cell
        }
        
        if self.isTogether { // 选择是一起递交
            let cell2 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointTimeSingleCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointTimeSingleCell
            cell2.updateModel(self.oneGroupTimeSetting)
            cell2.switchBlock = {
                [weak self] isOn in
                guard let self = self else { return }
                self.oneGroupTimeSetting.notleaveHK = isOn
                self.tableView.reloadData()
            }
            cell2.refreshBlock = {
                [weak self] in
                guard let self = self else { return }
                self.tableView.reloadData()
            }
            return cell2
        }
                
        if 0 <= indexPath.row && indexPath.row < selectGroupArr.count {
            let model = selectGroupArr[indexPath.row]
            if model.isHaveAppointed { // 已确认在港 只展示信息
                let cell1 = tableView.dequeueReusableCell(withIdentifier: YHResignHaveAppointedApplicantsInfoCell.cellReuseIdentifier, for: indexPath) as! YHResignHaveAppointedApplicantsInfoCell
                cell1.updateModel(model)
                return cell1
            }
            
            // 分批次cell
            let cell1 = tableView.dequeueReusableCell(withIdentifier: YHResignAppointTimeMultipleCell.cellReuseIdentifier, for: indexPath) as! YHResignAppointTimeMultipleCell
            cell1.updateModel(model)
            cell1.selectUserBlock = {
               [weak self] member, isSelect, groupIndex in
                guard let self = self else { return }
                self.selectMember(member, select: isSelect, groupLevel: groupIndex)
            }
            cell1.switchBlock = {
                [weak self] isOn in
                guard let self = self else { return }
                model.notleaveHK = isOn
                self.tableView.reloadData()
            }
            cell1.refreshBlock = {
                [weak self] in
                guard let self = self else { return }
                self.tableView.reloadData()
            }
            return cell1
        }
        
        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) {
        
        if 0 <= indexPath.row && indexPath.row < selectGroupArr.count {
            let model = selectGroupArr[indexPath.row]
            
        }
    }
    
    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
    }
}

extension YHResignAppointTimeModifyViewController {
    
    // 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 { // 如果操作的当前批次不是最后一批 需要更新当前批次的下一批该用户的选中状态
                
                var nextGroupIndex = groupLevel+1
                let newMember = currentMember.copy() as! YHResignAppointMember
                newMember.isSelected = true
                while 0 <= nextGroupIndex, nextGroupIndex < selectGroupArr.count {
                    let item = selectGroupArr[nextGroupIndex]
                    if !item.isHaveAppointed { // 不是已确认在港
                        var members = item.users
                        members.append(newMember)
                        item.users = members
                        break
                    }
                    nextGroupIndex += 1
                }
                
                if nextGroupIndex == selectGroupArr.count { // 在现有列表没有找到下一批可以操作的批次 则需要分一个新批次
                    // 进行分批
                    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
            if 0 <= nextGroupIndex, nextGroupIndex < selectGroupArr.count {
                for i in nextGroupIndex..<selectGroupArr.count {
                    let item = selectGroupArr[i]
                    if !item.isHaveAppointed { // 不是已确认在港
                        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 !item.isHaveAppointed { // 不是已确认在港
                    if a.count <= 0 {
                        selectGroupArr.remove(at: i)
                        
                    } else {
                        i += 1
                    }
                } else { // 已确认在港 不能编辑直接跳过
                    i += 1
                }
            }
        }
        
        // 重新进行批次排号
        for (index, group) in selectGroupArr.enumerated() {
            group.itemIndex = index
        }
        self.tableView.reloadData()
    }
    
    @objc func didSubmitBtnClicked() {
        
        // 判断所有组是否有选择时间
        var isNoSelectTime = false

        if self.isTogether { // 选择一起递交
            self.oneGroupTimeSetting.isClickSubmit = true
            var noSeletTime = false
            if self.oneGroupTimeSetting.notleaveHK {
                noSeletTime = self.oneGroupTimeSetting.ready_to_submit_at.isEmpty
            } else {
                noSeletTime = (self.oneGroupTimeSetting.ready_to_submit_at.isEmpty || self.oneGroupTimeSetting.leave_hk_at.isEmpty)
            }
            if noSeletTime {
                self.tableView.reloadData()
                YHHUD.flash(message: "未选择时间")
                return
            }
            
        } else { // 非一起递交
            
            for group in self.selectGroupArr {
                if !group.isHaveAppointed {
                    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()
                YHHUD.flash(message: "有分批未选择时间")
                return
            }
        }
        requestSubmit()
    }
    
    func requestSubmit() {
        
        var batchs: [[String : Any]] = []
        
        if self.isTogether {
            let allUserInfoArr = self.allAppointUsers.map {
                let dict = ["member_id" : "\($0.id)"]
                return dict
            }
            let dict = ["ready_to_submit_at" : self.oneGroupTimeSetting.getSubmitHKTime(),
                        "leave_hk_at" : self.oneGroupTimeSetting.notleaveHK ? "" : self.oneGroupTimeSetting.getLeaveHKTime(),
                        "users" : allUserInfoArr] as! [String : Any]
            batchs.append(dict)
            
        } else {
            for group in self.selectGroupArr {
                group.isClickSubmit = false
                if !group.isHaveAppointed { // 非已确认在港 才加入集合
                    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)
                }
            }
        }
        
        
        
        let param: [String : Any] = ["renewal_id" :  renewalId,
                                     "is_together" : self.isTogether ? 1 : 2,
                                     "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 {
                YHHUD.flash(message: "提交成功")
                self.navigationController?.popViewController(animated: true)
                return
            }
            let msg = error?.errorMsg ?? "提交失败"
            YHHUD.flash(message: msg)
        }
    }
}
