<template>
  <div class="view-table-content">
    <div class="view-dataSpecies-left">
      <MenuTree :currentNodeKey="currentNodeKey" nodeKey="id" :treedata="menuTreeData" @TreeNodeclick="treeNodeClick" v-bind="treeObj"> </MenuTree>
    </div>
    <div class="view-dataSpecies-right">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()" :disabled="currentNode && currentNode.type == 0">新增</el-button>
          <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
          <el-button type="primary">导入模板</el-button>
          <el-button type="primary">导出模板</el-button>
        </div>
        <div class="view-dataType-title-search">
          <el-input placeholder="请输入关键字" v-model="keyWord" class="input1">
            <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
          </el-input>
        </div>
      </div>
      <div class="view-dataType-table">
        <LTable ref="table" @selection-change="selection" :defaultFetch="false" :fetch="fetch" :columns="columns" :dataSource="tableData" :options="options" :pagination="tableRequset"></LTable>
      </div>
      <!-- 添加或修改${functionName}对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px">
            #foreach($column in $columns)
              #set($field=$column.javaField)
              #if($column.insert && !$column.pk)
                #if(($column.usableColumn) || (!$column.superColumn))
                  #set($parentheseIndex=$column.columnComment.indexOf("（"))
                  #if($parentheseIndex != -1)
                    #set($comment=$column.columnComment.substring(0, $parentheseIndex))
                  #else
                    #set($comment=$column.columnComment)
                  #end
                  #set($dictType=$column.dictType)
                  #if($column.htmlType == "input")
                    <el-form-item label="${comment}" prop="${field}">
                      <el-input v-model="form.${field}" placeholder="请输入${comment}" />
                    </el-form-item>
                  #elseif($column.htmlType == "imageUpload")
                    <el-form-item label="${comment}" prop="${field}">
                      <image-upload v-model="form.${field}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "fileUpload")
                    <el-form-item label="${comment}" prop="${field}">
                      <file-upload v-model="form.${field}"/>
                    </el-form-item>
                  #elseif($column.htmlType == "editor")
                    <el-form-item label="${comment}">
                      <editor v-model="form.${field}" :min-height="192"/>
                    </el-form-item>
                  #elseif($column.htmlType == "select" && "" != $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-select v-model="form.${field}" placeholder="请选择${comment}">
                        <el-option
                                v-for="dict in ${dictType}"
                                :key="dict.value"
                                :label="dict.label"
                          #if($column.javaType == "Integer" || $column.javaType == "Long")
                                :value="parseInt(dict.value)"
                          #else
                                :value="dict.value"
                          #end
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  #elseif($column.htmlType == "select" && $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-select v-model="form.${field}" placeholder="请选择${comment}">
                        <el-option label="请选择字典生成" value="" />
                      </el-select>
                    </el-form-item>
                  #elseif($column.htmlType == "checkbox" && "" != $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-checkbox-group v-model="form.${field}">
                        <el-checkbox
                                v-for="dict in ${dictType}"
                                :key="dict.value"
                                :label="dict.value">
                          {{dict.label}}
                        </el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  #elseif($column.htmlType == "checkbox" && $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-checkbox-group v-model="form.${field}">
                        <el-checkbox>请选择字典生成</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  #elseif($column.htmlType == "radio" && "" != $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-radio-group v-model="form.${field}">
                        <el-radio
                                v-for="dict in ${dictType}"
                                :key="dict.value"
                          #if($column.javaType == "Integer" || $column.javaType == "Long")
                                :label="parseInt(dict.value)"
                          #else
                                :label="dict.value"
                          #end
                        >{{dict.label}}</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  #elseif($column.htmlType == "radio" && $dictType)
                    <el-form-item label="${comment}" prop="${field}">
                      <el-radio-group v-model="form.${field}">
                        <el-radio label="1">请选择字典生成</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  #elseif($column.htmlType == "datetime")
                    <el-form-item label="${comment}" prop="${field}">
                      <el-date-picker clearable
                                      v-model="form.${field}"
                                      type="date"
                                      value-format="YYYY-MM-DD"
                                      placeholder="请选择${comment}">
                      </el-date-picker>
                    </el-form-item>
                  #elseif($column.htmlType == "textarea")
                    <el-form-item label="${comment}" prop="${field}">
                      <el-input v-model="form.${field}" type="textarea" placeholder="请输入内容" />
                    </el-form-item>
                  #end
                #end
              #end
            #end
            #if($table.sub)
              <el-divider content-position="center">${subTable.functionName}信息</el-divider>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" icon="Plus" @click="handleAdd${subClassName}">添加</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="danger" icon="Delete" @click="handleDelete${subClassName}">删除</el-button>
                </el-col>
              </el-row>
              <el-table :data="${subclassName}List" :row-class-name="row${subClassName}Index" @selection-change="handle${subClassName}SelectionChange" ref="${subclassName}">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="序号" align="center" prop="index" width="50" />
                #foreach($column in $subTable.columns)
                  #set($javaField=$column.javaField)
                  #set($parentheseIndex=$column.columnComment.indexOf("（"))
                  #if($parentheseIndex != -1)
                    #set($comment=$column.columnComment.substring(0, $parentheseIndex))
                  #else
                    #set($comment=$column.columnComment)
                  #end
                  #if($column.pk || $javaField == ${subTableFkclassName})
                  #elseif($column.list && $column.htmlType == "input")
                    <el-table-column label="$comment" prop="${javaField}" width="150">
                      <template #default="scope">
                        <el-input v-model="scope.row.$javaField" placeholder="请输入$comment" />
                      </template>
                    </el-table-column>
                  #elseif($column.list && $column.htmlType == "datetime")
                    <el-table-column label="$comment" prop="${javaField}" width="240">
                      <template #default="scope">
                        <el-date-picker clearable
                                        v-model="scope.row.$javaField"
                                        type="date"
                                        value-format="YYYY-MM-DD"
                                        placeholder="请选择$comment">
                        </el-date-picker>
                      </template>
                    </el-table-column>
                  #elseif($column.list && ($column.htmlType == "select" || $column.htmlType == "radio") && "" != $column.dictType)
                    <el-table-column label="$comment" prop="${javaField}" width="150">
                      <template #default="scope">
                        <el-select v-model="scope.row.$javaField" placeholder="请选择$comment">
                          <el-option
                                  v-for="dict in $column.dictType"
                                  :key="dict.value"
                                  :label="dict.label"
                                  :value="dict.value"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                  #elseif($column.list && ($column.htmlType == "select" || $column.htmlType == "radio") && "" == $column.dictType)
                    <el-table-column label="$comment" prop="${javaField}" width="150">
                      <template #default="scope">
                        <el-select v-model="scope.row.$javaField" placeholder="请选择$comment">
                          <el-option label="请选择字典生成" value="" />
                        </el-select>
                      </template>
                    </el-table-column>
                  #end
                #end
              </el-table>
            #end
          </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { get${BusinessName}, getAircaftTypeAndModelTree, add${BusinessName}, update${BusinessName}, remove${BusinessName} } from '@/api/${moduleName}/${businessName}'
  import { deepClone, debounce } from '@/utils/index'
  export default {
    name: '${BusinessName}',
    components: {},
    data() {
      // 这里存放数据
      return {
        dialogTitle: '新增',
        dialogVisible: false,
        keyWord: '',
        aircaftModelIdList: [],
        currentNodeKey: null,
        currentNode: null,
        menuTreeData: [],
        treeObj: {
          title: '所属机种',
          activityheight: '275px',
          searchIcon: false,
          configure: {
            children: 'children',
            label: 'label'
          }
        },
        typeTree: {
          children: 'children',
          label: 'label'
        },
        searchValue: '',
        columns: [
          #foreach($column in $columns)
            #set($javaField=$column.javaField)
            #set($parentheseIndex=$column.columnComment.indexOf("（"))
            #if($parentheseIndex != -1)
              #set($comment=$column.columnComment.substring(0, $parentheseIndex))
            #else
              #set($comment=$column.columnComment)
            #end
            #if($column.pk)
              { prop: '${javaField}', label: '${comment}' },
            #elseif($column.list && "" != $javaField)
              {
                prop: '${javaField}',
                label: '${comment}'
              },
            #end
          #end
          {
            button: true,
            label: '操作',
            width: '240px',
            group: [
              {
                name: '编辑',
                type: 'text',
                round: false,
                plain: false,
                onClick: (row, index, scope) => {
                  _this.handUpdate(row)
                }
              },
              {
                name: '删除',
                type: 'text',
                round: false,
                plain: false,
                onClick: (row, index, scope) => {
                  _this.remove([row])
                }
              }
            ]
          }
        ],
        options: {
          stripe: true, // 斑马纹
          mutiSelect: true, // 多选框
          index: false, // 显示序号， 多选则 mutiSelect
          loading: false, // 表格动画
          initTable: false, // 是否一挂载就加载数据
          border: true,
          height: 'calc(100vh - 300px)'
        },
        tableCheckItems: [],
        tableData: [],
        tableRequset: {
          total: 0,
          pageIndex: 1,
          pageSize: 10,
          searchValue: ''
        },
        form: {
      #foreach($column in $columns)
        #set($javaField=$column.javaField)
        #set($parentheseIndex=$column.columnComment.indexOf("（"))
        #if($parentheseIndex != -1)
          #set($comment=$column.columnComment.substring(0, $parentheseIndex))
        #else
          #set($comment=$column.columnComment)
        #end
            ${javaField}:'',
      #end
        },
        debounceFn: debounce(this.fetch, 500)
      }
    },
    watch: {
      keyWord() {
        this.tableRequset.pageIndex = 1
        this.debounceFn()
      }
    },
    mounted() {
      this.getAircaftTypeAndModelTreeAPI()
    },
    methods: {
      async getAircaftTypeAndModelTreeAPI(params) {
        const { data } = await getAircaftTypeAndModelTree(params)
        this.menuTreeData = data
        if (data.length) {
          this.currentNodeKey = data[0].value
          this.currentNode = data[0]
          this.aircaftModelIdList = this.getTreeLeafData(data[0]?.children).map((e) => e.id)
          this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
        }
      },

      async remove${BusinessName}API(params) {
        try {
          const { success } = await remove${BusinessName}(params)
          if (success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            await this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
            this.handleClose()
          }
        } catch (error) {}
      },

      getTreeLeafData(list) {
        const newArr = []
        function getLeaf(data, arr) {
          data.forEach((e) => {
            if (e.type === 1) {
              arr.push(e)
            }
            if (e.children.length) {
              getLeaf(e.children, arr)
            }
          })
        }
        getLeaf(list, newArr)
        return newArr
      },

      async get${BusinessName}API(params) {
        if (this.$refs.table) this.$refs.table.clearSelection()
        const { keyWord } = this
        const { pageSize, pageIndex } = this.tableRequset
        const {
          data: { list, totalCount }
        } = await get${BusinessName}({ pageSize, pageIndex, keyWord, ...params })
        this.tableData = list
        this.tableRequset.total = totalCount
      },

      fetch() {
        this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
      },

      searchClick() {
        this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
      },

      async add${BusinessName}API() {
        try {
          delete this.form.aircaftModelName
          const { success } = await add${BusinessName}({ ...this.form })
          if (success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
          }
        } catch (error) {}
      },

      async update${BusinessName}API() {
        try {
          const { success } = await update${BusinessName}({...this.form})
          if (success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
          }
        } catch (error) {}
      },

      treeNodeClick(data) {
        this.$refs.table.clearSelection()
        this.currentNodeKey = data.id
        this.currentNode = data
        this.aircaftModelIdList = this.getTreeLeafData(data.children.length ? data.children : [data]).map((e) => e.id)
        this.get${BusinessName}API({ aircaftModelIdList: this.aircaftModelIdList })
      },

      openDialog() {
        this.dialogTitle = '新增'
        this.dialogVisible = true
        this.form.aircaftModelName = this.currentNode.label
        this.form.aircaftModelId = this.currentNode.id
      },

      handleClose() {
        this.dialogVisible = false
        this.form = {
          #foreach($column in $columns)
            #set($javaField=$column.javaField)
            #set($parentheseIndex=$column.columnComment.indexOf("（"))
            #if($parentheseIndex != -1)
              #set($comment=$column.columnComment.substring(0, $parentheseIndex))
            #else
              #set($comment=$column.columnComment)
            #end
              ${javaField}:'',
          #end
        }
      },

      handUpdate(row) {
        this.dialogTitle = '编辑'
        this.form = deepClone(row)
        this.dialogVisible = true
      },

      submit() {
        switch (this.dialogTitle) {
          case '编辑':
            this.update${BusinessName}API()
            this.handleClose()
            break
          case '新增':
            this.add${BusinessName}API()
            this.handleClose()
            break
        }
      },

      selection(val) {
        this.tableCheckItems = val
      },

      remove(row) {
        this.$confirm('是否删除该机种', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(() => {
              this.remove${BusinessName}API(row.map((e) => e.${pkColumn.javaField}))
            })
            .catch(() => {})
      }
    }
  }
</script>

<style lang="scss">
  @import '../index.scss';
</style>
