<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="btns">
          <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>
          <el-button type="primary" icon="el-icon-download" @click="exportDownload()">导出</el-button>
        </div>
        <el-table :data="tableData" ref="singleTable" highlight-current-row class="dictTypeTable">
          <el-table-column align="center" width="55">
            <template slot-scope="scope">
              <el-radio :label="scope.$index" v-model="checked" @change.native="getCurrentRow(scope.row)" class="radio"></el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="dictName" label="字典名称"></el-table-column>
          <el-table-column prop="dictType" label="字典类型"></el-table-column>
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button type="text" size="mini" style="font-size: 14px; border: 0" @click="addOrUpdateHandle(scope.row)">修改</el-button>
              <!-- <el-button type="text" size="mini" style="font-size: 14px; border: 0" @click="deleteBatchHandle(scope.row.id)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="searchForm.pageIndex"
            :page-size="searchForm.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalCount"
          ></el-pagination>
        </div>
      </el-col>
      <el-col :span="1">
        <div class="divider"></div>
      </el-col>
      <el-col :span="15">
        <DictDataTable :row="currentRow" :baseApi="baseApi" :TokenKey="TokenKey"></DictDataTable>
      </el-col>
    </el-row>
    <DictTypeDialog :show.sync="typeVisible" :row="row" :baseApi="baseApi" :TokenKey="TokenKey" @refreshList="getTableData"></DictTypeDialog>
  </div>
</template>

<script>
import axios from 'axios';
import DictTypeDialog from './components/dictTypeDialog.vue';
import DictDataTable from './components/dictDataTable.vue';

export default {
  name: 'fireflyDictionary',
  components: {
    DictTypeDialog,
    DictDataTable
  },
  props: {
    baseApi: {
      type: String,
      default: ''
    },
    TokenKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      searchForm: {
        pageIndex: 1,
        pageSize: 10,
        dictName: '',
        dictType: '',
        status: ''
      },
      totalCount: 0,
      tableHeader: [],
      tableData: [],
      typeVisible: false, // 字典类型
      row: {},
      currentRow: {},
      checked: ''
    };
  },

  created() {
    this.getTableData();
  },

  methods: {
    getTableData() {
      this.loading = true;
      axios({
        method: 'get',
        url: `${this.baseApi}/system/dict/type/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;
              if (res.data.length > 0) {
                this.getCurrentRow(res.data[0]);
                this.checked = 0;
              }
              this.totalCount = res.pageInfo.totalCount;
            } else {
              this.$message.error(`${res.message}`);
            }
          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleCurrentChange(val) {
      this.searchForm.pageIndex = val;
      this.getTableData();
    },

    getCurrentRow(row) {
      if (row && row.id) {
        this.currentRow = { ...row };
      }
    },

    // 新增 & 修改
    addOrUpdateHandle(row) {
      if (row && row.id) {
        this.row = { ...row };
      }
      this.typeVisible = true;
    },

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

    // 导出
    exportDownload() {
      axios({
        method: 'get',
        responseType: 'blob',
        url: `${this.baseApi}/system/dict/type/export`,
        headers: {
          Authorization: `Bearer ${localStorage.getItem(this.TokenKey)}`
        }
      })
        .then(response => {
          const { status } = response;
          if (status === 200) {
            if (response.data.type === 'application/vnd.ms-excel') {
              // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
              const fileName = response.headers['content-disposition'].split('=')[1];
              const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
              const url = window.URL.createObjectURL(blob);
              const a = document.createElement('a'); // 创建a标签
              a.href = url;
              a.download = decodeURIComponent(fileName);
              a.click();
              document.body.removeChild(a);
              URL.revokeObjectURL(url); // 释放内存
            } else {
              const reader = new FileReader();
              reader.onload = function (eventa) {
                const msg = JSON.parse(reader.result).message;
                ElMessage.error(msg);
              };
              reader.readAsText(response.data);
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.link {
  color: #1e97f8;
  cursor: pointer;
}
.btns {
  margin-bottom: 10px;
}
.divider {
  width: 10px;
  background-color: #f6f7f9;
  height: calc(100vh - 118px);
}
.radio {
  :deep .el-radio__label {
    display: none;
  }
}
.pagination {
  margin-top: 10px;
  text-align: right;
}
:deep .dictTypeTable.el-table th.el-table__cell > .cell {
  color: #62606e;
}
</style>
