<template>
  <el-row class="page-container dict">
    <el-container class="page-main" :gutter="20">
      <el-aside width="300px" class="left-content">
        <el-col :span="24" class="left-title">
          <span>字典列表</span>
          <span class="left-add" @click="updateDictType()" title="新增"
            ><i class="el-icon-circle-plus-outline"></i
          ></span>
        </el-col>
        <el-col :span="24" class="left-search">
          <el-input
            v-model.trim="searchVal"
            clearable
            :placeholder="placeholder"
          >
          </el-input>
        </el-col>
        <el-col class="dict-list" ref="dict">
          <el-col
            v-for="(item, index) in dictData"
            :key="item.id"
            class="dict-item"
          >
            <span
              @click="handClick(index, item)"
              :class="{ active: index == isActive }"
              style="cursor: pointer"
            >
              {{ item.name }}
            </span>
            <span class="item-del">
              <!-- <i class="el-icon-edit-outline" @click="updateDictType(item)"></i> -->
              <i
                class="el-icon-delete"
                style="color: #f56c6c"
                @click="handleDelType(item)"
              ></i>
            </span>
          </el-col>
        </el-col>
      </el-aside>
      <el-main>
        <el-row>
          <el-button  v-if="typeCode" plain @click="copyJSON(typeCode)" title="复制">
            {{ typeCode }} <i class="el-icon-document-copy"></i
          ></el-button>
          <direct-search
            ref="form"
            :label-position="'right'"
            :forms="searchList"
            @handleSearch="handleFormSearch"
            :form-style="{
              'text-align': 'right',
              float: 'right',
            }"
          />
        </el-row>
        <el-table-self
          :list-loading="listLoading"
          :tab-type="'index'"
          :tab-label="'序号'"
          :table-data="filterTableData"
          row-key="id"
          :columns="tabColumns"
          default-expand-all
        />
        <dialog-form
          ref="edit"
          :width="'450px'"
          :title="dictTitle"
          :form-data="formData"
          :form-edit="formEdit"
          @handleConfirm="handleConfirm"
        />
      </el-main>
    </el-container>
  </el-row>
</template>

