<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.apiName" clearable placeholder="请输入"
                  @keyup.enter.native="$refs['app-filter'].query"
        />
      </app-filter-item>
      <!--      <app-filter-item label="接口状态">-->
      <!--        &lt;!&ndash;        <el-radio-group v-model="filters.status">&ndash;&gt;-->
      <!--        &lt;!&ndash;          <el-radio-button v-for="radio in createdList" :key="radio.value" :label="radio.value">{{ radio.label }} </el-radio-button>&ndash;&gt;-->
      <!--        &lt;!&ndash;        </el-radio-group>&ndash;&gt;-->
      <!--        <el-select v-model="filters.status" filterable placeholder="请选择" @keyup.enter.native="$refs['app-filter'].query">-->
      <!--          <el-option v-for="item in createdList" :key="item.value" :label="item.label" :value="item.label" />-->
      <!--        </el-select>-->
      <!--      </app-filter-item>-->
      <app-filter-item label="请求方式" prop="apiMode">
        <el-select v-model="filters.apiMode" filterable placeholder="请选择"
                   @keyup.enter.native="$refs['app-filter'].query"
        >
          <el-option v-for="item in createdList" :key="item.value" :label="item.label" :value="item.label" />
        </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 :disabled="!selectDataList.length > 0" icon="el-icon-delete" size="mini" type="danger" @click="delCompany">删除 </el-button>-->
      </div>
      <app-table
        :column="columns"
        :pagination="pagination"
        :table-data="tableData"
        :table-loading="tableLoading"
        :total="total"
        @pagination-change="onPaginationChange"
        @selection-change="handleSelectionChange"
        @row-dblclick="editData"
      >
        <!--checkbox-->
        <!-- 插槽 -->
        <template #url="scope">
          <el-link type="primary">{{ scope.row.url }}</el-link>
        </template>
        <template #apiMode="scope">
          <el-tag :type="determineTagType(scope.row.apiMode)">{{ scope.row.apiMode }}</el-tag>
        </template>
        <template #status="scope">
          <el-tag :type="scope.row.status==='1' ? 'primary' : 'danger'">{{ scope.row.status === '1' ? '正式' : '下架'
          }}
          </el-tag>
        </template>
      </app-table>
    </div>

    <!-- dialog组件 -->
    <add-edit-dialog v-model="dialogVisible" :data="dialogdData" :related-id="currentId" :title="dialogTitle"
                     @confirm="onConfirm"
    />
    <!-- 编辑/详情组件 @data-added="fetchUpdatedData"-->
    <detail-dialog v-model="detailVisible" :data="dialogdData" :related-id="currentId" :title="detailTitle"
                   @confirm="onConfirm"
    />
    <!-- 查看日志的弹层-->
    <service-dialog v-model="dialogService" :data="currentRow" :title="dialogServiceTitle" />
    <!--接口详情-->
    <show-dialog v-model="dialogDetails" :data="currentRow" :title="dialogDetailsTitle" />

    <!-- 资源授权 -->
    <resource-authorize v-if="resourceDialog" v-model="resourceDialog" :data="currentRow" :resource-id="currentRow.id"
                        :table-id="currentId"
                        title="资源授权"
                        xqf-type="3"
    />
  </div>
</template>

<script>
import tableMixin from '@/mixins/table.js'; // 列表mixins
import AddEditDialog from './AddEditDialog.vue';
import ShowDialog from './ShowDialog.vue';
import API from '@/api/business/shareApi';
import ServiceDialog from '@/views/dataResource/dataServices/dataServiceAPI/ServiceDialog.vue';
import DetailDialog from '@/views/dataResource/dataServices/dataServiceAPI/DetailDialog.vue';
import ResourceAuthorize from '@/views/dataResource/dataShare/shareDataCatalog/ResourceAuthorize.vue';

