<template>
  <div class="page-view border-radius-5">
    <div class="flex-row bg-white px-15 border-radius-5">
      <el-page-header content="" @back="handleBack" />
      <!--      (true, { clusterId: $route.query.id })-->
      <app-filter ref="app-filter" :model="filters" class="flex-1" @query="onQuery" @reset="onReset">
        <app-filter-item label="表资源名称" prop="name">
          <el-input v-model="filters.name" clearable placeholder="请输入" @keyup.enter.native="$refs['app-filter'].query" />
        </app-filter-item>
        <app-filter-item label="表资源编码" prop="code">
          <el-input v-model="filters.code" clearable placeholder="请输入" @keyup.enter.native="$refs['app-filter'].query" />
        </app-filter-item>
      </app-filter>
    </div>

    <div class="flex-1 bg-white flex-col border-radius-5 pa-11 mt-11">
      <div class="mb-11">
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="addSource"> 添加表</el-button>
        <!--        <el-button icon="el-icon-document-copy" size="mini" type="primary" @click="copyChange"> 复制表</el-button>-->
        <el-popover v-model="uploadVisible" placement="bottom">
          <p>请先下载模板，填写完成后上传</p>
          <div class="text-c flex-row-c">
            <el-button class="mr-10" size="mini" type="text" @click="download">下载模板</el-button>
            <el-upload ref="upload" :action="actionUrl" :headers="headers" :multiple="false" :show-file-list="false" v-bind="{ ...UPLOAD_CONFIG }">
              <el-button size="mini" type="primary">导入表</el-button>
            </el-upload>
          </div>
          <el-button slot="reference" :loading="uploadLoading" class="ml-10" icon="el-icon-upload2" size="mini" type="primary"> 导入表 </el-button>
        </el-popover>
      </div>
      <app-table
        :column="columns"
        :pagination="pagination"
        :table-data="tableData"
        :table-loading="tableLoading"
        :total="total"
        @row-dblclick="editSource"
        @pagination-change="onPaginationChange"
      >
        <template #deployed="scope">
          <el-tag :type="scope.row['deployed'] === 1 ? '' : 'danger'">{{ scope.row['deployed'] === 1 ? '已发布' : '未发布' }} </el-tag>
        </template>
      </app-table>
    </div>

    <trigger-dialog v-model="triggerVisible" :data="currentRow" title="查看触发器" @confirm="refresh" />
    <fields-manage v-model="dialogVisible" :data="currentRow" title="字段管理" @confirm="refresh" />
    <manual-dialog v-model="manualVisible" :cluster-id="filters.clusterId" :data="currentRow" :title="manualTitle" @confirm="refresh" />

    <copy-dialog v-model="copyVisible" :cluster-id="filters.clusterId" :data="currentRow" @confirm="refresh" />
    <put-out-dialog v-model="putOutVisible" :cluster-id="filters.clusterId" :data="currentRow" @confirm="refresh" />
  </div>
</template>

<script>
import API from '@/api/business/dataCollectCompany';
import tableMixin from '@/mixins/table.js';
import FieldsManage from './FieldsManage';
import ManualDialog from './ManualDialog';
import TriggerDialog from './TriggerDialog';
import CopyDialog from './CopyDialog';
import PutOutDialog from './PutOutDialog';
import { mapState } from 'vuex';
import DICT from '@/utils/dict';

