<template>
    <div class="edit-view">
        <page-title>
            <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
            <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
                删除
            </el-button>
            <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
        </page-title>
        <div class="edit-view__content-wrapper">
            <div class="edit-view__content-section">
                <el-form :model="formData" :rules="rules" ref="form" label-width="${labelWidth}" label-position="right"
                         size="small"
                         style="max-width: 500px;">
                    <#list model.fields as field>
                        <el-form-item prop="${field.modelName}" label="${field.remark}">
                            <#if field.showInForm>
                                <#if field.formType == 'singleLineText'>
                                    <el-input v-model="formData.${field.modelName}"></el-input>
                                <#elseif field.formType == 'textarea'>
                                    <el-input type="textarea" v-model="formData.${field.modelName}"></el-input>
                                <#elseif field.formType == 'number'>
                                    <el-input-number type="number" v-model="formData.${field.modelName}"></el-input-number>
                                <#elseif field.formType == 'date'>
                                    <el-date-picker
                                            v-model="formData.${field.modelName}"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择日期">
                                    </el-date-picker>
                                <#elseif field.formType == 'datetime'>
                                    <el-date-picker
                                            v-model="formData.${field.modelName}"
                                            type="datetime"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            placeholder="选择日期时间">
                                    </el-date-picker>
                                <#elseif field.formType == 'select'>
                                    <el-select v-model="formData.${field.modelName}" clearable filterable placeholder="请选择">
                                        <el-option
                                                v-for="item in ${field.modelName}Options"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                <#elseif field.formType == 'multiSelect'>
                                    <template>
                                        <el-select v-model="formData.${field.modelName}" multiple clearable filterable
                                                   placeholder="请选择">
                                            <el-option
                                                    v-for="item in ${field.modelName}Options"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </template>
                                <#elseif field.formType == 'singleImage'>
                                    <single-upload v-model="formData.${field.modelName}"></single-upload>
                                <#elseif field.formType == 'multiImage'>
                                    <multi-upload v-model="formData.${field.modelName}"></multi-upload>
                                <#elseif field.formType == 'fileUpload'>
                                    <el-upload
                                            class="upload-demo"
                                            action="../upload/file"
                                            :on-change="handleChange"
                                            :file-list="fileList3">
                                        <el-button size="small" type="primary">
                                            点击上传
                                        </el-button>
                                    </el-upload>
                                <#elseif field.formType == 'tree'>
                                    <el-tree
                                            :props="props"
                                            :load="loadNode"
                                            lazy
                                            show-checkbox
                                            @check-change="handleCheckChange">
                                    </el-tree>
                                <#elseif field.formType == 'switch'>
                                    <el-switch v-model="formData.${field.modelName}"></el-switch>
                                <#elseif field.formType == 'richText'>
                                    <rich-text v-model="formData.${field.modelName}"></rich-text>
                                <#elseif field.formType == 'loginName'>
                                    <el-input v-model="formData.${field.modelName}" disabled></el-input>
                                <#elseif field.formType == 'currentTime'>
                                    <el-input v-model="formData.${field.modelName}" disabled></el-input>
                                <#elseif field.formType == 'currentDate'>
                                    <el-input v-model="formData.${field.modelName}" disabled></el-input>
                                <#else>
                                    <el-input v-model="formData.${field.modelName}"></el-input>
                                </#if>
                            </#if>
                        </el-form-item>
                    </#list>
                    <#--<el-form-item class="form-submit">
                        <el-button @click="onSave" :loading="saving" type="primary">
                            保存
                        </el-button>
                        <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
                            删除
                        </el-button>
                        <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
                    </el-form-item>-->
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        name: '${model.className}Edit',
        created() {
            if (this.$route.query.id) {
                this.$http
                    .get('${model.className?uncap_first}/get/' + ${r'this.$route.query.id'})
                    .then(res => {
                        <#list model.fields as field>
                        <#if field.formType == 'multiSelect'>
                        if (res.${field.modelName}) {
                            res.${field.modelName} = res.${field.modelName}.split(',');
                        } else {
                            res.${field.modelName} = [];
                        }
                        </#if>
                        </#list>
                        this.formData = res;
                    })
                    .catch(e => {
                        console.log(e);
                        this.$message.error(e.error);
                    });
            }
            <#list model.fields as field>
            <#if (field.formType == 'select' || field.formType == 'multiSelect') && field.apiFlag == '2'>
            this.$http.post('${field.optionsMethod}', {size: 1000, query: {del: false}}).then(res => {
                if (res.content.length > 0) {
                    res.content.forEach(item => {
                        this.${field.modelName}Options.push({
                            label: item.${field.optionsLabel},
                            value: item.${field.optionsValue}<#if field.formType == 'multiSelect'> + ''</#if>
                        });
                    })
                }
            }).catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
            </#if>
            </#list>
        },
        data() {
            return {
                saving: false,
                formData: {
                    <#list model.fields as field>
                    <#if field.formType == 'loginName'>
                    ${field.modelName}: '',
                    </#if>
                    </#list>
                },
                rules: {
                    <#list model.fields as field>
                    <#if field.required!false == true || field.validate!false == true>
                    ${field.modelName}: [
                        <#if field.required!false == true>
                        {
                            required: true,
                            message: '请输入${field.remark!field.modelName}',
                            trigger: 'blur'
                        },
                        </#if>
                        <#if field.validate!false == true>
                        <#if field.maxLength?? && field.minLength??>
                        {
                            min: ${field.minLength},
                            max: ${field.maxLength},
                            message: '长度在 ${field.minLength} 到 ${field.maxLength} 个字符',
                            trigger: 'blur'
                        },
                        </#if>
                        <#if field.min?? && field.max??>
                        {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (value <= ${field.max} && value >= ${field.min}) {
                                        callback();
                                    } else {
                                        callback(new Error('值在 ${field.min} 到 ${field.max} 之间'));
                                    }
                                }
                            }, trigger: 'blur'
                        },
                        </#if>
                        <#if field.validatorType == 'phone'>
                        {
                            pattern: /^1[3-9]\d{9}$/,
                            message: "请输入正确的手机号",
                            trigger: "blur"
                        },
                        </#if>
                        <#if field.validatorType == 'number'>
                        {
                            type: "number",
                            message: "输入有误",
                            trigger: "blur"
                        },
                        </#if>
                        <#if field.validatorType == 'url'>
                        {
                            pattern: /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/,
                            message: "请输入正确的URL",
                            trigger: "blur"
                        },
                        </#if>
                        <#if field.validatorType == 'email'>
                        {
                            type: "email",
                            message: "请输入正确的邮箱地址",
                            trigger: "blur"
                        },
                        </#if>
                        <#if field.validatorType == 'id'>
                        {
                            pattern: /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/,
                            message: "请输入正确的身份证号码",
                            trigger: "blur"
                        },
                        </#if>
                        <#if field.validatorType == 'english'>
                        {
                            pattern: /^[A-Za-z].+$/,
                            message: "输入有误",
                            trigger: "blur"
                        },
                        </#if>
                        </#if>
                    ],
                    </#if>
                    </#list>
                },
                <#list model.fields as field>
                <#if (field.formType == 'select' || field.formType=='multiSelect')>
                <#if (field.apiFlag == '2' || field.apiFlag == '3')>
                ${field.modelName}Options: [],
                <#else>
                ${field.modelName}Options: ${field.optionsValue},
                </#if>
                </#if>
                </#list>
            }
        },
        methods: {
            onSave() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.submit();
                    } else {
                        return false;
                    }
                });
            },
            submit() {
                let data = {...this.formData};

                <#list model.fields as field>
                <#if field.formType == 'currentTime"||${field.formType}=="currentDate'>
                if (data.${field.modelName}) {
                    data.${field.modelName} = Date.parse(new Date(data.${field.modelName}));
                }
                </#if>
                </#list>
                this.saving = true;
                this.$http
                    .post('/${model.className?uncap_first}/save', data, {body: 'json'})
                    .then(res => {
                        this.saving = false;
                        this.$message.success('成功');
                        this.$router.go(-1);
                    })
                    .catch(e => {
                        console.log(e);
                        this.saving = false;
                        this.$message.error(e.error);
                    });
            },
            onDelete() {
                this.$alert('删除将无法恢复，确认要删除么？', '警告', {type: 'error'}).then(() => {
                    return this.$http.post(`/${model.className?uncap_first}/del/${r'${this.formData.id}'}`)
                }).then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                }).catch(e => {
                    if (e !== 'cancel') {
                        console.log(e);
                        this.$message.error((e || {}).error || '删除失败');
                    }
                })
            },
        }
    }
</script>
<style lang="less" scoped></style>