export default {
  components: { ResourceAuthorize, DetailDialog, ServiceDialog, ShowDialog, AddEditDialog },
  mixins: [tableMixin],
  data() {
    const TABLE_CONFIG = {
      createdList: [
        { label: 'GET', value: '1' },
        { label: 'POST', value: '0' },
      ],
      // 列表表头
      columns: [
        { label: '接口名称', prop: 'apiName', align: 'center', width: '300px' },
        { label: '接口地址', prop: 'apiUrl', width: '350px', align: 'center' },
        { label: '请求方式', prop: 'apiMode', dataType: 'slot', slot: 'apiMode', width: '150px', align: 'center' },
        { label: '数据库别名', prop: 'dbAlias', align: 'center' },
        { label: '接口状态', prop: 'status', dataType: 'slot', slot: 'status', width: '150px', align: 'center' },
        {
          dataType: 'option',
          label: '操作',
          fixed: 'right',
          operation: [
            {
              name: '资源授权',
              icon: 'el-icon-setting',
              clickFun: (row) => {
                this.resourceChange(row);
              },
            },
            {
              name: '接口信息',
              icon: 'el-icon-document',
              clickFun: (row) => {
                this.detailsShow(row);
              },
            },
            {
              name: '发布',
              icon: 'el-icon-s-promotion',
              color: '#fa912a',
              showHide: (row) => {
                return row.status !== 1;
              },
              clickFun: (row) => {
                this.publishTable(row);
              },
            },
            {
              name: '查看日志',
              icon: 'el-icon-document',
              clickFun: (row) => {
                this.serviceshow(row);
              },
            },
            {
              name: '删除',
              icon: 'el-icon-delete',
              color: 'red',
              clickFun: (row) => {
                this.delCompany(row);
              },
            },
          ],
        },
      ],
    };

    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '新增',
      dialogDetails: false,
      dialogDetailsTitle: '接口详情',
      dialogdData: {},
      dialogService: false,
      dialogServiceTitle: '查看日志',
      detailVisible: false,
      detailTitle: '编辑',
      resourceDialog: false,
    };

    return {
      ...TABLE_CONFIG, // table相关
      ...DIALOG_CONFIG, // 主列表dialog相关
      selectDataList: [],
      currentId: null,
    };
  },
  computed: {
    // 配置列表接口方法；只有配置了该计算属性才会执行table mixins中的getData方法
    dataMethod() {
      return API.apiList;
    },
  },
  created() {
    this.currentId = this.$route.query.id || null;
    if (this.currentId === null) {
      console.error('No id received from the previous page');
    } else {
      console.log('-----------------', this.currentId);
    }
  },
  methods: {
    // 资源授权
    resourceChange(row) {
      this.currentRow = row;
      this.resourceDialog = true;
    },
    // apiMode标签颜色
    determineTagType(apiMode) {
      return apiMode === 'GET' ? '' : 'warning';
    },
    handleSelectionChange(val) {
      this.selectDataList = val;
      console.log(val);
    },
    addData() {
      this.dialogTitle = '新增';
      this.dialogdData = {};
      this.dialogVisible = true;
      this.$refs.addEditDialog.relatedId = this.currentId;
    },
    editData(row) {
      this.dialogTitle = `编辑 - ${row.apiName}`;
      this.dialogdData = row;
      this.dialogVisible = true;
    },
    delCompany(row) {
      // this.$confirm(`此操作将永久删除该接口（${row.apiName}）, 是否继续?`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {});
      this.$confirm(`此操作将永久删除该接口项（${row.apiName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await API.delApiData(row.id);
          console.log('111111111', row.id);
          this.getData();
          this.$message.success('删除成功');
          // 找到要删除的数据在tableData中的索引
          const index = this.tableData.findIndex((item) => item.id === row.id);
          if (index !== -1) {
            // 从tableData数组中删除对应的数据
            this.tableData.splice(index, 1);
          }
        })
        .catch((error) => {
          console.error('删除数据失败:', error);
        });
    },
    onConfirm(data) {
      this.getData();
    },
    // 返回按钮
    gotodataCatalog() {
      this.$router.back();
    },
    // 查看日志按钮
    serviceshow(row) {
      this.dialogServiceTitle = `查看日志- ${row.apiName}`;
      this.currentRow = row;
      const rowId = row.id; // 获取当前行的id
      this.dialogService = true;
      this.$refs.ServiceDialog.initData({ id: rowId }); // 将id传递给ServiceDialog组件
    },
    // 接口文档查看
    detailsShow(row) {
      this.dialogDetailsTitle = `接口详情- ${row.apiName}`;
      this.currentRow = row;
      this.dialogDetails = true;
    },
    // 发布
    async publishTable(data) {
      this.$confirm(`此操作将发布（${data.apiName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          data.status = '1';
          try {
            this.tableLoading = true;
            const { state, message } = await API.updateAction(data);
            if (state) {
              this.getData();
              this.$message.success('接口发布成功！');
            } else {
              this.tableLoading = false;
              this.$message.warning(message || '接口发布失败！');
            }
          } catch (err) {
            this.$message.warning(err || '接口发布失败！');
          }
        })
        .catch(() => {
        });
    },
  },
};
</script>

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