<!-- 字典数据 -->
<template>
  <div>
    <FireflySearchBar :model="searchForm" @search="getTableData" @reset="resetSearch" :loading="loading">
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input v-model="searchForm.dictLabel" placeholder="请输入字典标签"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="searchForm.status" clearable placeholder="状态" style="width: 100%" @change="getTableData()">
          <el-option value="1" label="正常"></el-option>
          <el-option value="0" label="停用"></el-option>
        </el-select>
      </el-form-item>
    </FireflySearchBar>
    <firefly-table
      ref="dictDataTable"
      :loading="loading"
      :searchForm="searchForm"
      :tableHeader="tableHeader"
      :tableData="tableData"
      :totalCount="totalCount"
      :lineBtns="lineBtns"
      :btns="btns"
      exportDownloadShow
      isSelect
      customPage="pageIndex"
      customSize="pageSize"
      @paginationChange="getTableData"
      @selection-change="selectionChangeHandle"
      @exportDownload="exportDownload"
    >
      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status == 1">正常</el-tag>
        <el-tag type="danger" v-if="scope.row.status == 0">停用</el-tag>
      </template>
    </firefly-table>
    <DictDataDialog :show.sync="dictDataVisible" :row="subRow" :baseApi="baseApi" :TokenKey="TokenKey" @refreshList="getTableData"></DictDataDialog>
  </div>
</template>

<script>
import axios from 'axios';
import FireflyDialog from '../../../fireflyDialog/src/main.vue';
import FireflySearchBar from '../../../fireflySearchBar/src/main.vue';
import FireflyTable from '../../../fireflyTable/src/main.vue';
import DictDataDialog from './dictDataDialog.vue';
export default {
  name: 'DictDataTable',
  components: {
    FireflyDialog,
    FireflySearchBar,
    FireflyTable,
    DictDataDialog
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => {
        return {};
      }
    },
    baseApi: {
      type: String,
      default: ''
    },
    TokenKey: {
      type: String,
      default: ''
    }
  },

  watch: {
    row(newVal, oldVal) {
      if (newVal) {
        this.searchForm = {
          ...this.searchForm,
          dictType: newVal.dictType
        };
        this.getTableData();
      }
    }
  },

  data() {
    return {
      loading: false,
      searchForm: {
        pageIndex: 1,
        pageSize: 10,
        dictType: '',
        dictLabel: '',
        status: ''
      },
      totalCount: 0,
      tableHeader: [],
      tableData: [],
      lineBtns: [
        {
          text: '新增',
          event: () => this.addOrUpdateHandle()
        },
        // {
        //   text: '删除',
        //   event: () => this.deleteBatchHandle()
        // }
      ],
      btns: [
        {
          text: '修改',
          event: ({ row }) => this.addOrUpdateHandle(row)
        },
        // {
        //   text: '删除',
        //   event: ({ row }) => this.deleteBatchHandle(row.id)
        // }
      ],
      selectList: [], // 多选
      typeOptions: [],
      dictDataVisible: false,
      subRow: {}
    };
  },

  methods: {
    getTableData() {
      this.loading = true;
      axios({
        method: 'get',
        url: `${this.baseApi}/system/dict/data/page`,
        headers: {
          Authorization: `Bearer ${localStorage.getItem(this.TokenKey)}`
        },
        params: this.searchForm
      })
        .then(response => {
          const { status } = response;
          if (status === 200) {
            const res = response.data;
            if (res.state === 200) {
              this.tableHeader = res.headInfo;
              this.tableData = res.data;
              this.totalCount = res.pageInfo.totalCount;
            } else {
              this.$message.error(`${res.message}`);
            }
          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    resetSearch() {
      this.searchForm = {
        ...this.searchForm,
        dictLabel: '',
        status: ''
      };
    },

    // 新增 & 修改
    addOrUpdateHandle(row) {
      if (row && row.id) {
        this.subRow = { ...row };
      } else {
        this.subRow = {
          dictType: this.searchForm.dictType
        };
      }
      this.dictDataVisible = true;
    },

    // 多选
    selectionChangeHandle(selections) {
      this.selectList = selections.map(item => item.id);
    },

    // 删除
    deleteBatchHandle(id) {
      let tableIds = this.selectList.length > 0 ? this.selectList : [];
      if (id) {
        tableIds = [id];
      }
      if (tableIds.length === 0) {
        this.$message.warning('请选择数据');
        return;
      }
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          axios({
            method: 'delete',
            url: `${this.baseApi}/system/dict/data/${tableIds.join(',')}`,
            headers: {
              Authorization: `Bearer ${localStorage.getItem(this.TokenKey)}`
            }
          })
            .then(response => {
              const { status } = response;
              if (status === 200) {
                const res = response.data;
                if (res.state === 200) {
                  this.selectList = [];
                  this.getTableData();
                  this.$message.success('删除成功');
                } else {
                  this.$message.error(`${res.message}`);
                }
              }
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 导出
    exportDownload(exportParams) {
      const checkboxIds = this.selectList.length
        ? this.selectList
        : this.tableData.map(item => {
            return item.id;
          });
      const params = {
        checkboxIds: checkboxIds,
        columns: exportParams.checkField,
        ...exportParams
      };
      axios({
        method: 'get',
        responseType: 'blob',
        url: `${this.baseApi}/system/dict/data/export`,
        headers: {
          Authorization: `Bearer ${localStorage.getItem(this.TokenKey)}`
        }
        // params: params,
      })
        .then(response => {
          const { status } = response;
          if (status === 200) {
            let data = response.data;
            let reader = new FileReader();
            reader.readAsText(data, 'utf-8');
            reader.onload = e => {
              if (e.target.result.indexOf('status_code') != -1) {
                let sError = eval('(' + e.target.result + ')');
                this.$message.warning(sError.errors[0].message);
              } else {
                if (window.navigator.msSaveBlob) {
                  let blob = new Blob([data], {
                    type: 'application/vnd.ms-excel'
                  });
                  window.navigator.msSaveBlob(blob, exportParams.filename + '.xlsx');
                } else {
                  let url = window.URL.createObjectURL(new Blob([data]));
                  let link = document.createElement('a');
                  link.style.display = 'none';
                  link.href = url;
                  link.setAttribute('download', exportParams.filename + '.xlsx');
                  document.body.appendChild(link);
                  link.click();
                }
              }
            };
          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.$refs.dictDataTable.closeExportDownload();
        });
    }
  }
};
</script>

<style lang="scss" scoped></style>
