<template>
    <div class="main-container">
        <div class="detail-head">
            <div class="left" @click="back()">
                <span class="iconfont iconxiangzuojiantou !text-xs"></span>
                <span class="ml-[1px]">{{t('returnToPreviousPage')}}</span>
            </div>
            <span class="adorn">|</span>
            <span class="right">{{ pageName }}</span>
        </div>
        <el-card class="box-card !border-none" shadow="never">
            <el-form :model="formData" label-width="90px" ref="formRef" :rules="formRules" class="page-form">
                <el-form-item :label="t('studentPhone')" prop="student_phone">
                    <el-input v-model="formData.student_phone" clearable :placeholder="t('studentPhonePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('studentName')" prop="student_name">
                    <el-input v-model="formData.student_name" clearable :placeholder="t('studentNamePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('sex')" prop="sex">
                    <el-select class="input-width"  v-model="formData.sex" clearable :placeholder="t('sexPlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in sexList"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('age')" prop="age">
                    <el-input-number v-model="formData.age" clearable :placeholder="t('agePlaceholder')"  class="input-width"  :min = "0" max = "300" />
                </el-form-item>
                
                <el-form-item :label="t('schoolName')" prop="school_name">
                    <el-input v-model="formData.school_name" clearable :placeholder="t('schoolNamePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('grade')" >
                    <el-input v-model="formData.grade" clearable :placeholder="t('gradePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('className')" >
                    <el-input v-model="formData.class_name" clearable :placeholder="t('classNamePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('sourceChannel')" prop="source_channel">
                    <el-select class="input-width"  v-model="formData.source_channel" clearable :placeholder="t('sourceChannelPlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in source_channelList"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('customerSource')" prop="customer_source">
                    <el-select class="input-width"  v-model="formData.customer_source" clearable :placeholder="t('customerSourcePlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in customer_sourceList"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('addStaffId')" prop="add_staff_id">
                    <el-select class="input-width" v-model="formData.add_staff_id" clearable :placeholder="t('addStaffIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in addStaffIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('getStaffId')" >
                    <el-select class="input-width" v-model="formData.get_staff_id" clearable :placeholder="t('getStaffIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in getStaffIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('contactName')" prop="contact_name">
                    <el-input v-model="formData.contact_name" clearable :placeholder="t('contactNamePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('provinceId')" >
                    <el-select class="input-width" v-model="formData.province_id" clearable :placeholder="t('provinceIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in provinceIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('cityId')" >
                    <el-select class="input-width" v-model="formData.city_id" clearable :placeholder="t('cityIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in cityIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('districtId')" >
                    <el-select class="input-width" v-model="formData.district_id" clearable :placeholder="t('districtIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in districtIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('communityName')" >
                    <el-input v-model="formData.community_name" clearable :placeholder="t('communityNamePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('customerTags')" >
                    <el-checkbox-group v-model="formData.customer_tags" :placeholder="t('customerTagsPlaceholder')">
                        <el-checkbox
                            v-for="(item, index) in customer_tagsList"
                                :key="index"
                                :label="item.value">
                           {{ item.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                

            </el-form>
        </el-card>
         <div class="fixed-footer-wrap">
            <div class="fixed-footer">
                <el-button type="primary" @click="onSave(formRef)">{{ t('save') }}</el-button>
                <el-button @click="back()">{{ t('cancel') }}</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { t } from '@/lang'
import { useDictionary } from '@/app/api/dict'
import type { FormInstance } from 'element-plus'
import { getSalesInfo,addSales,editSales, getWithStaffList, getWithStaffList, getWithSysAreaList, getWithSysAreaList, getWithSysAreaList } from '@/addon/zhjw/api/sales';
import { useRoute } from 'vue-router'

const route = useRoute()
const id:number = parseInt(route.query.id);
const loading = ref(false)
const pageName = route.meta.title



/**
 * 表单数据
 */
const initialFormData = {
    id: 0,
    student_phone: '',
    student_name: '',
    sex: '',
    age: '',
    school_name: '',
    grade: '',
    class_name: '',
    source_channel: '',
    customer_source: '',
    add_staff_id: '',
    get_staff_id: '',
    contact_name: '',
    province_id: '',
    city_id: '',
    district_id: '',
    community_name: '',
    customer_tags: '',

}
const formData: Record<string, any> = reactive({ ...initialFormData })

const setFormData = async (id:number = 0) => {
    Object.assign(formData, initialFormData)
    const data = await (await getSalesInfo(id)).data
    Object.keys(formData).forEach((key: string) => {
        if (data[key] != undefined) formData[key] = data[key]
    })
}
if(id) setFormData(id);

const formRef = ref<FormInstance>()
// 选中数据
const selectData = ref<any[]>([])

// 字典数据
    let sexList = ref([])
    const sexDictList = async () => {
    sexList.value = await (await useDictionary('users_sex')).data.dictionary
    }
    sexDictList();
    watch(() => sexList.value, () => { formData.sex = sexList.value[0].value })
    let source_channelList = ref([])
    const source_channelDictList = async () => {
    source_channelList.value = await (await useDictionary('source_channel')).data.dictionary
    }
    source_channelDictList();
    watch(() => source_channelList.value, () => { formData.source_channel = source_channelList.value[0].value })
    let customer_sourceList = ref([])
    const customer_sourceDictList = async () => {
    customer_sourceList.value = await (await useDictionary('customer_source')).data.dictionary
    }
    customer_sourceDictList();
    watch(() => customer_sourceList.value, () => { formData.customer_source = customer_sourceList.value[0].value })
    let customer_tagsList = ref([])
    const customer_tagsDictList = async () => {
    customer_tagsList.value = await (await useDictionary('customer_tags')).data.dictionary
    }
    customer_tagsDictList();


    
    const addStaffIdList = ref([] as any[])
    const setAddStaffIdList = async () => {
    addStaffIdList.value = await (await getWithStaffList({})).data
    }
    setAddStaffIdList()
    const getStaffIdList = ref([] as any[])
    const setGetStaffIdList = async () => {
    getStaffIdList.value = await (await getWithStaffList({})).data
    }
    setGetStaffIdList()
    const provinceIdList = ref([] as any[])
    const setProvinceIdList = async () => {
    provinceIdList.value = await (await getWithSysAreaList({})).data
    }
    setProvinceIdList()
    const cityIdList = ref([] as any[])
    const setCityIdList = async () => {
    cityIdList.value = await (await getWithSysAreaList({})).data
    }
    setCityIdList()
    const districtIdList = ref([] as any[])
    const setDistrictIdList = async () => {
    districtIdList.value = await (await getWithSysAreaList({})).data
    }
    setDistrictIdList()
// 表单验证规则
const formRules = computed(() => {
    return {
    student_phone: [
        { required: true, message: t('studentPhonePlaceholder'), trigger: 'blur' },
        
    ]
,
    student_name: [
        { required: true, message: t('studentNamePlaceholder'), trigger: 'blur' },
        
    ]
,
    sex: [
        { required: true, message: t('sexPlaceholder'), trigger: 'blur' },
        
    ]
,
    age: [
        { required: true, message: t('agePlaceholder'), trigger: 'blur' },
        { validator: (rule: any, value: string, callback: any) => {  if (value && !/^\d{0,300}$/.test(value)) { callback(new Error(t('generateBetween')))} else { callback() }}},
    ]
,
    school_name: [
        { required: true, message: t('schoolNamePlaceholder'), trigger: 'blur' },
        
    ]
,
    grade: [
        { required: true, message: t('gradePlaceholder'), trigger: 'blur' },
        
    ]
,
    class_name: [
        { required: true, message: t('classNamePlaceholder'), trigger: 'blur' },
        
    ]
,
    source_channel: [
        { required: true, message: t('sourceChannelPlaceholder'), trigger: 'blur' },
        
    ]
,
    customer_source: [
        { required: true, message: t('customerSourcePlaceholder'), trigger: 'blur' },
        
    ]
,
    add_staff_id: [
        { required: true, message: t('addStaffIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    get_staff_id: [
        { required: true, message: t('getStaffIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    contact_name: [
        { required: true, message: t('contactNamePlaceholder'), trigger: 'blur' },
        
    ]
,
    province_id: [
        { required: true, message: t('provinceIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    city_id: [
        { required: true, message: t('cityIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    district_id: [
        { required: true, message: t('districtIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    community_name: [
        { required: true, message: t('communityNamePlaceholder'), trigger: 'blur' },
        
    ]
,
    customer_tags: [
        { required: true, message: t('customerTagsPlaceholder'), trigger: 'blur' },
        
    ]
,
    }
})

const onSave = async (formEl: FormInstance | undefined) => {
    if (loading.value || !formEl) return
    await formEl.validate(async (valid) => {
       if (valid) {
           loading.value = true
           let data = formData

           const save = id ? editSales : addSales
           save(data).then(res => {
               loading.value = false
               history.back()
           }).catch(err => {
               loading.value = false
           })

       }
    })
}

// 验证手机号格式
const mobileVerify = (rule: any, value: any, callback: any) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error(t('generateMobile')))
    } else {
        callback()
    }
}

// 验证身份证号
const idCardVerify = (rule: any, value: any, callback: any) => {
    if (value && !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)) {
        callback(new Error(t('generateIdCard')))
    } else {
        callback()
    }
}

// 验证邮箱号
const emailVerify = (rule: any, value: any, callback: any) => {
    if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
        callback(new Error(t('generateEmail')))
    } else {
        callback()
    }
}


// 验证请输入整数
const numberVerify = (rule: any, value: any, callback: any) => {
    if (!Number.isInteger(value)) {
        callback(new Error(t('generateNumber')))
    } else {
        callback()
    }
}
const back = () => {
    history.back()
}
</script>

<style lang="scss" scoped></style>