<script>
import { translateListToTree } from "@/utils/handleRoutes"
import { mapActions } from "vuex"
import {
  getDictList,
  updateDictType,
  delDictType,
  getDictDetail,
  addDictDetail,
  delDictDetail,
} from "@/api/dict.js"
export default {
  name: "dict",
  data() {
    return {
      searchList: [
        {
          type: "input",
          prop: "name",
          placeholder: "名称",
          slot: {
            slot: "append",
            type: "button",
            icon: "el-icon-search",
          },
        },
        {
          type: "button",
          color: "primary",
          icon: "el-icon-plus",
          value: "新增",
          func: this.handleAdd,
        },
      ],
      dictTitle: "",
      isActive: -1,
      dictList: [],
      typeCode: "",
      typeId: "",
      searchVal: "",
      placeholder: "请输入字典关键字",
      listLoading: false,
      tabData: [],
      name: "",
      tabColumns: [
        {
          value: "name",
          label: "名称",
          align: "center",
        },
        {
          value: "code",
          label: "值",
          align: "center",
        },
        {
          value: "value",
          label: "医院code",
          align: "center",
        },
        {
          value: "sort",
          label: "排序",
          align: "center",
        },
        {
          value: "note",
          label: "说明",
          align: "center",
        },
        {
          label: "操作",
          fixed: "right",
          align: "center",
          width: 220,
          operType: "button",
          operations: [
            {
              func: this.handleAdd,
              formatter(row) {
                return {
                  label: "新增",
                  type: "primary",
                }
              },
            },
            {
              label: "编辑",
              type: "primary",
              func: this.handleEdit,
            },
            {
              func: this.handleDel,
              label: "删除",
              type: "danger",
            },
          ],
        },
      ],
      formEdit: {},
      formData: [
        {
          type: "input",
          label: "名称",
          prop: "name",
          rules: [{ required: true, message: "名称必填" }],
        },
        {
          type: "input",
          label: "分类",
          rules: [{ required: true, message: "分类必填" }],
          prop: "type",
          hidden: true,
        },
        {
          type: "input",
          label: "值",
          rules: [{ required: true, message: "代码必填" }],
          prop: "code",
          hidden: true,
        },
        {
          type: "input",
          prop: "value",
          hidden: true,
          label: "医院code",
          rules: [{ required: true, message: "医院code必填" }],
        },
        {
          type: "input",
          label: "排序",
          prop: "sort",
        },
        {
          type: "input",
          label: "说明",
          prop: "note",
        },
      ],
      cacheForm: {},
    }
  },
  computed: {
    dictData() {
      const list = this.dictList.filter(
        (_) => !this.searchVal || _.name.includes(this.searchVal)
      )
      this.isActive = this.getListIdx(list, this.typeId)
      return list
    },
    filterTableData() {
      return this.tabData.filter(
        (_) => !this.cacheForm.name || _.name.includes(this.cacheForm.name)
      )
    },
  },
  methods: {
    ...mapActions({
      handleUpdateDictDetail: "dict/updateDictDetail",
      handleUpdateDictType: "dict/updateDictType",
    }),
    // 获得字典列表
    async getDictList() {
      const res = await getDictList()
      const d = res.data
      this.dictList = d
      return d
    },

    handleDelType({ id, name }) {
      this.$confirm(`确定删除${name}吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDictType(id).then(async (res) => {
            if (res.code === 1) {
              this.$message.success("删除成功")
              if (this.name === name) {
                this.isActive = -1
                this.typeCode = null
              }
              const data = await this.getDictList()
              this.handleUpdateDictType(data)
            }
          })
        })
        .catch(() => {})
    },
    // 点击左侧列表
    handClick(index, { type, name, id }) {
      this.name = name
      this.isActive = index
      this.typeCode = type
      this.typeId = id
      // this.copyJSON(type)
      this.handleSearch()
    },
    async copyJSON(text) {
      let target = document.createElement("input")
      target.value = text
      document.body.appendChild(target)
      target.select()
      try {
        await document.execCommand("Copy")
        document.body.removeChild(target)
        this.$message.success('已复制')
      } catch {}
    },
    handleFormSearch(form) {
      this.cacheForm = form
    },

    // 查询 获得字典列表详情-列表
    async handleSearch() {
      if (this.typeCode) {
        const params = {}
        params.type = this.typeCode
        this.listLoading = true
        const res = await getDictDetail(params)
        this.listLoading = false
        const d = res.data
        this.tabData = translateListToTree(d) || []
        return d
      } else {
        this.$message.warning("请选择左侧具体字典")
      }
    },

    // 新增字典分类
    updateDictType(row) {
      this.formData[1].hidden = false
      this.formData[2].hidden = true
      this.formData[3].hidden = true
      this.dictTitle = `${row ? "编辑" : "新增"}字典分类`
      this.formEdit = Object.assign({}, row)
      this.$refs.edit.open()
    },

    // 编辑
    handleEdit(row) {
      this.formData[1].hidden = true
      this.formData[2].hidden = false
      this.formData[3].hidden = false
      this.dictTitle = `编辑${this.name}字典`
      this.formEdit = {
        id: row.id,
        code: row.code,
        name: row.name,
        note: row.note,
        sort: row.sort,
        value: row.value,
      }
      this.$refs.edit.open()
    },

    // 删除
    handleDel(row) {
      this.$confirm(`确定删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDictDetail(row.id).then((res) => {
            // this.$store.dispatch("deleteDictByCode", row)
            this.successCallback(res, "删除成功")
          })
        })
        .catch(() => {})
    },

    // 新增
    handleAdd({ id }) {
      this.formData[1].hidden = true
      this.formData[2].hidden = false
      this.formData[3].hidden = false
      this.dictTitle = `新增【${this.name}】字典`
      this.formEdit = { parentId: id || "" }
      if (this.typeCode) {
        this.$refs.edit.open()
      } else {
        this.$message.warning("请选择左侧具体字典")
      }
    },

    // 保存
    handleConfirm(d) {
      const form = Object.assign({}, d)
      let msg = form.id ? "修改成功" : "保存成功"
      let type = form.id ? "edit" : "add"
      if (this.dictTitle.includes("字典分类")) {
        // 字典分类新增编辑
        updateDictType(form)
          .then((res) => {
            this.successCallback(res, msg)
          })
          .catch(() => {
            this.$refs.edit.loading = false
          })
      } else {
        // 字典新增修改
        form.type = this.typeCode
        addDictDetail(form)
          .then((res) => {
            this.successCallback(res, msg, type)
          })
          .catch(() => {
            this.$refs.edit.loading = false
          })
      }
    },

    // 保存成功
    async successCallback(res, msg, type) {
      this.$refs.edit.loading = false
      if (res.code === 1) {
        if (this.dictTitle === "新增字典分类") {
          if (this.isActive !== -1) this.isActive = this.isActive + 1
          const data = await this.getDictList()
          this.handleUpdateDictType(data)
        } else {
          if (type) {
            // const data = res.data
            // data.type = type
            // this.$store.dispatch("updateDictByCode", data)
          }
          const data = await this.handleSearch()
          // 更新全局字典数据
          this.handleUpdateDictDetail({ data, type: this.typeCode })
        }
        this.$message.success(msg)
        this.$refs.edit.close()
      }
    },

    getListIdx(list, id) {
      let listIdx = -1
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) {
          listIdx = i
          break
        }
      }
      return listIdx
    },
  },
  mounted() {
    this.getDictList()
  },
}
</script>

<style lang="scss" scoped>
.el-main {
  padding: 0 20px;
}

.page-main {
  align-items: flex-start;
}
</style>
