<template>
    <el-card shadow="never" class="!border-none">
        <el-page-header :content="id ? '编辑分销' : '新增分销'" @back="$router.back()" />
    </el-card>
    <el-form ref="formRef" :model="formData" label-width="230px" :rules="formRules">
        <el-card shadow="never" style="margin-top: 15px" class="!border-none">
            <el-form-item label="绑定用户成为分销商" prop="userId">
                <user-select
                    btn-text="选择用户"
                    type="primary"
                    v-model="formData.userId"
                    :userVo="formData.userVo"
                    :id="id"
                    :api="apiUnBindingDistributor"
                    v-model:userMobile="formData.contact"
                />
            </el-form-item>
            <el-form-item label="分销员名称" prop="name">
                <el-input
                    class="w-56 ls-input"
                    v-model="formData.name"
                    placeholder="请输入分销员名称"
                    clearable
                    :maxlength="100"
                />
            </el-form-item>
            <el-form-item label="ID号" prop="distNum" v-if="id">
                <el-input
                    :disabled="isDisabled"
                    class="w-56 ls-input"
                    v-model="formData.distNum"
                    placeholder="请输入分销员ID"
                    clearable
                    :maxlength="100"
                />
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
                <el-input
                    class="w-56 ls-input"
                    v-model="formData.contact"
                    placeholder="请输入手机号"
                    clearable
                    :maxlength="100"
                />
            </el-form-item>
            <el-form-item label="分销码有效期" prop="validStartTime">
                <el-date-picker
                    v-model="formData.validStartTime"
                    type="date"
                    placeholder="开始日期"
                    value-format="YYYY-MM-DD"
                    :disabled="id ? true : false"
                />
                <el-date-picker
                    v-model="formData.validEndTime"
                    type="date"
                    placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    :disabled-date="setDisabledDate"
                />
            </el-form-item>
            <el-form-item label="用户信息绑定分销员ID有效期" prop="bindingTime">
                <el-input
                    class="w-56 ls-input"
                    v-model.number="formData.bindingTime"
                    placeholder="请输入有效期天数"
                >
                    <template #append>天</template>
                </el-input>
            </el-form-item>
            <el-form-item label="组别" prop="groupId">
                <el-select class="w-[280px]" v-model="formData.groupId" placeholder="请选择组别">
                    <el-option
                        v-for="option in groupData"
                        :key="option.id"
                        :label="option.groupName"
                        :value="option.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="分销状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio v-for="option in status" :label="option.value">
                        {{ option.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="分销抽佣比" prop="commissionRate">
                <el-input
                    class="w-56 ls-input"
                    v-model="formData.commissionRate"
                    placeholder="请输入分销抽佣比"
                    clearable
                    max="20"
                >
                    <template #append>%</template>
                </el-input>
            </el-form-item>
        </el-card>
    </el-form>
    <footer-btns>
        <el-button type="primary" @click="onSubmit">保存</el-button>
    </footer-btns>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import UserSelect from '@/components/user-select/index.vue'
import { useRequest } from '@/hooks/useFetchData'
import {
    apiDistributorAdd,
    apiDistributorDetail,
    apiDistributorEdit,
    apiUnBindingDistributor
} from '@/api/distributor/lists'
import { toast } from '@/utils/util'
import { validateContact, validateCommissionRate, validateEffectTime } from '@/utils/validate'
import type { DistributorGroup } from '@/api/distributor/group'
import { apiDistributorGroupLists } from '@/api/distributor/group'

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

const id: any = route.query.id

const status = [
    { label: '正常', value: 1 },
    { label: '停用', value: 0 }
]

const formRef = ref<FormInstance>()

const formData = reactive<Record<string, any>>({
    name: '',
    distNum: '',
    contact: '',
    bindingTime: 100,
    status: 1,
    groupId: '',
    commissionRate: '',
    userId: null,
    userVo: {},
    validStartTime: '',
    validEndTime: ''
})
const isDisabled = computed(() => (id ? true : false))

const formRules = {
    name: { required: true, message: '请输入分销员名称', trigger: 'blur' },
    distNum: { required: true, message: '请输入分销员ID', trigger: 'blur' },
    validStartTime: [
        { required: true, message: '请选择日期', trigger: 'change' },
        {
            validator: (...args) => validateEffectTime(args, formData),
            trigger: 'blur'
        }
    ],
    bindingTime: { required: true, message: '请输入有效期天数', trigger: 'blur' },
    groupId: { required: true, message: '请选择组别', trigger: 'change' },
    contact: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validateContact, trigger: 'blur' }
    ],
    commissionRate: [
        { required: true, message: '请输入分销抽佣比', trigger: 'blur' },
        { validator: (...args) => validateCommissionRate(args, '分销'), trigger: 'blur' }
    ],
    userId: { required: true, message: '请选择用户', trigger: 'blur' }
}

/**保存 */
const onSubmit = () => {
    formRef.value?.validate(async valid => {
        if (!valid) return
        // 校验通过
        const { runFn } = useRequest({
            apiFn: !id ? apiDistributorAdd : apiDistributorEdit,
            onSuccess: res => {
                router.back()
                toast('操作成功', 'success')
            },
            onError: err => {}
        })
        runFn(formData)
    })
}

onMounted(() => {
    if (id) getDetail()
    getGroupList()
})

/**获取详情 */
const getDetail = async () => {
    const data = await apiDistributorDetail({ id })
    setFormData(data)
}

function setFormData(data: any) {
    for (const key in formData) {
        formData[key] = data[key]
    }
}

const groupData = ref<DistributorGroup[]>([])
// 获取分类通用列表
const getGroupList = (): void => {
    let pageNo = 1
    async function request() {
        const res = await apiDistributorGroupLists({ pageNo, pageSize: 60 })
        groupData.value.push(...res.lists)
        if (groupData.value.length < res.count) {
            pageNo++
            request()
        }
    }
    request()
}
const setDisabledDate = (date: Date) => {
    return date.getTime() < Date.now() - 8.64e7
}
defineExpose({
    setFormData,
    getDetail
})
</script>

<style scoped>
:deep(.el-date-editor.el-input) {
    width: auto;
    margin-right: 10px;
}
</style>
