<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 flex-1">
            <div class="flex">
                <el-button type="primary" @click="handleAddItem({ uid: getNonDuplicateID(4), minute: '', rate: '' })">添加退单时间节点</el-button>
                <el-button :disabled="isDisabledDel" @click="handleBatchDelete">批量删除</el-button>
            </div>
            <div class="text-danger text-lg my-2 font-bold">提示：扣款比例范围在0-100%，最多保留2位小数</div>
            <div class="mt-3">
                <el-table
                    size="large"
                    ref="tableDataRef"
                    :data="tableList"
                    :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="250">
                        <template #default="{ row }">
                            <div class="flex items-center gap-[8px]">
                                上门时间前
                                <el-input class="flex-1" v-positiveNumber 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>
                                <!-- v-precision="{ minRow: 0, maxRow: 100, $index: scope.$index, update: updateFn }" -->
                                <el-input
                                    v-model.trim="scope.row.rate"
                                    placeholder="请输入"
                                    @input="(value: any) => handleInput(value, scope.$index)"
                                    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] 2xl:w-2/5 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="rate" label="扣款比例">
                        <template #default="{ row }">
                            <span class="strong">{{ row.rate }}</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 { unref } from 'vue'
import type { ElTable } from 'element-plus'
import FooterBtns from '@/components/footer-btns/index.vue'
import { useSettingRule } from '@/hooks/useSettingRule'
import { usePaging } from '@/hooks/usePaging'
import { TemplateEnum } from '@/enums/modeEnum'
import { apiOrderRule, apiRuleList } from '@/api/master_worker'
import feedback from '@/utils/feedback'
import { getNonDuplicateID } from '@/utils/util'

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

const router = useRouter()
const route = useRoute()

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

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

/**表格选中 */
const handleSelectionChange = (row: any) => {
    selectTableList.value = row
}
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].rate = ''
    } else if (zeroReg.test(value)) {
        tableList.value[index].rate = value.replace(zeroReg, '$1')
    } else if (precisionReg.test(value)) {
        tableList.value[index].rate = value.replace(precisionReg, '$1')
    } else if (_reg3.test(value)) {
        tableList.value[index].rate = value.replace(_reg3, '')
    }

    const parsedValue = parseFloat(value)
    if (isNaN(parsedValue) || parsedValue < 0) {
        tableList.value[index].rate = ''
    } else if (parsedValue > 100) {
        tableList.value[index].rate = '0'
    }
}

/**保存退单规则模板 */
const handleSubmitTemplate = async () => {
    try {
        const hasEmpty = unref(tableList).some(i => i.minute === '' || i.rate === '')
        if (hasEmpty) return feedback.msgWarning('上门时间和扣款比例不能为空。不需要的配置请删除！')
        const data = {
            type: TemplateEnum.USER,
            goodsId: route.query.id,
            cancelOrderConfigList: unref(tableList).map(item => ({
                intervalTime: item.minute,
                value: item.rate
            }))
        }
        await apiOrderRule(data)
        feedback.msgSuccess('用户退单规则订制成功')
        router.back()
    } catch (error) {}
}

const { pager, getLists, resetPage, resetParams } = usePaging({
    size: 9999,
    fetchFun: apiRuleList,
    params: {
        type: TemplateEnum.USER,
        goodsId: route.query.id
    }
})
/**映射规则 */
function mappingRuleList() {
    if (!pager.lists.length) return
    tableList.value = pager.lists.map(item => ({
        uid: item.id,
        minute: item.intervalTime,
        rate: item.value
    }))
}
// /**使用输入法后更新绑定数值 */
// function updateFn($index: number, value: any) {
//     tableList.value[$index].rate = value
// }

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

watch(
    () => pager.lists,
    () => mappingRuleList()
)
</script>

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

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