<template>
    <el-card class="!border-none" shadow="never">
        <el-page-header content="退单时间节点" @back="$router.back()" />
    </el-card>

    <div class="mt-3 lg:flex justify-between bg-white p-5">
        <div class="left min-w-0 w-[840px]">
            <div class="flex">
                <el-button type="primary"
                    @click="handleAddItem({ uid: getNonDuplicateID(4), minute: '', score: '' })">添加退单时间节点</el-button>
                <el-button :disabled="isDisabledDel" @click="handleBatchDelete">批量删除</el-button>
            </div>
            <div class="text-danger text-lg my-2 font-bold">提示：扣分范围在0-5分，最多保留2位小数。</div>
            <div class="mt-3">
                <el-table size="large" ref="tableDataRef" :data="tableList" :fit="true" row-key="id"
                    @selection-change="handleSelectionChange" border style="width: 840px">
                    <el-table-column type="selection" max-width="55" />
                    <el-table-column property="timeDesc" label="时间节点" min-width="250">
                        <template #default="{ row }">
                            <div class="flex items-center gap-[8px]">
                                上门时间前
                                <el-input v-positiveNumber class="flex-1" v-model.number="row.minute" placeholder="请输入"
                                    :maxlength="4" clearable>
                                    <template #append>分钟以内</template>
                                </el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="timeDesc" label="扣分" min-width="150">
                        <template #default="scope">
                            <div>
                                <el-input
                                    @input="(value: any) => handleInput(value, scope.$index, { minRow: 1, maxRow: 5, field: 'score' })"
                                    v-model.trim="scope.row.score" placeholder="请输入" clearable>
                                    <template #append>分</template>
                                </el-input>
                            </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="handleDelete(scope)">删除</el-link>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="right ml-6 lg:pt-[42px] flex-1 2xl:hot-search-phone 2xl:mr-5">
            <span class="mb-4 ml-24">- 预览图 -</span>
            <div v-if="tableList.length > 0" class="hot-search-phone-content overflow-y-scroll overflow-x-hidden w-80">
                <el-table :data="tableList" style="width: 100%">
                    <el-table-column prop="minute" label="上门服务时间" width="180">
                        <template #default="{ row }">
                            <span class="strong">{{ row.minute }}</span>
                            分钟以内
                        </template>
                    </el-table-column>
                    <el-table-column prop="score" label="扣分">
                        <template #default="{ row }">
                            <span class="strong">{{ row.score }}</span>
                            分
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>

    <footer-btns>
        <el-button type="primary" @click="handleSubmitTemplate()">保存</el-button>
    </footer-btns>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { ElTable } from 'element-plus'
import FooterBtns from '@/components/footer-btns/index.vue'
import { usePaging } from '@/hooks/usePaging'
import { useSettingRule } from '@/hooks/useSettingRule'
import { apiOrderRule, apiRuleList } from '@/api/master_worker'
import { getNonDuplicateID } from '@/utils/util'
import feedback from '@/utils/feedback'
import { TemplateEnum } from '@/enums/modeEnum'
import { ElMessage } from 'element-plus'

const router = useRouter()

const isDisabledDel = computed(() => !unref(selectTableList).length)

const { pager, getLists, resetPage, resetParams } = usePaging({
    size: 9999,
    fetchFun: apiRuleList,
    params: {
        type: TemplateEnum.STAFF
    }
})

/**表格选中 */
const handleSelectionChange = (row: any) => {
    selectTableList.value = row
}

interface Item {
    uid?: string
    minute: number | string
    score: number | string
}

const {
    tableList, selectTableList, tableDataRef,
    handleAddItem, handleBatchDelete, handleDelete,
    initDropTable
} = useSettingRule<Item>()

/**保存退单规则模板 */
const handleSubmitTemplate = async () => {
    try {
        const hasEmpty = unref(tableList).some(i => i.minute === '' || i.score === '')
        if (hasEmpty) return ElMessage({ type: 'warning', message: '上门时间和扣分不能为空。不需要的配置请删除！', duration: 5000 })
        const data = {
            type: TemplateEnum.STAFF,
            cancelOrderConfigList: unref(tableList).map(item => ({
                intervalTime: item.minute,
                value: item.score
            }))
        }
        await apiOrderRule(data)
        feedback.msgSuccess('师傅退单规则订制成功')
        router.back()
    } catch (error) { }
}
// /**使用输入法后更新绑定数值 */
// function updateFn($index: number, value: any) {
//     tableList.value[$index].score = value
// }
const handleInput = (value: string, index: any) => {
    const _reg = /[^\d.]/g //移除特殊字符
    const zeroReg = /^0+(\d+)/ //连续输入多个0
    const precisionReg = /(\.\d\d)\d+$/ //最多保留2位小数
    const _reg3 = /(\.\d*\.)/g //连续输入多个小数点，只保留一个

    if (_reg.test(value)) {
        tableList.value[index].score = ''
    } else if (zeroReg.test(value)) {
        tableList.value[index].score = value.replace(zeroReg, '$1')
    } else if (precisionReg.test(value)) {
        tableList.value[index].score = value.replace(precisionReg, '$1')
    } else if (_reg3.test(value)) {
        tableList.value[index].score = value.replace(_reg3, '')
    }

    const parsedValue = parseFloat(value)
    if (isNaN(parsedValue) || parsedValue < 0) {
        tableList.value[index].score = ''
    } else if (parsedValue > 5) {
        tableList.value[index].score = '0'
    }
}
/**复选框是否禁用 */
// function _checkSelected(row: any) {
//     return !(!row.minute.toString().trim().length || !row.score.toString().trim())
// }

/**映射规则 */
function mappingRuleList() {
    if (!pager.lists.length) return
    tableList.value = pager.lists.map(item => ({
        uid: item.id,
        minute: item.intervalTime,
        score: item.value
    }))
    // selectTableList.value = tableList.value
    // tableDataRef.value?.toggleAllSelection()
}

onMounted(async () => {
    await getLists()
    initDropTable()
})

// watch(
//     () => unref(tableList),
//     () => {
//         unref(tableList).forEach(item => {
//             _checkSelected(item)
//         })
//     },
//     { deep: true }
// )
watch(
    () => pager.lists,
    () => mappingRuleList()
)
</script>

<style lang="scss" scoped>
.right {
    .strong {
        color: #f56c6c;
    }
}

.left {
    .error {
        color: #f56c6c;
        font-size: 12px;
    }
}
</style>
