<template>
    <el-card shadow="never" class="!border-none">
        <el-page-header
            :content="id ? '编辑服务时间模板' : '新增服务时间模板'"
            @back="$router.back()"
        />
    </el-card>
    <el-card shadow="never" class="mt-4">
        <div class="lg:flex justify-between">
            <div class="min-w-0 flex-1">
                <el-form :model="formData" ref="formRef" label-width="auto" :rules="rules">
                    <div class="flex items-baseline flex-wrap">
                        <el-form-item label="可提前预约" prop="time" class="mr-7">
                            <div>
                                <el-input
                                    class="w-56 ls-input"
                                    v-model.number="formData.time"
                                    placeholder="请输入"
                                    maxlength="5"
                                >
                                    <template #append>天</template>
                                </el-input>
                                <div class="text-gray-400 form-tips">
                                    用户可以提前预约的天数，默认7天
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="服务名称" prop="name">
                            <el-input
                                class="w-56 ls-input"
                                v-model="formData.name"
                                placeholder="请输入"
                                maxlength="64"
                            ></el-input>
                        </el-form-item>
                    </div>
                    <el-tabs v-model="activeName">
                        <el-tab-pane
                            :label="item.name"
                            :name="item.value"
                            v-for="(item, index) in tabList"
                            :key="index"
                            :disabled="!!id"
                        >
                            <component
                                :is="componentId"
                                v-model:orderTimeList="componentData"
                                :ref="setComponentRef"
                            ></component>
                        </el-tab-pane>
                    </el-tabs>
                </el-form>
            </div>

            <div class="ml-6 lg:pt-[115px] 2xl:w-1/5 2xl:hot-search-phone 2xl:mr-5">
                <span class="mb-4 ml-24">- 预览图 -</span>
                <div class="hot-search-phone-content overflow-y-scroll overflow-x-hidden">
                    <!-- 热门搜索 -->
                    <div class="hot-search-text">
                        <span
                            class="item"
                            v-for="(text, index) in formData.orderTimeList"
                            :key="index"
                        >
                            {{ text?.startTime + '-' + text?.endTime }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </el-card>

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

<script lang="ts" setup>
import { apiGetGoodsTimeDetail, apiAddGoodsTime, apiEditGoodsTime } from '@/api/service/subscribe'
import { ref, toRaw, watch } from 'vue'
import FooterBtns from '@/components/footer-btns/index.vue'
import feedback from '@/utils/feedback'
import Customization from './components/customization.vue'
import AutomaticInterval from './components/automatic-interval.vue'
import type { FormRules } from 'element-plus'
import { validateGoodsTime } from '@/utils/validate'
const router = useRouter()
const route = useRoute()
const id: any = route.query.id

const formData = ref<any>({
    time: '7',
    name: '',
    orderTimeList: [],
    serviceTime: '',
    endTime: '',
    intervalTime: '',
    startTime: ''
})

// 子组件的数据
const componentData = ref<any>({
    orderTimeList: [],
    serviceTime: '',
    endTime: '',
    intervalTime: '',
    startTime: ''
})
watch(
    () => componentData.value,
    val => {
        formData.value.orderTimeList = val?.orderTimeList
        formData.value.serviceTime = val?.serviceTime
        formData.value.intervalTime = val?.intervalTime
        formData.value.startTime = val?.startTime
        formData.value.endTime = val?.endTime
    }
)

// 表单验证
const rules = reactive<FormRules>({
    time: [
        { required: true, trigger: 'blur', message: '请输入可提前预约天数' },
        { validator: (...args) => validateGoodsTime(args), trigger: 'blur' }
    ],
    name: { required: true, trigger: 'blur', message: '请输入服务名称' }
})

// 获取预约详情
const getOrderTime = async (): Promise<void> => {
    const data = await apiGetGoodsTimeDetail({ id })
    const formKeys = Object.keys(formData.value)
    formKeys.map(key => {
        formData.value[key] = data[key]
    })
    activeName.value = data.type
    const keys = Object.keys(componentData.value)
    keys.map(key => {
        componentData.value[key] = data[key]
    })
}

const formRef = ref()
const componentRef = ref()
const setComponentRef = el => {
    componentRef.value = el
}

const goodTimeAdd = async () => {
    await apiAddGoodsTime({
        ...formData.value,
        type: activeName.value
    })
    feedback.msgSuccess('操作成功')
    router.back()
}
const goodsTimeEdit = async () => {
    await apiEditGoodsTime({
        ...formData.value,
        type: activeName.value,
        id
    })
    feedback.msgSuccess('操作成功')
    router.back()
}
// 保存
const onSubmit = async (): Promise<void> => {
    await formRef.value?.validate()
    if (activeName.value == 1) await componentRef.value?.validateData()
    if (timeNotValid()) return feedback.msgError('时间段不能为空！')
    if (!id) goodTimeAdd()
    else goodsTimeEdit()
}

const timeNotValid = () => {
    return (
        formData.value.orderTimeList.length == 0 ||
        formData.value.orderTimeList.some(item => !item.startTime || !item.endTime)
    )
}

const tabList = [
    {
        name: '自定义时间段',
        value: 0,
        ref: 'customRef'
    },
    {
        name: '自动设置时间段',
        value: 1,
        ref: 'autoRef'
    }
]
const activeName = ref(tabList[0].value)
const componentId = computed(() => {
    return activeName.value == 0 ? Customization : AutomaticInterval
})

onMounted(async () => {
    id && getOrderTime()
})
</script>

<style lang="scss" scoped>
.ls-input {
    width: 223px;
}

.noflex :deep() .el-form-item__content {
    display: block;
}

.hot-search-phone {
    &-content {
        @apply grid grid-cols-2;
        width: 280px;
        height: 494px;
        padding: 10px 10px;
        border-radius: 10px;
        border: 1px solid #e6e6e6;

        .hot-search-text {
            @apply flex flex-wrap grid grid-cols-2 w-[250px] h-4;
            span {
                @apply flex-1 text-center;
                font-size: 12px;
                border-radius: 5px;
                border: 1px solid #e6e6e6;
                margin: 0 6px 6px 0;
                display: inline-block;
                background-color: #fff;
                height: 30px;
                line-height: 30px;
            }
        }
    }
}
</style>
