<script setup name="Dictionary">
import { onMounted, ref, toRefs } from 'vue'
import { Split } from 'view-ui-plus';
import { ElMessage } from "element-plus";

import ModalPop from "@/components/EditPop/ModalPop.vue"
import AddClass from './modules/AddClass.vue' // 分类
import AddValue from './modules/AddValue.vue' // 值
import uploadModule from './modules/uploadModule.vue' // 上传模块

import { dictinaryTypes, query, delDictionaryType, delValue, exportExcel } from '@/api/ruleConfig/dictionary'

const splitNum = ref(0.31) // 左右分割比例

const data = reactive({
  queryParams: {
    pageno: 1,
    pagesize: 10,
    typecode: '',
    typename: '',
    value: '',
    parvalue: ''
  },
  addClassForm: {},
  addValueForm: {},
  delData: {}
});

const { addClassForm, addValueForm, queryParams, delData } = toRefs(data);

const classList = ref([])
const modalData = reactive({
  show: false,
  text: '',
  icon: 'error',
  cancel: false,
  type: ''
})

const modalPopData = reactive({
  show: false,
  title: '',
  type: '',
  operation: ''
})

const tableData = reactive({
  list: [],
  total: 0
})


// 新增关闭
const modalPopCancel = () => {
  modalPopData.show = false
}

// 新增/编辑 分类
const addClassClick = (type, item) => {
  modalPopData.operation = type
  if (modalPopData.operation === 'edit') {
    addClassForm.value = item
  }
  modalPopData.title = '字典分类'
  modalPopData.type = 'class'
  modalPopData.show = true
}

// 新增/编辑 值
const addValueClick = (type, item) => {
  modalPopData.operation = type
  if (modalPopData.operation === 'add') {
    addValueForm.value = {
      typecode: queryParams.value.typecode,
    }
  } else if (modalPopData.operation === 'edit') {
    addValueForm.value = item
  }
  modalPopData.title = '字典数据'
  modalPopData.type = 'value'
  modalPopData.show = true
}

// 删除值
const valueDelete = (item) => {
  const { value } = item
  delData.value = item
  modalData.type = 'value'
  modalData.icon = 'error'
  modalData.text = '删除后无法恢复，是否确认删除[' + value + ']?'
  modalData.show = true
}

// 删除分类
const classDelete = (item) => {
  const { value } = item
  delData.value = item
  modalData.type = 'class'
  modalData.icon = 'error'
  modalData.text = '删除后无法恢复，是否确认删除[' + value + ']?'
  modalData.show = true
}

// 提示回调
const modalConfirm = () => {
  if (modalData.type === 'class') {
    const { value, text } = delData.value
    const data = {
      dictionaryTypeCode: value,
      dictionaryTypeName: text
    }
    delDictionaryType(data).then(res => {
      const { flag } = res
      if (flag) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败')
      }
      if (value === queryParams.value.typecode) {
        getData()
      } else {
        getData('class')
      }
    })
  } else if (modalData.type === 'value') {
    const { id, name } = delData.value
    const data = {
      dicId: id,
      dicName: name
    }
    delValue(data).then(res => {
      const { flag } = res
      if (flag) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败')
      }
      getTableData()
    })
  }
  modalData.show = false
}

// 分类查看
const classView = (item) => {
  if (queryParams.value.typecode === item.value) return
  queryParams.value.typecode = item.value
  queryParams.value.typename = item.text
  getTableData()
}

// 新增确认
const AddDomainConfirm = (item) => {
  if (modalPopData.type === 'class') {
    getData('class')
  } else if (modalPopData.type === 'value') {
    getTableData()
  } else if (modalPopData.type === 'upload') {
    console.log('导入', item)
    getTableData()
  }
  modalPopData.type = ''
  modalPopData.show = false
}

// 导入功能
const importClick = () => {
  modalPopData.title = '上传文件'
  modalPopData.type = 'upload'
  modalPopData.show = true
}

// 获取分类名称
const getClassName = (value) => {
  const item = classList.value.find(item => item.value === value)
  return item ? item.text : ''
}

// 获取列表数据
const getData = (type) => {
  dictinaryTypes({}).then(res => {
    const { data } = res;
    classList.value = data
    if (classList.value.length <= 0) return
    if (type === 'class') {
      getTableData()
    } else {
      queryParams.value.typecode = classList.value[0].value
      queryParams.value.typename = classList.value[0].text
      getTableData()
    }
  })
}

// 获取列表table数据
const getTableData = () => {
  query(queryParams.value).then(res => {
    const { data } = res;
    tableData.list = data.list
    tableData.total = data.total
  })
}

// 导出excel
const exportExcelFunc = () => {
  exportExcel({ typecode: queryParams.value.typecode }).then(response => {
    const { data } = response;
    const blob = new Blob([response], { type: 'application/vnd.ms-excel,charset=utf-8' });
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `${queryParams.value.typename}知识库.xlsx`
    link.click()
    URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  })
}