export default {
  components: { FieldsManage, ManualDialog, TriggerDialog, CopyDialog, PutOutDialog },
  mixins: [tableMixin],
  props: {
    providerRow: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    const TABLE_CONFIG = {
      columns: [
        { label: '表资源名称', prop: 'name' },
        { label: '表资源编码', prop: 'code', width: '400' },
        // {
        //   label: '资源密级',
        //   prop: 'level',
        //   width: '100',
        //   align: 'center',
        //   formatData: (val) => {
        //     return this.filterDict('SECRET_LEVEL', val).label;
        //   },
        // },
        // {
        //   label: '资源格式',
        //   prop: 'sourceType',
        //   width: '100',
        //   align: 'center',
        //   formatData: (val) => {
        //     return this.filterDict('SOURCE_FILE_TYPE', val).label;
        //   },
        // },
        // {
        //   label: '物理实体表中文名',
        //   width: '200',
        //   prop: 'tableNameCh',
        // },
        // {
        //   label: '物理实体表英文名',
        //   width: '200',
        //   prop: 'tableNameEn',
        // },
        { label: '数据库表名', prop: 'tableNameEn', width: '350' },
        // {
        //   label: '提供方式',
        //   prop: 'source',
        //   width: '100',
        //   align: 'center',
        //   formatData: val => {
        //     return this.filterDict('SOURCE_PROVIDED_TYPE', val).label;
        //   },
        // },
        {
          label: '是否发布',
          prop: 'deployed',
          width: '150',
          align: 'center',
          dataType: 'slot', // 使用插槽
          slot: 'deployed', // 插槽名，搭配 dataType: 'slot' 使用
        },
        {
          dataType: 'option',
          label: '操作',
          width: '280px',
          fixed: 'right',
          operation: [
            {
              name: '字段管理',
              type: 'text',
              size: 'mini',
              color: '#409eff',
              icon: 'el-icon-s-order',
              plain: true,
              clickFun: (row) => {
                this.currentRow = row;
                this.dialogVisible = true;
              },
            },
            {
              name: '发布建表',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-s-promotion',
              color: '#fa912a',
              plain: true,
              showHide: (row) => {
                return row.deployed !== 1;
              },
              clickFun: (row) => {
                this.publishTable(row);
              },
            },
            {
              name: '查询建表SQL',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-document',
              plain: true,
              showHide: (row) => {
                return row.deployed === 1;
              },
              clickFun: (row) => {
                this.currentRow = row;
                this.triggerVisible = true;
              },
            },
            {
              name: '复制表',
              type: 'text',
              size: 'mini',
              color: '#407cff',
              icon: 'el-icon-document-copy',
              plain: true,
              showHide: (row) => {
                return row.deployed === 1;
              },
              clickFun: (row) => {
                this.copyChange(row);
              },
            },
            // {
            //   name: '创建触发器',
            //   type: 'text',
            //   size: 'mini',
            //   icon: 'el-icon-position',
            //   plain: true,
            //   // showHide: (row) => {
            //   //   return row.deployed === 1;
            //   // },
            //   clickFun: (row) => {
            //     this.triggerChange(row);
            //   },
            // },
            {
              name: '删除',
              type: 'text',
              color: 'red',
              icon: 'el-icon-delete',
              plain: true,
              // showHide: row => {
              //   return row.deployed !== 1;
              // },
              clickFun: (row) => {
                this.delSource(row);
              },
            },
          ],
        },
      ],
    };

    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '新增',
      manualVisible: false,
      manualTitle: '新增',
      copyVisible: false,
      putOutVisible: false,
    };

    const UPLOAD_CONFIG = {
      beforeUpload: (file) => {
        return new Promise((resolve, reject) => {
          this.uploadLoading = true;
          const { size, name } = file;
          this.$confirm(`请确认是否导入 “${name}” ？`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then((_) => {
              let passedOrNot = true; // 是否通过验证
              const typeRegular = /\.(xls|xlsx)$/i;
              const verification = [
                {
                  condition: !typeRegular.test(name),
                  result: () => this.$message.error('只能上传xls或xlsx文件类型'),
                },
              ];
              verification.forEach((item) => {
                if (item.condition) {
                  item.result();
                  passedOrNot = false;
                  this.uploadLoading = false;
                }
              });

              passedOrNot ? resolve() : reject();
            })
            .catch((_) => {
              reject();
              this.uploadLoading = false;
              this.$message.warning('已取消上传');
            });
        });
      },
      data: {
        clusterInfoId: this.$route.query.id,
      },
      onError: (res) => {
        const res_ = JSON.parse(res.message);
        this.$message.error(res_.message || '导入失败，请重试');
        this.uploadLoading = false;
      },
      onSuccess: async (res) => {
        if (res.state) {
          this.$message.success('导入成功');
          this.uploadLoading = false;
          this.refresh();
        } else {
          this.$message.error(res.message);
        }
      },
    };

    return {
      ...TABLE_CONFIG, // table相关
      ...DIALOG_CONFIG, // 主列表dialog相关
      UPLOAD_CONFIG, // 抽屉相关
      uploadVisible: false,
      uploadLoading: false,
      triggerVisible: false,
      clusterId: '',
    };
  },
  computed: {
    actionUrl: (_) => `${window.context.portal}/biz/dataCollect/clusterTable/v1/importFile`,
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
    dataMethod() {
      return API.getDataSourceList;
    },
    // initRefresh: () => false,
  },
  watch: {
    '$route.query.id': {
      immediate: true,
      handler(id) {
        if (id) {
          this.filters.clusterId = id;
          this.refresh();
        }
      },
    },
  },
  methods: {
    async triggerChange(row) {
      const { state } = await API.createdTriggerChange(row.id);
      if (state) {
        this.getData();
        this.$message.success('创建成功！');
      } else {
        this.$message.warning('创建失败！');
      }
    },
    async publishTable(data) {
      this.currentRow = data;
      this.putOutVisible = true;
      // this.$confirm(`此操作将发布（${data.name}）, 是否继续?`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // })
      //   .then(async () => {
      //     try {
      //       const { state, message } = await API.publishTable(data.id);
      //       if (state) {
      //         this.getData();
      //         console.log(11111);
      //         this.$message.success('资源项发布成功！');
      //       } else {
      //         console.log(2222);
      //         this.$message.warning(message || '资源项发布失败！');
      //       }
      //     } catch (err) {
      //       console.log(3333);
      //       // this.$message.warning(err || '资源项发布失败！');
      //     }
      //   })
      //   .catch(() => {
      //   });
    },

    handleBack() {
      this.$router.push({
        name: 'dataCollectCompany',
      });
    },
    filterDict(dictKey, val) {
      const def = { label: '', value: val };
      if ([null, undefined, ''].includes(val)) {
        return def;
      }
      return DICT[dictKey].find((item) => item.value === val) || def;
    },
    download() {
      const file = '数据提供方-数据资源表清单.xlsx';
      const a = document.createElement('a');
      a.href = window.context.download + file;
      a.download = file;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      a.remove();
    },
    addSource() {
      this.manualTitle = '新增';
      this.currentRow = null;
      this.manualVisible = true;
    },
    editSource(row) {
      this.manualTitle = `${row.deployed ? '详情' : '编辑'} - ${row.name}`;
      this.currentRow = row;
      this.manualVisible = true;
    },
    delSource(row) {
      this.$confirm(`此操作将永久删除资源项（${row.name}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await API.delSource(row.id);
        this.$message.success('删除成功');
        this.refresh();
      });
    },
    // onCompanyConfirm(data) {
    //   const id = this.tableData.length++;
    //   if (data?.id) {
    //     const ind = this.tableData.findIndex((o) => o.id == data.id);
    //     ind >= 0 && this.tableData.splice(ind, 1, data);
    //   } else {
    //     this.tableData.push({ ...data, id });
    //   }
    //   this.dialogVisible = false;
    // },
    copyChange(row) {
      this.copyVisible = true;
      this.currentRow = row;
    },
  },
};
</script>
