<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="80px">
          #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)
                      #if (!$column.primaryKey)## 忽略主键，不用在表单里
                        <el-form-item label="${comment}" prop="${javaField}">
                          <el-input v-model="form.${javaField}" placeholder="请输入${comment}" />
                        </el-form-item>
                      #end
                  #elseif($column.htmlType == "imageUpload")## 图片上传
                      #set ($hasImageUploadColumn = true)
                    <el-form-item label="${comment}">
                      <imageUpload v-model="form.${javaField}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "fileUpload")## 文件上传
                      #set ($hasFileUploadColumn = true)
                    <el-form-item label="${comment}">
                      <fileUpload v-model="form.${javaField}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "editor")## 文本编辑器
                      #set ($hasEditorColumn = true)
                    <el-form-item label="${comment}">
                      <editor v-model="form.${javaField}" :min-height="192"/>
                    </el-form-item>
                  #elseif($column.htmlType == "select")## 下拉框
                    <el-form-item label="${comment}" prop="${javaField}">
                      <el-select v-model="form.${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="form.${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="form.${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="form.${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="form.${javaField}" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                  #end
              #end
          #end
      </el-form>
        ## 特殊：主子表专属逻辑
        #if ( $subTables && $subTables.size() > 0 )
          <!-- 子表的表单 -->
          <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 ( $subTables && $subTables.size() > 0 )
  #foreach ($subSimpleClassName in $subSimpleClassNames)
  import ${subSimpleClassName}Form from './components/${subSimpleClassName}Form.vue'
  #end
  #end
  export default {
    name: "${simpleClassName}",
    components: {
        #if ($hasImageUploadColumn)
          ImageUpload,
        #end
        #if ($hasFileUploadColumn)
          FileUpload,
        #end
        #if ($hasEditorColumn)
          Editor,
        #end
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          Treeselect,
        #end
        ## 特殊：主子表专属逻辑
        #if ( $subTables && $subTables.size() > 0 )
        #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 ( $subTables && $subTables.size() > 0 )
            /** 子表的表单 */
             subTabsName: '$subClassNameVars.get(0)'
          #end
      };
    },
    methods: {
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          /** 转换${table.classComment}数据结构 */
          normalizer(node) {
            if (node.children && !node.children.length) {
              delete node.children;
            }
            return {
              id: node.id,
              label: node.name,
              children: node.children
            };
          },
        #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");
      },
      /** 打开弹窗 */
     open(id) {
        this.dialogVisible = true;
        this.reset();
        const that = this;
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            ${simpleClassName}Api.get${simpleClassName}(id).then(res=>{
              that.formData = res.data;
              that.title = "修改${table.classComment}";
            })
          } finally {
            this.formLoading = false;
          }
        }
        this.title = "新增${table.classComment}";
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
            this.get${simpleClassName}Tree()
        #end
      },
        ## 特殊：树表专属逻辑
        #if ( $table.templateType == 2 )
          /** 获得${table.classComment}树 */
          get${simpleClassName}Tree() {
            const that = this;
            that.${classNameVar}Tree = [];
            ${simpleClassName}Api.get${simpleClassName}List().then(res=>{
              const root = { id: 0, name: '顶级${table.classComment}', children: [] };
              root.children = this.handleTree(res.data, 'id', '${treeParentColumn.javaField}')
              that.${classNameVar}Tree.push(root)
            });
          },
        #end

      /** 提交按钮 */
      submitForm() {
        this.formLoading = true;
        try {
          let data = this.formData;
## 特殊：主子表专属逻辑
#if ( $subTables && $subTables.size() > 0 )
          // 需要校验的表单 ref
          const validFormRefArr = [
              #foreach ($subTable in $subTables)
                  #set ($index = $foreach.count - 1)
                  #set ($subClassNameVar = $subClassNameVars.get($index))
                "${subClassNameVar}FormRef",
              #end
          ];

          const validArr = []; // 校验
          const that = this;
          validFormRefArr.forEach((item, index) => {
            validArr.push(new Promise((resolve, reject) => {
              that.getRef(item).validate(valid => {
                if (valid){ // 校验成功
                  resolve()
                }else {
                  reject(item.replace("FormRef","")) // 校验失败返回对应的表单
                }
              })
            }))})
          Promise.all(validArr).then(() => {
            // 全部校验通过-拼接子表的数据
            // 拼接子表的数据
              #foreach ($subTable in $subTables)
                  #set ($index = $foreach.count - 1)
                  #set ($subClassNameVar = $subClassNameVars.get($index))
                data.${subClassNameVar}#if ( $subTable.subJoinMany)s#end = that.getRef(${subClassNameVar}FormRef).getData()
              #end
          }).catch((err)=>{
            that.subTabsName = err
          })
#end

        this.getRef("formRef").validate(valid => {
          if (!valid) {
            return;
          }
          // 修改的提交
          if (data.${primaryColumn.javaField}) {
            ${simpleClassName}Api.update${simpleClassName}(data).then(response => {
              this.#[[$modal]]#.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.#[[$]]#emit('success');
            });
            return;
          }
          // 添加的提交
          ${simpleClassName}Api.create${simpleClassName}(data).then(response => {
            this.#[[$modal]]#.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.#[[$]]#emit('success');
          });
        });
        }finally {
          this.formLoading = false
        }
      },
      getRef(refName){
        this.#[[$]]#refs[refName]
      }
    }
  };
</script>