onMounted(() => {
  getData()
})

</script>
<template>
  <div class="app-container scroller">
    <PageTitle>
      <template #title>
        知识库
      </template>
    </PageTitle>
    <div class="app-container__body">
      <Split v-model="splitNum">
        <template #left>
          <div class="left">
            <div class="mb20" style="display: flex;flex-direction: row-reverse;">
              <el-button icon="Plus" type="primary" @click="addClassClick('add')">新增分类</el-button>
            </div>
            <div style="width: 100%;flex: 1;overflow: auto;">
              <el-scrollbar>
                <div class="left_item" :class="queryParams.typecode === item.value ? 'active' : ''"
                  v-for="(item, index) in classList" :key="index" @click="classView(item)">
                  <span>{{ item.text }}（{{ item.value }}）</span>
                  <div class="left_item_btn">
                    <el-icon :size="16" @click.stop="addClassClick('edit', item)">
                      <edit />
                    </el-icon>
                    <el-icon :size="16" style="margin-left: 10px;" @click.stop="classDelete(item)">
                      <delete />
                    </el-icon>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </template>
        <template #right>
          <div class="right">
            <div style="display: flex;justify-content: space-between;">
              <el-form-item label="值：">
                <el-input placeholder="" v-model="queryParams.value" class="input-with-select">
                  <template #append>
                    <el-button icon="Search" @click="getTableData"></el-button>
                  </template>
                </el-input>
              </el-form-item>
              <div style="display: flex;">
                <el-button icon="Upload" type="primary" @click="importClick">导入</el-button>
                <el-button icon="Download" type="success" @click="exportExcelFunc">导出</el-button>
                <el-button icon="Plus" type="primary" @click="addValueClick('add')">新增值</el-button>
              </div>
            </div>
            <el-table :data="tableData.list" stripe style="width: 100%;flex:1;">
              <el-table-column prop="date" label="分类" align="center">
                <template #default="scope">
                  {{ getClassName(scope.row.typecode) }}
                </template>
              </el-table-column>
              <el-table-column prop="typecode" label="分类编码" align="center"></el-table-column>
              <el-table-column prop="value" label="值" align="center"></el-table-column>
              <el-table-column prop="name" label="名称" align="center"></el-table-column>
              <el-table-column prop="parentvalue" label="父值" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="primary" link @click="addValueClick('edit',scope.row)">编辑</el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-button type="danger" link @click="valueDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="tableData.total>0" :total="tableData.total" :isTextShow="true"
              v-model:page="queryParams.pageno" v-model:limit="queryParams.pagesize" @pagination="getTableData" />
          </div>
        </template>
      </Split>
    </div>

    <!-- 提示框 -->
    <Modal v-model="modalData.show" :icon="modalData.icon" :cancel="modalData.cancel" :text="modalData.text"
      @confirm="modalConfirm"></Modal>

    <!-- 新增分类 / 新增值 -->
    <ModalPop :width="'600'" v-model="modalPopData.show" :title="modalPopData.title" @cancel="modalPopCancel">
      <template #content>
        <AddClass :itemData="addClassForm" :type="modalPopData.operation" @cancel="modalPopCancel"
          @confirm="AddDomainConfirm" v-if="modalPopData.type === 'class'" />
        <AddValue :itemData="addValueForm" :type="modalPopData.operation" :classDict="classList"
          @cancel="modalPopCancel" @confirm="AddDomainConfirm" v-if="modalPopData.type === 'value'" />
        <uploadModule @cancel="modalPopCancel" @confirm="AddDomainConfirm" v-if="modalPopData.type === 'upload'" />
      </template>
    </ModalPop>
  </div>
</template>

<style lang="scss" scoped>
.app-container__body {
  height: calc(
    100vh - var(--navbar-height) - var(--container-pd) - var(--container-pd)
  ) !important;
  .left {
    display: flex;
    flex-direction: column;
    padding: 0 38px 10px 0;
    width: 100%;
    overflow: auto;
    height: 100%;
    .left_item {
      position: relative;
      height: 38px;
      line-height: 38px;
      border-bottom: 1px solid #dce5eb;
      padding: 0 10px;
      -webkit-transition: all 0.3s;
      transition: all 0.3s;
      cursor: pointer;
      font-size: 14px;
      color: #7a8495;
      .left_item_btn {
        position: absolute;
        right: 8px;
        top: 2px;
        z-index: 0;
        -webkit-transition: all 0.3s;
        transition: all 0.3s;
        opacity: 0;
      }
    }
    .left_item:hover {
      .left_item_btn {
        z-index: 10;
        opacity: 1;
      }
    }
    .active {
      background: #f4faff;
    }
  }
  .right {
    padding-left: 36px;
    height: 100%;
    display: flex;
    flex-direction: column;
    :deep(.el-table .el-table__header-wrapper th) {
      background-color: #e9f5fe !important;
      color: #2c9ef7;
    }
  }
}
</style>