<template>
  <div class="page-view">
    <app-filter ref="app-filter" :model="filters" class="bg-white px-15 border-radius-5" label-width="90px"
                @query="onQuery" @reset="onReset"
    >
      <app-filter-item :span="2">
        <el-button @click="gotodataCatalog"><span><&nbsp;</span>返回</el-button>
      </app-filter-item>
      <app-filter-item :span="6" label="文件名称">
        <el-input v-model="filters.fileName" clearable placeholder="请输入"
                  @keyup.enter.native="$refs['app-filter'].query"
        />
      </app-filter-item>
      <app-filter-item :span="6" label="是否生成">
        <el-select v-model="filters.isCreate" clearable placeholder="请选择"
                   @keyup.enter.native="onQuery(filters)"
        >
          <el-option v-for="item in createdList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </app-filter-item>
    </app-filter>

    <!-- 列表组件 -->
    <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
      <div class="mb-15">
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="addData"> 新增</el-button>
        <el-button icon="el-icon-delete" size="mini" type="danger" @click="deleteRowChange">删除</el-button>
      </div>
      <app-table
        :column="columns"
        :pagination="pagination"
        :table-data="tableData"
        :table-loading="tableLoading"
        :total="total"
        checkbox
        @select-change="selectChange"
        @pagination-change="onPaginationChange"
        @row-dblclick="editData"
      >
        <!-- 插槽 -->
        <template #filePath="scope">
          <el-link type="primary">{{ scope.row.filePath }}</el-link>
        </template>
        <template #isCreate="scope">
          <el-tag :type="scope.row.isCreate === '1' ? 'primary' : 'warning'">
            {{ scope.row.isCreate === '1' ? '已生成' : '未生成' }}
          </el-tag>
        </template>
      </app-table>
    </div>

    <!-- dialog组件 -->
    <add-edit-dialog v-model="dialogVisible" :data="currentRow" :table-id="tabledId" :title="dialogTitle"
                     @confirm="onCompanyConfirm"
    />

    <!-- 资源授权 -->
    <resource-authorize v-if="resourceDialog" v-model="resourceDialog" :data="currentRow" :resource-id="currentRow.id"
                        :table-id="tabledId"
                        title="资源授权"
                        xqf-type="2"
    />
  </div>
</template>
<script>
import tableMixin from '@/mixins/table.js'; // 列表mixins
import AddEditDialog from './AddEditDialog.vue';
import API from '@/api/business/shareDataCatalog';
import ResourceAuthorize from '@/views/dataResource/dataShare/shareDataCatalog/ResourceAuthorize.vue';

export default {
  components: { ResourceAuthorize, AddEditDialog },
  mixins: [tableMixin],
  data() {
    const TABLE_CONFIG = {
      createdList: [
        { label: '已生成', value: '1' },
        { label: '未生成', value: '0' },
      ],
      // 列表表头
      columns: [
        { label: '文件名称', prop: 'fileName', align: 'center', width: '250px' },
        { label: '文件描述', prop: 'fileContent', align: 'center' },
        { label: '下载地址', prop: 'filePath', dataType: 'slot', slot: 'filePath', width: '350px', align: 'center' },
        { label: '文件类型', prop: 'fileType', width: '150px', align: 'center' },
        { label: '是否生成', prop: 'isCreate', dataType: 'slot', slot: 'isCreate', width: '150px', align: 'center' },
        {
          dataType: 'option',
          label: '操作',
          width: '230px',
          fixed: 'right',
          align: 'center',
          operation: [
            {
              name: '资源授权',
              icon: 'el-icon-setting',
              clickFun: row => {
                this.resourceChange(row);
              },
            },
            {
              name: '下载',
              icon: 'el-icon-download',
              showHide: (row) => {
                return row.isCreate === '1';
              },
              clickFun: (row) => {
                this.downloadTheFile(row);
              },
            },
            {
              name: '生成',
              icon: 'el-icon-paperclip',
              showHide: (row) => {
                return row.isCreate === '0';
              },
              clickFun: (row) => {
                this.spannedFileChange(row);
              },
            },
            {
              name: '删除',
              icon: 'el-icon-delete',
              color: 'red',
              clickFun: (row) => {
                this.delTable(row);
              },
            },
          ],
        },
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'tableId',
          relation: 'AND',
          value: '',
        },
      ],
    };

    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '新增',
    };

    return {
      ...TABLE_CONFIG, // table相关
      ...DIALOG_CONFIG, // 主列表dialog相关
      tabledId: '',
      resourceDialog: false,
      multipleSelection: [],
    };
  },
  computed: {
    dataMethod() {
      return API.fileResourceList;
    },
  },
  mounted() {
    if (this.$route.query) {
      this.tabledId = this.$route.query.id;
    }
  },
  methods: {
    // 资源授权
    resourceChange(row) {
      this.currentRow = row;
      this.resourceDialog = true;
    },
    // 左边树
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'tableId', this.tabledId);
    },
    // 返回
    gotodataCatalog() {
      this.$router.back();
    },
    onCompanyConfirm(data) {
      this.refresh();
    },

    addData() {
      this.dialogTitle = '新增';
      this.currentRow = null;
      this.dialogVisible = true;
    },
    editData(row) {
      this.dialogTitle = `编辑 - ${row.fileName}`;
      this.currentRow = row;
      this.dialogVisible = true;
    },

    selectChange(data) {
      this.multipleSelection = [];
      data.forEach((item) => {
        this.multipleSelection.push(item.id);
      });
    },

    // 删除事件
    async deleteRowChange() {
      const delId = JSON.parse(JSON.stringify(this.multipleSelection)).join(',');
      this.$confirm('是否删除选中数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const { state } = await API.fileRemoveTableDelete(delId);
          if (state) {
            await this.getData();
            this.$message.success('删除成功！');
          }
        } catch (err) {
          this.$message.warning(err || '删除失败！');
        }
      });
    },
    // 个别删除
    delTable(row) {
      this.$confirm(`此操作将删除（${row.fileName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const { state, message } = await API.fileRemoveDelete(row.id);
            if (state) {
              await this.getData();
              this.$message.success('删除成功！');
            } else {
              this.$message.warning(message || '删除失败！');
            }
          } catch (err) {
            this.$message.warning(err || '删除失败！');
          }
        })
        .catch(() => {
        });
    },
    // 下载文件
    async downloadTheFile(row) {
      await API.fileUpload(row.id);
    },
    // 生成文件
    spannedFileChange(row) {
      this.$confirm('此操作将生成文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const param = new FormData();
            param.append('id', row.id);
            const { state } = await API.spannedFile(param);
            if (state) {
              await this.getData();
              this.$message.success('生成成功！');
            }
          } catch (err) {
            this.$message.warning(err || '生成失败！');
          }
        })
        .catch(() => {
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__cell:first-child .cell {
  text-align: center;
}
</style>
