<template>
    <div class="noflex">
        <div>
            <div class="flex">
                <el-button type="primary" @click="addItem">添加时间段</el-button>

                <el-button
                    @click="btnDelete('multiple', selectionData)"
                    :disabled="!selectionData.length"
                >
                    批量删除
                </el-button>
            </div>
            <div class="text-danger text-lg my-2 font-bold">提示：可通过拖拽改变时间段的行排序</div>
            <div class="mt-2">
                <el-table
                    size="large"
                    ref="tableDataRef"
                    :data="dataList"
                    :row-class-name="getRowIndex"
                    :fit="true"
                    style="width: 840px"
                    row-key="id"
                    @selection-change="handleSelectionChange"
                    border
                >
                    <el-table-column type="selection" max-width="55" />
                    <el-table-column property="timeDesc" label="时间段" min-width="360">
                        <template #default="{ row }">
                            <div class="flex">
                                <el-time-select
                                    v-model="row.startTime"
                                    :max-time="row.endTime"
                                    class="mr-2"
                                    placeholder="开始时间"
                                    start="00:00"
                                    step="00:30"
                                    end="24:00"
                                />
                                <el-time-select
                                    v-model="row.endTime"
                                    :min-time="row.startTime"
                                    placeholder="结束时间"
                                    start="00:00"
                                    step="00:30"
                                    end="24:00"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="110" fixed="right">
                        <template #default="scope">
                            <div class="flex leading-4">
                                <el-link
                                    class="ml-2"
                                    type="danger"
                                    :underline="false"
                                    @click="btnDelete('single', scope.row)"
                                >
                                    删除
                                </el-link>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, type PropType } from 'vue'
import {
    apiGetOrderTime,
    apiSetOrderTime,
    apiOrderTimeLists,
    apiOrderTimeDel
} from '@/api/service/subscribe'
import { apiServiceLists } from '@/api/service/lists'
import feedback from '@/utils/feedback'
import Sortable from 'sortablejs'

const props = defineProps({
    orderTimeList: Object as PropType<any>
})
interface ListItem {
    startTime: string
    endTime: string
}
let dataList = ref<ListItem[]>([])

const getRowIndex = ({ row, rowIndex }: { row: any; rowIndex: string }): string => {
    return (row.row_index = rowIndex)
}

const tableDataRef = ref()
let sortableObj: any = null
const initDropTable = () => {
    if (tableDataRef.value) {
        const el = tableDataRef.value.$el.querySelector('.el-table__body tbody')
        sortableObj = Sortable.create(el, {
            handle: '.el-table__row',
            onEnd: ({ newIndex, oldIndex }: { newIndex: number; oldIndex: number }) => {
                const arr = dataList.value
                const currRow = arr.splice(oldIndex, 1)[0]
                arr.splice(newIndex, 0, currRow)
                dataList.value = []
                nextTick(() => {
                    dataList.value = arr
                })
            }
        })
    }
}

// 选中的服务项目
const selectionData = ref<number[]>([])
// 表格多选选择的数据
const handleSelectionChange = (val: Event | any) => {
    selectionData.value = val
}

// 添加时间段
const addItem = () => {
    dataList.value.push({
        startTime: '',
        endTime: ''
    })
}
// 删除处理 / 批量删除
const btnDelete = async (type: string, obj?: any) => {
    obj = Array.isArray(obj) ? obj : [obj]
    for (let len = dataList.value.length, i = len - 1; i >= 0; i--) {
        const item = obj.find(m => m.row_index == i)
        if (item) dataList.value.splice(i, 1)
    }
    tableDataRef.value?.clearSelection()
}

watch(
    () => props.orderTimeList,
    val => {
        //第一次进来页面回显编辑的数据
        if (sortableObj) return
        if (val && val.orderTimeList?.length != 0) {
            dataList.value = val.orderTimeList
            nextTick(() => {
                initDropTable()
            })
        }
    },
    {
        deep: true,
        immediate: true
    }
)

const emit = defineEmits(['update:orderTimeList'])
watch(
    dataList.value,
    val => {
        emit('update:orderTimeList', {
            orderTimeList: val,
            serviceTime: '',
            endTime: '',
            intervalTime: '',
            startTime: ''
        })
    },
    {
        immediate: true,
        deep: true
    }
)
</script>
<style scoped lang="scss">
.noflex :deep() .el-form-item__content {
    display: block;
}
</style>
