<template>
  <!-- 字典管理 -->
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <!-- 列表搜索栏 -->
      <el-form
        :inline="true"
        ref="searchFormInput"
        :model="searchFormInput"
        size="medium"
      >
        <el-form-item label="字典名称">
          <el-input
            placeholder="请输入"
            v-model="searchFormInput.dictionaryName"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input
            placeholder="请输入"
            v-model="searchFormInput.dictionaryEncoding"
          ></el-input>
        </el-form-item>
        <el-button type="primary" size="medium" plain @click="getList"
          >查询</el-button
        >
        <el-button type="warning" size="medium" plain @click="refresh(1)"
          >刷新</el-button
        >
        <el-button type="primary" size="medium" @click="add">新增</el-button>
        <el-button type="primary" size="medium" @click="exportBtn"
          >导出</el-button
        >
        <el-upload
          style="margin: 0px 15px; display: inline"
          class="upload-demo expintBtn"
          name="mppFile"
          :on-success="handleImportSuccess"
          :on-change="handleImportChange"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :action="$http.defaults.baseURL + 'xmgl/dictionary/importExcel'"
          :data="{ projectSn: projectSn }"
          :show-file-list="false"
          :headers="headers"
        >
          <el-button size="medium" type="primary">导入</el-button>
        </el-upload>
        <el-button type="primary" size="medium" @click="recyclebinBtn"
          >回收站</el-button
        >
        <el-button
          type="primary"
          plain
          size="medium"
          @click="deleteInBatches"
          :disabled="multipleSelection.length == 0"
          >批量移入回收站</el-button
        >
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table
        class="tables"
        :data="List"
        height="800"
        tooltip-effect="dark"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column
          prop="dictionaryName"
          align="left"
          label="字典名称"
        ></el-table-column>
        <el-table-column
          prop="dictionaryEncoding"
          label="字典编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remarks"
          label="描述"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div class="operationText last" @click="previewDetail(scope.row)">
                <i
                  class="el-icon-document"
                  style="color: #8dacfa; font-size: 16px; margin-right: 2px"
                ></i>
                <span>字典配置</span>
              </div>
              <div @click="edit(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-edit.png"
                  width="15px"
                  height="15px"
                />
                <span>编辑</span>
              </div>
              <div @click="deleteDev(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-delete.png"
                  width="15px"
                  height="15px"
                />
                <span>移入回收站</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(pageTotal)"
      ></el-pagination>
    </div>
    <!-- 新增字典弹框 -->
    <el-dialog
      :modal-append-to-body="false"
      @close="close"
      :title="title"
      :visible.sync="diaLogShow"
      width="667px"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          ref="addEditForm"
          :model="addEditForm"
          :rules="addEditRules"
          label-width="120px"
          class="dialogFormBox"
        >
          <el-form-item label="字典名称" prop="dictionaryName">
            <el-input
              v-model="addEditForm.dictionaryName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="字典编码" prop="dictionaryEncoding">
            <el-input
              v-model="addEditForm.dictionaryEncoding"
              placeholder="请输入"
              :disabled="title == '编辑字典'"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="remarks">
            <el-input
              v-model="addEditForm.remarks"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="diaLogShow = false"
              icon="el-icon-circle-close"
              size="medium"
              >取消
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="submit"
              size="medium"
              >保存
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 字典数据项列表弹框-->
    <el-dialog
      title="数据项"
      class="dialog-center"
      :visible.sync="showDetail"
      :modal-append-to-body="false"
      @close="closeDetail"
    >
      <div class="dialog-content">
        <div class="search-box">
          <div class="search-item">
            <span class="search-label" style="margin-right: 10px">名称</span>
            <el-input v-model="dataSearch.name" placeholder="请输入"></el-input>
          </div>
          <div class="search-item">
            <span class="search-label" style="margin-right: 10px">状态</span>
            <el-select
              v-model="dataSearch.isEnable"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataSelect"
                :key="item.value"
                :label="item.isEnable"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <el-button type="primary" plain @click="dataGetSearch"
            >查询</el-button
          >
          <el-button type="warning" plain @click="refresh(2)">刷新</el-button>
          <el-button type="primary" @click="addTestPoint">新增</el-button>
        </div>
        <el-table :data="surveyPointDetail" class="tables" height="560">
          <el-table-column
            prop="name"
            label="名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="data"
            label="数据值"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="remarks"
            label="描述"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="orderNum"
            label="排序"
            align="center"
          ></el-table-column>
          <el-table-column prop="isEnable" label="是否启用" align="center">
            <template slot-scope="scope">{{
              scope.row.isEnable == 1 ? '是' : '否'
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="170">
            <template slot-scope="scope">
              <div class="tableBtns">
                <div class="operationText" @click="dataEdit(scope.row)">
                  <img
                    src="@/assets/images/icon-edit.png"
                    width="15px"
                    height="15px"
                  />
                  <span>编辑</span>
                </div>
                <div class="operationText" @click="deleData(scope.row)">
                  <img
                    src="@/assets/images/icon-delete.png"
                    width="15px"
                    height="15px"
                  />
                  <span>删除</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pager"
          @size-change="handleSizeChangeData"
          @current-change="handleCurrentChangeData"
          :current-page="dataPage.pageNo"
          :page-sizes="$store.state.PAGESIZRS"
          :page-size="dataPage.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="Number(dataPage.total)"
          background
        ></el-pagination>
      </div>
    </el-dialog>
    <!-- 字典数据项新增弹框-->
    <el-dialog
      :modal-append-to-body="false"
      @close="dataClose"
      :title="dataTitle"
      :visible.sync="dataDiaLogShow"
      width="667px"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          ref="dataAddEditForm"
          :model="dataAddEditForm"
          :rules="dataAddEditRules"
          label-width="120px"
          class="dialogFormBox"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="dataAddEditForm.name"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="数据值" prop="data">
            <el-input
              v-model="dataAddEditForm.data"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="remarks">
            <el-input
              :maxlength="10"
              v-model="dataAddEditForm.remarks"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="orderNum">
            <el-input-number
              v-model="dataAddEditForm.orderNum"
              :min="1"
              :max="100"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-radio-group v-model="dataAddEditForm.isEnable">
              <el-radio-button :label="1">启用</el-radio-button>
              <el-radio-button :label="0">不启用</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="dataDiaLogShow = false"
              icon="el-icon-circle-close"
              size="medium"
              >取消
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="dataSubmit"
              size="medium"
              >保存
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 字典回收站弹框 -->
    <el-dialog
      title="字典回收站"
      class="dialog-center"
      :visible.sync="recyclebinShow"
      :modal-append-to-body="false"
    >
      <div class="dialog-content">
        <el-table :data="recyclebinList" class="tables" height="560">
          <el-table-column
            prop="dictionaryName"
            label="字典名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="dictionaryEncoding"
            label="字典编码"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="remarks"
            label="描述"
            align="center"
          ></el-table-column>
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <div class="tableBtns">
                <div class="operationText" @click="retrieveBtn(scope.row)">
                  <i
                    class="el-icon-refresh-left"
                    style="color: #5483f6; font-size: 18px"
                  ></i>
                  <span>取回</span>
                </div>
                <div class="operationText" @click="deleCompletely(scope.row)">
                  <img
                    src="@/assets/images/icon-delete.png"
                    width="15px"
                    height="15px"
                  />
                  <span>彻底删除</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagerBox"
          @size-change="handleSizeChangeDataRetr"
          @current-change="handleCurrentChangeDataRetr"
          :current-page="retrieve.pageNo"
          :page-sizes="$store.state.PAGESIZRS"
          :page-size="retrieve.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="Number(retrieve.total)"
          background
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addDictionaryApi,
  editDictionaryApi,
  getDictionaryPageApi,
  addDictionaryItemApi,//数据项
  deleteDictionaryItemApi,
  editDictionaryItemApi,
  getDictionaryItemPageApi,
  getDictionaryItemBackApi,//取回
  deleteDictionaryItemBackApi,//彻底删除
  batchDeleteDictionaryItemBackApi,//批量删除
} from "@/assets/js/api/jxjadmin";
import axios from 'axios'
export default {
  mounted() {
    this.getList()
    this.projectSn = this.$store.state.projectSn
  },
  data() {
    return {
      searchFormInput: {
        dictionaryName: '',
        dictionaryEncoding: '',
      },
      addEditForm: {
        dictionaryName: '',
        dictionaryEncoding: '',
        remarks: '',
      },
      diaLogShow: false,
      pageTotal: 0,
      searchForm: {
        pageNo: 1,
        pageSize: 10,
      },
      addEditRules: {
        dictionaryName: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        dictionaryEncoding: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
      },
      List: [],
      title: '',
      multipleSelection: [],//表格多选数据
      showDetail: false,

      //数据项
      surveyPointDetail: [],
      dataSelect: [
        {
          value: 0,
          isEnable: '否'
        },
        {
          value: 1,
          isEnable: '是'
        },
      ],
      dataSearch: {
        name: '',
        isEnable: '',
      },
      dataDiaLogShow: false,
      dataTitle: '',
      dataAddEditForm: {
        name: '',
        data: '',
        remarks: '',
        orderNum: '',
        isEnable: 1,
        dictionaryId: '',
      },
      dataAddEditRules: {
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        data: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
      },
      dataPage: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      retrieve: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      recyclebinShow: false,
      recyclebinList: [
      ],
      projectSn: '',
      fileList: [],

    }
  },
  computed: {
    headers() {
      return { Authorization: this.$store.state.userInfo.token }
    },
  },
  methods: {
    //点击回收站
    recyclebinBtn() {
      this.recyclebinShow = true
      this.getRetrieveList()
    },
    // 导入成功
    handleImportSuccess(res) {
      if (res.code == 200) {
        this.$message.success(res.message);
        this.getList()
      } else {
        this.$message.error(res.message);
      }
      console.log('导入', res)
    },
    // 上传mpp文件触发
    handleImportChange(file, fileList) {
      console.log('=[====]')
    },
    beforeUpload(file) {
      console.log('=========', file)
    },
    //导出
    exportBtn() {
      fetch(this.$http.defaults.baseURL + 'xmgl/dictionary/exportXls', {
        headers: {
          'Authorization': this.$store.state.userInfo.token
        }
      })
        .then(response => {
          // 处理响应
          if (!response.ok) {
            throw new Error('导出失败');
          }
          return response.blob();
        })
        .then(blob => {
          console.log('导出成功');
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob);
          // 创建一个<a>元素
          const link = document.createElement('a');
          link.href = url;
          link.download = '导出文件.xlsx'; // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放URL对象
          window.URL.revokeObjectURL(url);
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch(error => {
          // 处理错误
          console.error(error);
        });

    },
    //取回
    retrieveBtn(obj) {
      getDictionaryItemBackApi({ id: obj.id }).then((result) => {
        if (result.success) {
          this.$message.success(result.message)
          this.getRetrieveList()
          this.getList()
        }
      })
    },
    //彻底删除
    deleCompletely(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDictionaryItemBackApi({ id: obj.id }).then((result) => {
            if (result.success) {
              this.$message.success(result.message)
              this.getRetrieveList()
            }
          })
        })
        .catch(() => { })
    },
    //批量删除
    deleteInBatches() {
      this.$confirm("此操作将数据移入回收站, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = this.multipleSelection
          batchDeleteDictionaryItemBackApi(data).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.message)
              this.multipleSelection = []
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        })
    },
    //查询回收站列表
    getRetrieveList() {
      //查询数据项列表
      getDictionaryPageApi({
        projectSn: this.$store.state.projectSn,
        pageSize: this.retrieve.pageSize,
        pageNo: this.retrieve.pageNo,
        deleted: 1,
      }).then((result) => {
        console.log('查询数据项列表', result);
        if (result.success) {
          this.recyclebinList = result.result.records
          this.retrieve.total = result.result.total
        }
      })
    },
    //查询数据项列表
    dataGetList(val) {
      getDictionaryItemPageApi({
        projectSn: this.$store.state.projectSn,
        pageSize: this.dataPage.pageSize,
        pageNo: this.dataPage.pageNo,
        dictionaryId: val,
        name: this.dataSearch.name,
        isEnable: this.dataSearch.isEnable,
      }).then((result) => {
        console.log('查询数据项列表', result);
        if (result.success) {
          this.surveyPointDetail = result.result.records
          this.dataPage.total = result.result.total
        }
      })
    },
    //数据项新增弹框
    addTestPoint() {
      this.dataDiaLogShow = true
      this.dataTitle = '新增'
    },
    dataEdit(obj) {
      this.dataDiaLogShow = true
      this.dataTitle = '编辑'
      this.dataAddEditForm = JSON.parse(JSON.stringify(obj))
    },
    dataSubmit() {
      let params = JSON.parse(JSON.stringify(this.dataAddEditForm))
      params.projectSn = this.$store.state.projectSn
      this.$refs.dataAddEditForm.validate((valid) => {
        if (valid) {
          if (this.dataTitle == '新增') {
            addDictionaryItemApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message)
                this.dataGetList(params.dictionaryId)
                this.dataAddEditForm.dictionaryId = params.dictionaryId
              }
            })
          } else if (this.dataTitle == '编辑') {
            editDictionaryItemApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message)
                this.dataGetList(params.dictionaryId)
                this.dataAddEditForm.dictionaryId = params.dictionaryId
              }
            })
          }
          this.dataDiaLogShow = false
        } else {
          return false
        }
      })
    },
    //数据项点击查询
    dataGetSearch() {
      this.dataGetList(this.dataAddEditForm.dictionaryId)
    },
    //打开字典配置弹框
    previewDetail(val) {
      this.showDetail = true
      this.dataAddEditForm.dictionaryId = val.id
      this.dataGetList(val.id)
    },
    //删除数据项
    deleData(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDictionaryItemApi({ id: obj.id }).then((result) => {
            if (result.success) {
              this.$message.success(result.message)
              this.dataGetList(this.dataAddEditForm.dictionaryId)
              // // 判断当前页是否为空
              // if (this.surveyPointDetail.length === 0 && this.dataPage.pageNo > 1) {
              //   this.dataPage.pageNo--; // 切换到前一页
              // }
            }
          })
        })
        .catch(() => { })
    },
    //列表多选
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
      console.log('批量选中的数据', this.multipleSelection);
    },
    //列表查询
    getList() {
      getDictionaryPageApi({
        projectSn: this.$store.state.projectSn,
        pageSize: this.searchForm.pageSize,
        pageNo: this.searchForm.pageNo,
        dictionaryName: this.searchFormInput.dictionaryName,
        dictionaryEncoding: this.searchFormInput.dictionaryEncoding,
        deleted: 0,
      }).then((result) => {
        if (result.success) {
          this.List = result.result.records
          this.pageTotal = result.result.total
          console.log('run', this.List)
        }
      })
    },
    add() {
      this.diaLogShow = true
      this.title = '新增字典'
    },
    edit(obj) {
      this.diaLogShow = true
      this.addEditForm = JSON.parse(JSON.stringify(obj))
      this.title = '编辑字典'
    },
    //移入回收站
    deleteDev(obj) {
      axios({
        method: 'post',
        url: `/xmgl/dictionary/delete?id=${obj.id} `,
      }).then(res => {
        this.getList()
      });

    },
    submit() {
      let params = JSON.parse(JSON.stringify(this.addEditForm))
      params.projectSn = this.$store.state.projectSn
      this.$refs.addEditForm.validate((valid) => {
        if (valid) {
          if (this.title == '新增字典') {
            addDictionaryApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          } else if (this.title == '编辑字典') {
            console.log('编辑信息', this.addEditForm)
            editDictionaryApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          }
          this.diaLogShow = false
        } else {
          return false
        }
      })
    },
    refresh(type) {
      if (type == 1) {
        this.searchFormInput = {}
        this.getList()
      } else {
        this.dataSearch = {}
        this.dataGetList(this.dataAddEditForm.dictionaryId)
      }
    },
    close() {
      this.addEditForm = {}
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    closeDetail() {
      this.showDetail = false
      this.dataAddEditForm.dictionaryId = ''
    },
    dataClose() {
      this.dataAddEditForm = {
        name: '',
        data: '',
        remarks: '',
        orderNum: '',
        isEnable: 1,
      },
        this.$nextTick(() => {
          this.$refs.dataAddEditForm.clearValidate()
        })
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.searchForm.pageNo = val
      this.getList()
    },
    handleSizeChangeData(val) {
      this.dataPage.pageSize = val
      this.dataGetList(this.dataAddEditForm.dictionaryId)
    },
    handleCurrentChangeData(val) {
      this.dataPage.pageNo = val
      this.dataGetList(this.dataAddEditForm.dictionaryId)
    },
    handleSizeChangeDataRetr(val) {
      this.retrieve.pageSize = val
      this.getRetrieveList()
    },
    handleCurrentChangeDataRetr(val) {
      this.retrieve.pageNo = val
      this.getRetrieveList()
    },
  }
}
</script>
<style lang="less">
.tables {
  img {
    cursor: pointer;
  }
}

.tableBtns {
  display: flex;
  justify-content: center;
}

.yj-dialogFormBox {
  width: 462px;
}

.dialog-content {
  height: 650px;
  margin-bottom: 30px;
}

.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .search-item {
    display: flex;
    align-items: center;
    padding: 20px;

    .search-label {
      // width: 80px;
      white-space: nowrap;
    }
  }
}

.dialog-center {
  overflow: auto;

  /deep/.el-dialog {
    margin: 0 !important;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.pager {
  margin-top: 5px;
  text-align: center;

  .el-pager li.active {
    background-color: @--bg-color-primary !important;
  }

  button:disabled,
  .btn-next,
  .btn-prev {
    background-color: transparent !important;
  }
}
</style>