<template>
  <div class="app-container my_menu">
    <el-form :inline="true">
      <el-form-item label="操作名">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入操作名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块">
        <el-select v-model="queryParams.visible" placeholder="模块" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button
        type="info"
        plain
        icon="el-icon-sort"
        size="mini"
        @click="toggleExpandAll"
      >展开/折叠</el-button>
    </div>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      :default-expand-all="isExpandAll"
      row-key="Id"
      :tree-props="{children: 'Children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="ModuleTypeValueCN" label="模块" align="left" min-width="230px" />
      <el-table-column prop="OptTypeValueCN" label="操作类型" min-width="120px" />
      <el-table-column prop="ChildrenTypeValueCN" label="操作子类" min-width="120px" show-overflow-tooltip />
      <el-table-column prop="Description" label="操作名称" :show-overflow-tooltip="true" min-width="200px" />
      <el-table-column prop="Code" label="字段名" min-width="120px" :show-overflow-tooltip="true" />
      <el-table-column prop="Value" label="字段英文" min-width="120px" :show-overflow-tooltip="true" />
      <el-table-column prop="ValueCN" label="字段中文" min-width="120px" :show-overflow-tooltip="true" />
      <el-table-column label="启用" align="center" prop="CreateTime" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsEnable" size="success">启用</el-tag>
          <el-tag v-else size="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否使用父数据" align="center" prop="CreateTime" min-width="130">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsShowParent" size="success">父数据</el-tag>
          <el-tag v-else size="danger">子数据</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.ConfigType === 'M'"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择操作">
              <treeselect
                v-model="form.ParentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级操作"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'M'">
            <el-form-item label="模块" prop="menuType">
              <el-select v-model="form.ModuleTypeId" placeholder="模块" clearable size="small" @change="changeDescription">
                <el-option v-for="item of dict.type.ModuleType" :value="item.value" :label="item.raw.ValueCN"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'M'">
            <el-form-item label="操作类型" prop="menuType">
              <el-select v-model="form.OptTypeId" placeholder="操作类型" clearable size="small" @change="changeDescription">
                <el-option v-for="item of dict.type.OptType" :value="item.value" :label="item.raw.ValueCN"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'M'">
            <el-form-item label="操作子类" prop="menuType">
              <el-select v-model="form.ChildrenTypeId" placeholder="操作子类" clearable size="small"  @change="changeDescription">
                <el-option v-for="item of dict.type.ChildrenType" :value="item.value" :label="item.raw.ValueCN"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType == 'M'">
            <el-form-item label="名称" prop="Description">
              <el-input v-model="form.Description" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="ShowOrder">
              <el-input-number v-model="form.Sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                是否启用
              </span>
              <el-switch
                v-model="form.IsEnable"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'C'">
            <el-form-item>
              <span slot="label">
                继承父数据
              </span>
              <el-switch
                v-model="form.IsShowParent"
                :active-value="true"
                :inactive-value="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.ConfigType === 'C'">
            <el-form-item label="字段key">
              <el-input v-model="form.Code" placeholder="请输入字段key" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'C'">
            <el-form-item label="字段英文">
              <el-input v-model="form.Value" placeholder="请输入字段英文" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.ConfigType === 'C'">
            <el-form-item label="字段中文">
              <el-input v-model="form.ValueCN" placeholder="请输入字段中文" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.ConfigType === 'C'">
            <el-form-item label="枚举类型">
              <el-radio-group v-model="form.EnumType">
                <el-radio :label="null">无</el-radio>
                <el-radio label="E">枚举</el-radio>
                <el-radio label="D">字典</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.ConfigType === 'C' && form.EnumType === 'E'">
            <el-form-item label="枚举">
              <el-input v-model="form.EnumList" placeholder="请输入枚举" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.ConfigType === 'C' && form.EnumType === 'D'">
            <el-form-item label="字典code">
              <el-input v-model="form.dictionaryKey" placeholder="请输入字典code" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getFrontAuditConfigList, addOrUpdateFrontAuditConfig, deleteFrontAuditConfig } from '@/api/dictionary/checkConfig'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import IconSelect from '@/components/IconSelect'

  export default {
    name: 'checkConfig',
    dicts: [ 'OptType', 'ModuleType', 'ChildrenType' ],
    components: { Treeselect, IconSelect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 菜单状态数据字典
        visibleOptions: [],
        // 查询参数
        queryParams: {
          menuName: undefined,
          visible: undefined,
        },
        // 是否展开，默认全部折叠
        isExpandAll: false,
        // 重新渲染表格状态
        refreshTable: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          MenuName: [
            { required: true, message: '菜单名称不能为空', trigger: 'blur' }
          ],
          ShowOrder: [
            { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.getList()
      // this.getDicts("sys_show_hide").then(response => {
      //   this.visibleOptions = response.data;
      // });
    },
    methods: {
      toggleExpandAll() {
        this.refreshTable = false
        this.isExpandAll = !this.isExpandAll
        this.$nextTick(() => {
          this.refreshTable = true
        })
      },
      normalizer(node) {
        if (node.Children && !node.Children.length) {
          delete node.Children
        }
        return {
          id: node.Id,
          label: node.Description,
          children: node.Children
        }
      },
      toTree(arr, ParentId) {
        function loop(ParentId) {
          const res = []
          for (let i = 0; i < arr.length; i++) {
            const item = arr[i]
            item.hasChildren = false
            if (item.ParentId !== ParentId) {
              continue
            }
            item.Children = loop(item.Id)
            res.push(item)
          }
          return res
        }
        return loop(ParentId)
      },
      // 选择图标
      selected(name) {
        this.form.MenuIcon = name
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true
        getFrontAuditConfigList(this.queryParams).then(res => {
          this.menuList = this.toTree(res.Result, '00000000-0000-0000-0000-000000000000')
          const menu = { Id: '00000000-0000-0000-0000-000000000000', Description: '操作', Children: [] }
          menu.Children = this.menuList
          this.menuOptions = Object.assign([], [menu])
          this.loading = false
        }).catch(function() {})
      },
      /** 查询菜单下拉树结构 */
      getTreeselect() {
        this.loading = true
        getFrontAuditConfigList({}).then(res => {
          const menu = { Id: '00000000-0000-0000-0000-000000000000', Description: '操作', Children: [] }
          menu.Children = this.toTree(res.Result, '00000000-0000-0000-0000-000000000000')
          this.menuOptions = Object.assign([], [menu])
          this.loading = false
        }).catch(function() {})
      },
      // 菜单显示状态字典翻译
      visibleFormat(row, column) {
        if (row.MenuType === 'F') {
          return ''
        }
        return this.selectDictLabel(this.visibleOptions, row.visible)
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          Id: null,
          ParentId: null,
          ConfigType: 'M',
          Description: null,
          IsEnable: true,
          ModuleTypeId: null,
          OptTypeId: null,
          ChildrenTypeId: null,
          IsShowParent: false,
          Sort: 0,
          Code: null,
          Value: null,
          ValueCN: null,
          EnumType: null
        }
        this.resetForm('form')
      },
      findName (id, dict, type) {
        if (id) {
          return this.dict.type[dict].find(v => {
            return v.value === id
          }).raw[type]
        }
        return ''
      },
      changeDescription () {
        this.form.Description = this.findName(this.form.OptTypeId, 'OptType', 'ValueCN') + this.findName(this.form.ModuleTypeId, 'ModuleType', 'ValueCN') + this.findName(this.form.ChildrenTypeId, 'ChildrenType', 'ValueCN')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList()
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset()
        this.getTreeselect()
        if (row != null) {
          this.form.ParentId = row.Id
          this.form.ModuleTypeId = row.ModuleTypeId
          this.form.OptTypeId = row.OptTypeId
          this.form.ChildrenTypeId = row.ChildrenTypeId
          if (row.ModuleTypeId && row.OptTypeId && row.ChildrenTypeId) {
            this.form.ConfigType = 'C'
          }
          this.form.Description = row.OptTypeValueCN + row.ModuleTypeValueCN + row.ChildrenTypeValueCN
        }
        this.open = true
        this.title = '添加'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        this.getTreeselect()
        this.form = Object.assign({}, row)
        this.open = true
        this.title = '修改'
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            addOrUpdateFrontAuditConfig(this.form).then(response => {
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.open = false
              this.getList()
            })
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.Description + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return deleteFrontAuditConfig(row.Id)
        }).then(() => {
          this.getList()
          this.$message.success('删除成功')
        }).catch(function() {})
      }
    }
  }
</script>
<style lang="scss">
  .vue-treeselect div{
    line-height: 40px;
  }
</style>
