<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
          #foreach($column in $columns)
              #if ($column.createOperation || $column.updateOperation)
                  #set ($dictType = $column.dictType)
                  #set ($javaField = $column.javaField)
                  #set ($AttrName = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
                  #set ($comment = $column.columnComment)
                  #if ( $table.templateType == 2 && $column.id == $treeParentColumn.id )
                    <el-form-item label="${comment}" prop="${javaField}">
                      <TreeSelect
                        v-model="formData.${javaField}"
                        :options="${classNameVar}Tree"
                        :normalizer="normalizer"
                        placeholder="请选择${comment}"
                      />
                    </el-form-item>
                  #elseif ($column.htmlType == "input" && !$column.primaryKey)## 忽略主键，不用在表单里
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-input v-model="formData.${javaField}" placeholder="请输入${comment}" />
                    </el-form-item>
                  #elseif($column.htmlType == "imageUpload")## 图片上传
                      #set ($hasImageUploadColumn = true)
                    <el-form-item label="${comment}">
                      <ImageUpload v-model="formData.${javaField}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "fileUpload")## 文件上传
                      #set ($hasFileUploadColumn = true)
                    <el-form-item label="${comment}">
                      <FileUpload v-model="formData.${javaField}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "editor")## 文本编辑器
                      #set ($hasEditorColumn = true)
                    <el-form-item label="${comment}">
                      <Editor v-model="formData.${javaField}" :min-height="192"/>
                    </el-form-item>
                  #elseif($column.htmlType == "select")## 下拉框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-select v-model="formData.${javaField}" placeholder="请选择${comment}">
                          #if ("" != $dictType)## 有数据字典
                            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.$dictType.toUpperCase())"
                                       :key="dict.value" :label="dict.label" #if ($column.javaType == "Integer" || $column.javaType == "Long"):value="parseInt(dict.value)"#else:value="dict.value"#end />
                          #else##没数据字典
                            <el-option label="请选择字典生成" value="" />
                          #end
                      </el-select>
                    </el-form-item>
                  #elseif($column.htmlType == "checkbox")## 多选框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-checkbox-group v-model="formData.${javaField}">
                          #if ("" != $dictType)## 有数据字典
                            <el-checkbox v-for="dict in this.getDictDatas(DICT_TYPE.$dictType.toUpperCase())"
                                         :key="dict.value" #if($column.javaType == "Integer" || $column.javaType == "Long"):label="parseInt(dict.value)"#else:label="dict.value"#end>{{dict.label}}</el-checkbox>
                          #else##没数据字典
                            <el-checkbox>请选择字典生成</el-checkbox>
                          #end
                      </el-checkbox-group>
                    </el-form-item>
                  #elseif($column.htmlType == "radio")## 单选框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-radio-group v-model="formData.${javaField}">
                          #if ("" != $dictType)## 有数据字典
                            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.$dictType.toUpperCase())"
                                      :key="dict.value" #if($column.javaType == "Integer" || $column.javaType == "Long"):label="parseInt(dict.value)"
                                      #else:label="dict.value"#end>{{dict.label}}</el-radio>
                          #else##没数据字典
                            <el-radio label="1">请选择字典生成</el-radio>
                          #end
                      </el-radio-group>
                    </el-form-item>
                  #elseif($column.htmlType == "datetime")## 时间框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-date-picker clearable v-model="formData.${javaField}" type="date" value-format="timestamp" placeholder="选择${comment}" />
                    </el-form-item>
                  #elseif($column.htmlType == "textarea")## 文本框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-input v-model="formData.${javaField}" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                  #end
              #end
          #end
      </el-form>
        ## 特殊：主子表专属逻辑
        #if ( $table.templateType == 10 || $table.templateType == 12 )
          <!-- 子表的表单 -->
          <el-tabs v-model="subTabsName">
              #foreach ($subTable in $subTables)
                  #set ($index = $foreach.count - 1)
                  #set ($subClassNameVar = $subClassNameVars.get($index))
                  #set ($subSimpleClassName = $subSimpleClassNames.get($index))
                  #set ($subJoinColumn_strikeCase = $subJoinColumn_strikeCases.get($index))
                <el-tab-pane label="${subTable.classComment}" name="$subClassNameVar">
                  <${subSimpleClassName}Form ref="${subClassNameVar}FormRef" :${subJoinColumn_strikeCase}="formData.id" />
                </el-tab-pane>
              #end
          </el-tabs>
        #end
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as ${simpleClassName}Api from '@/api/${table.moduleName}/${table.businessName}';
  #if ($hasImageUploadColumn)
  import ImageUpload from '@/components/ImageUpload';
  #end
  #if ($hasFileUploadColumn)
  import FileUpload from '@/components/FileUpload';
  #end
  #if ($hasEditorColumn)
  import Editor from '@/components/Editor';
  #end
  ## 特殊：树表专属逻辑
  #if ( $table.templateType == 2 )
  import TreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  #end
  ## 特殊：主子表专属逻辑
  #if ( $table.templateType == 10 || $table.templateType == 12 )
      #foreach ($subSimpleClassName in $subSimpleClassNames)
      import ${subSimpleClassName}Form from './components/${subSimpleClassName}Form.vue'
      #end
  #end
  export default {
    name: "${simpleClassName}Form",
    components: {
        #if ($hasImageUploadColumn)
          ImageUpload,
        #end
        #if ($hasFileUploadColumn)
          FileUpload,
        #end
        #if ($hasEditorColumn)
          Editor,
        #end
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          TreeSelect,
        #end
        ## 特殊：主子表专属逻辑
        #if ( $table.templateType == 10 || $table.templateType == 12 )
            #foreach ($subSimpleClassName in $subSimpleClassNames)
               ${subSimpleClassName}Form,
            #end
        #end
    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
            #foreach ($column in $columns)
                #if ($column.createOperation || $column.updateOperation)
                    #if ($column.htmlType == "checkbox")
                            $column.javaField: [],
                    #else
                            $column.javaField: undefined,
                    #end
                #end
            #end
        },
        // 表单校验
        formRules: {
            #foreach ($column in $columns)
                #if (($column.createOperation || $column.updateOperation) && !$column.nullable && !${column.primaryKey})## 创建或者更新操作 && 要求非空 && 非主键
                    #set($comment=$column.columnComment)
                        $column.javaField: [{ required: true, message: '${comment}不能为空', trigger: #if($column.htmlType == 'select')'change'#else'blur'#end }],
                #end
            #end
        },
          ## 特殊：树表专属逻辑
          #if ( $table.templateType == 2 )
             ${classNameVar}Tree: [], // 树形结构
          #end
        ## 特殊：主子表专属逻辑
        #if ( $table.templateType == 10 || $table.templateType == 12 )
        #if ( $subTables && $subTables.size() > 0 )
            /** 子表的表单 */
             subTabsName: '$subClassNameVars.get(0)'
        #end
        #end
      };
    },
    methods: {
      /** 打开弹窗 */
     async open(id) {
        this.dialogVisible = true;
        this.reset();
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await ${simpleClassName}Api.get${simpleClassName}(id);
            this.formData = res.data;
            this.title = "修改${table.classComment}";
          } finally {
            this.formLoading = false;
          }
        }
        this.title = "新增${table.classComment}";
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
        await this.get${simpleClassName}Tree();
        #end
      },
      /** 提交按钮 */
      async submitForm() {
        // 校验主表
        await this.$refs["formRef"].validate();
          ## 特殊：主子表专属逻辑
          #if ( $table.templateType == 10 || $table.templateType == 12 )
              #if ( $subTables && $subTables.size() > 0 )
                // 校验子表
                  #foreach ($subTable in $subTables)
                      #set ($index = $foreach.count - 1)
                      #set ($subClassNameVar = $subClassNameVars.get($index))
                    try {
                      ## 代码生成后会替换为正确的 refs
                      await this.refs['${subClassNameVar}FormRef'].validate();
                    } catch (e) {
                      this.subTabsName = '${subClassNameVar}';
                      return;
                    }
                  #end
              #end
          #end
        this.formLoading = true;
        try {
          const data = this.formData;
        ## 特殊：主子表专属逻辑
        #if ( $table.templateType == 10 || $table.templateType == 12 )
        #if ( $subTables && $subTables.size() > 0 )
            // 拼接子表的数据
            #foreach ($subTable in $subTables)
                #set ($index = $foreach.count - 1)
                #set ($subClassNameVar = $subClassNameVars.get($index))
              data.${subClassNameVar}#if ( $subTable.subJoinMany)s#end = this.refs['${subClassNameVar}FormRef'].getData();
            #end
        #end
        #end
          // 修改的提交
          if (data.${primaryColumn.javaField}) {
            await ${simpleClassName}Api.update${simpleClassName}(data);
            this.#[[$modal]]#.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.#[[$]]#emit('success');
            return;
          }
          // 添加的提交
          await ${simpleClassName}Api.create${simpleClassName}(data);
          this.#[[$modal]]#.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.#[[$]]#emit('success');
        } finally {
          this.formLoading = false;
        }
      },
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          /** 获得${table.classComment}树 */
         async get${simpleClassName}Tree() {
            this.${classNameVar}Tree = [];
            const res = await ${simpleClassName}Api.get${simpleClassName}List();
            const root = { id: 0, name: '顶级${table.classComment}', children: [] };
            root.children = this.handleTree(res.data, 'id', '${treeParentColumn.javaField}')
            this.${classNameVar}Tree.push(root)
          },
        #end
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          /** 转换${table.classComment}数据结构 */
          normalizer(node) {
            if (node.children && !node.children.length) {
              delete node.children;
            }
              #if ($treeNameColumn.javaField == "name")
                return {
                  id: node.id,
                  label: node.name,
                  children: node.children
                };
              #else
                return {
                  id: node.id,
                  label: node['$treeNameColumn.javaField'],
                  children: node.children
                };
              #end
          },
        #end
      /** 表单重置 */
      reset() {
        this.formData = {
            #foreach ($column in $columns)
                #if ($column.createOperation || $column.updateOperation)
                    #if ($column.htmlType == "checkbox")
                            $column.javaField: [],
                    #else
                            $column.javaField: undefined,
                    #end
                #end
            #end
        };
        this.resetForm("formRef");
      }
    }
  };
</script>
