<template>
  <div class="page-view flex-row-sb">
    <app-sync-tree
      ref="appAsyncTree"
      :actions="treeActions"
      :default-data="{ customConfigField: 'custom config field' }"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-all="expandAll"
      :fields="treeFields"
      :props="treeProps"
      :request-method="getTreeNodes"
      highlight-first
      title="贴源层目录"
      @select="onTreeNodeClick"
    />

    <div class="page-view flex-1 ml-11">
      <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 :filter-config="{ operation: 'EQUAL' }" :span="6" el-type="input" label="表资源名称">
          <el-input v-model="filters.name" clearable placeholder="请输入"
                    @keyup.enter.native="$refs['app-filter'].query"
          />
        </app-filter-item>
        <app-filter-item :span="6" label="表资源编码">
          <el-input v-model="filters.code" clearable placeholder="请输入"
                    @keyup.enter.native="$refs['app-filter'].query"
          />
        </app-filter-item>
      </app-filter>

      <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
        <app-table
          :column="columns"
          :pagination="pagination"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          @pagination-change="onPaginationChange"
          @row-dblclick="showDetail"
        >
          <template #deployed="scope">
            <el-tag :type="scope.row['deployed'] === 1 ? '' : 'danger'">
              {{ scope.row['deployed'] === 1 ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </app-table>
      </div>
      <app-dialog v-model="downVisible" append-to-body class="down-dialog" hide-footer title="数据导入" width="400px">
        <div class="mb-35">请先下载模板，填写完成后再导入</div>
        <div class="btn-row flex-row-e-c">
          <el-button :loading="uploadLoading" class="mr-10" icon="el-icon-download" size="mini" type="text"
                     @click="downLoad"
          > 下载模板
          </el-button>
          <el-upload
            ref="upload"
            :action="actionUrl"
            :data="uploadFilter"
            :headers="headers"
            :multiple="false"
            :show-file-list="false"
            v-bind="{ ...UPLOAD_CONFIG }"
          >
            <el-button :loading="uploadLoading" icon="el-icon-upload2" size="mini" type="primary">导入表数据</el-button>
          </el-upload>
        </div>
      </app-dialog>
    </div>

    <detail-dialog v-model="dialogVisible" :data="currentRow" :ods-catalogs-id="curNode.id" :title="dialogTitle" />
  </div>
</template>

<script>
import DetailDialog from '@/views/dataResource/sourceLayer/tyDataManageQuery/DetailDialog.vue';
import tableMixin from '@/mixins/table.js';
import API from '@/api/business/dataODSCatalog';
import { mapState } from 'vuex';

export default {
  name: '',
  components: { DetailDialog },
  mixins: [tableMixin],
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name',
      },
      expandAll: false,
      defaultExpandedKeys: ['1'],
      // 此处fields内配置对象属性包括: label/prop/rules/type(枚举:switch/number/input(默认))/span/
      treeFields: [
        { label: '目录名称', prop: 'name', rules: [{ required: true, message: '资源目录名称不能为空' }] },
        { label: '目录编码', prop: 'code', rules: [{ required: true, message: '资源目录编码不能为空' }] },
      ],
      curNode: {}, // 当前选择节点
    };
    const TABLE_CONFIG = {
      // 列表表头
      columns: [
        { label: '表资源名称', prop: 'name' },
        { label: '表资源编码', prop: 'code', width: '300' },
        { label: '数据库表名', width: '200', prop: 'tableNameEn' },
        {
          label: '是否发布',
          prop: 'deployed',
          width: '150',
          align: 'center',
          dataType: 'slot', // 使用插槽
          slot: 'deployed', // 插槽名，搭配 dataType: 'slot' 使用
        },
        {
          dataType: 'option',
          label: '操作',
          width: '200px',
          fixed: 'right',
          operation: [
            {
              name: '导入数据',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-upload2',
              plain: true,
              disabled: (row) => {
                return row.deployed !== 1;
              },
              clickFun: (row) => {
                this.currentRow = row;
                this.downVisible = true;
              },
            },
            {
              name: '查看数据',
              icon: 'el-icon-tickets',
              // showHide: (row) => {},
              clickFun: (row) => {
                this.currentRow = row;
                this.dialogTitle = `${row.name} - 数据信息`;
                this.dialogVisible = true;
              },
            },
          ],
        },
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'odsCatalogsId',
          relation: 'AND',
          value: '',
        },
        {
          operation: 'EQUAL',
          property: 'deployed',
          relation: 'AND',
          value: '1',
        },
      ],
    };
    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '',

    };
    const UPLOAD_CONFIG = {
      beforeUpload: (file) => {
        return new Promise((resolve, reject) => {
          this.uploadLoading = true;
          const { size, name } = file;
          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();
        });
      },
      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.downVisible = false;
        } else {
          this.$message.error(res.message);
        }
      },
    };

    return {
      ...TREE_CONFIG,
      ...TABLE_CONFIG,
      ...DIALOG_CONFIG,
      UPLOAD_CONFIG, // 抽屉相关
      downVisible: false,
      uploadLoading: false,
    };
  },
  computed: {
    actionUrl: (_) => `${window.context.portal}/biz/dataResource/odsTable/v1/importMain`,
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
    uploadFilter() {
      return this.currentRow?.id
        ? {
          tableId: this.currentRow.id,
        }
        : {};
    },
    dataMethod() {
      return API.getSourceList;
    },
    // initRefresh: () => false,
  },
  methods: {
    async getTreeNodes() {
      const { value } = await API.queryTreeData();
      this.defaultExpandedKeys = [value?.[0].id || ''];
      return { data: value || [] };
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return;
      this.curNode = { ...node };
      // this.filters['odsCatalogsId'] = node.id;
      // this.refresh();
      this.getData();
    },
    reloadTree() {
      this.$refs.appAsyncTree.getTreeData();
    },
    /**
     * @description: treeActions支持函数也支持数组，由于实际场景当中 可能会动态设置按钮，故以函数示例来展示
     * @param {*} data 当前点击节点数据
     * @return {*} 当前节点展示的操作项数组
     */
    treeActions(data) {
      // 根节点判断方式以业务为准，此处仅为示例
      return [
        { label: '添加', type: 'add', method: this.addNode },
        {
          label: '编辑',
          type: 'edit',
          method: this.editNode,
          showHide: (row) => {
            return row.id !== '1';
          },
        },
        {
          label: '删除',
          type: 'delete',
          method: this.delNode,
          showHide: (row) => {
            return row.id !== '1';
          },
        },
      ];
    },
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'deployed', '1');
      this.setFilterValue(this.queryParams, this.defaultFilter, 'odsCatalogsId', this.curNode.id);
    },
    async downLoad() {
      try {
        this.uploadLoading = true;
        await API.downLoadFile(this.currentRow.id);
      } catch (e) {
        console.log(e.message || '下载失败');
      } finally {
        this.uploadLoading = false;
      }
    },

    async addNode(params, node) {
      const { code, name } = params;
      const { id } = node;
      const newNode = {
        code,
        name,
        parentId: id,
      };
      try {
        const { state, message } = await API.addTreeNode(newNode);
        if (state) {
          this.reloadTree();
          this.$message.success('添加资源目录成功！');
        } else {
          this.$message.warning(message || '添加贴源层目录失败！');
        }
      } catch (err) {
        this.$message.warning(err || '添加贴源层目录失败！');
      }
    },
    // 编辑
    async editNode(params) {
      const { code, name, parentId, id } = params;
      const newNode = {
        code,
        name,
        id,
        parentId,
      };
      try {
        const { state, message } = await API.editTreeNode(newNode);
        if (state) {
          this.reloadTree();
          this.$message.success('编辑贴源层目录成功！');
        } else {
          this.$message.warning(message || '编辑贴源层目录失败！');
        }
      } catch (err) {
        this.$message.warning(err || '编辑贴源层目录失败！');
      }
    },
    // 删除
    async delNode(params, node) {
      try {
        const { state, message } = await API.delTreeNode(node.id);
        if (state) {
          this.reloadTree();
          this.$message.success('删除贴源层目录成功！');
        } else {
          this.$message.warning(message || '删除贴源层目录失败！');
        }
      } catch (err) {
        this.$message.warning(err || '删除贴源层目录失败！');
      }
    },
    dataAdd() {
      this.dialogTitle = '新增贴源层数据源';
      this.dialogVisible = true;
    },
    async onAddConfirm(source) {
      /** 先注释*/

      const params = {
        catalogId: this.curNode.id,
        tableId: source.id,
      };

      try {
        await API.addByCompanySource(params);
        this.$message.success('操作成功');
        // this.$me
        // this.refresh();
      } catch (error) {
        console.log(error);
      }

      console.log(params);
    },
    showDetail() {
    },
  },
};
</script>

<style lang="scss" scoped>
.com {
  transition: opacity 0.3s;
}

.leave {
  opacity: 0;
}

.down-dialog {
  display: flex;
  justify-content: center;
  align-items: center;

  ::v-deep {
    .gz-dialog {
      margin: 0px !important;
      min-height: 0;
    }

    .app-dialog-content {
      height: auto;
    }
  }
}
</style>
