<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"
      :tree-options="treeData"
      title="接口目录"
      @select="onTreeNodeClick"
    >
      <!-- 此form为组件内部form 在actions配置项的method函数当中 可以获取参数 -->
      <template #default="{ form: treeForm }">
        <app-filter-item :rules="[{ required: true, message: '自定义项一不能为空' }]" :span="24" label="自定义项一" prop="customConfigField">
          <el-input v-model="treeForm.customConfigField" placeholder="请输入自定义项一" />
        </app-filter-item>
      </template>
    </app-sync-tree>
    <!-- 右侧-->
    <div class="page-view flex-1 ml-15 h-100">
      <!-- 搜索-->
      <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="6" label="接口名称" prop="apiName">
          <el-input v-model="filters.apiName" clearable placeholder="请输入" @keyup.enter.native="$refs['app-filter'].query" />
        </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.value" />
          </el-select>
        </app-filter-item>
      </app-filter>
      <!-- table列表 -->
      <div class="flex-1 pa-15 bg-white h-100 flex-col mt-15 border-radius-5">
        <div class="mb-15">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="addData"> 新增</el-button>
          <!-- icon按钮提示按钮  -->
          <tooltip-button :tooltip-text="''" />
        </div>
        <app-table
          :column="columns"
          :pagination="pagination"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          @pagination-change="onPaginationChange"
          @row-dblclick="editData"
        >
          <!-- 插槽-->
          <template #apiMode="scope">
            <el-tag :type="determineTagType(scope.row.apiMode)">{{ scope.row.apiMode }}</el-tag>
          </template>
          <!-- 接口状态  -->
          <template #status="scope">
            <el-switch v-model="scope.row.status" :active-value="true" :inactive-value="false" active-color="#13ce66" disabled inactive-color="#ff4949" />
            <!--  disabled控制是否禁用-->
          </template>
        </app-table>
      </div>
      <!-- 编辑/详情组件 -->
      <detail-dialog
        v-model="detailVisible"
        :add-id="treeId"
        :data="currentRow"
        :title="detailTitle"
        @confirm="onCompanyConfirm"
        @data-added="fetchUpdatedData"
      />
      <!--      新增-->
      <add-dialog v-model="addVisible" :add-id="treeId" :data="currentRow" :title="addTitle" @confirm="onCompanyConfirm" @data-added="fetchUpdatedData" />
      <!-- 查看日志的弹层-->
      <service-dialog v-model="dialogService" :data="currentRow" :title="dialogServiceTitle" />
      <!--接口详情-->
      <show-dialog v-model="dialogDetails" :data="currentRow" :title="dialogDetailsTitle" />
      <!-- 抽屉内部的内容 -->

      <div>
        <el-drawer :visible.sync="drawerVisible" direction="rtl" size="30%" title="接口测试">
          <div class="drawer-content">
            <!--   头部    -->
            <div class="drawer-select-input" style="margin-top: 15px">
              <el-input v-model="input1" class="input-with-select" placeholder="请输入内容">
                <el-select slot="prepend" v-model="select" placeholder="请选择">
                  <el-option label="GET" value="1" />
                  <el-option label="POST" value="2" />
                </el-select>
                <el-button slot="append" icon="el-icon-search" />
              </el-input>
            </div>
            <div class="drawer-footer">
              <template>
                <el-tabs v-model="activeName" @tab-click="handleClick">
                  <el-tab-pane label="Params" name="first" style="margin-left: 12px">
                    <el-table :data="drawerData" border style="width: 95%">
                      <el-table-column label="" prop="date" width="40" />
                      <el-table-column label="Key" prop="key" width="223" />
                      <el-table-column label="Value" prop="value" width="260" />
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </template>
            </div>
          </div>
        </el-drawer>
      </div>
    </div>
  </div>
</template>
<script>
import API from '@/api/business/dataServiceAPI';
import TooltipButton from '@/views/dataResource/dataServices/dataServiceAPI/components/TooltipButton.vue';
import ServiceDialog from '../dataServiceAPI/ServiceDialog.vue';
import DetailDialog from './DetailDialog.vue';
import AddDialog from '@/views/dataResource/dataResource/dataServices/dataServiceAPI/AddDialog.vue';
import tableMixin from '@/mixins/table.js'; // 列表mixins
import ShowDialog from '@/views/dataResource/dataResource/dataServices/dataServiceAPI/ShowDialog.vue';

export default {
  components: {
    DetailDialog,
    ServiceDialog,
    ShowDialog,
    TooltipButton,
    AddDialog,
  },
  mixins: [tableMixin],
  data() {
    // 树
    const TREE_CONFIG = {
      name: '',
      treeId: '',
      // components: {},
      treeProps: {
        value: 'id',
        label: 'label',
      },
      expandAll: false,
      defaultExpandedKeys: ['0'],
      // 此处fields内配置对象属性包括: label/prop/rules/type(枚举:switch/number/input(默认))/span/
      treeFields: [
        {
          label: '接口目录名称',
          prop: 'name',
          labelWidth: '120',
          rules: [{ required: true, message: '接口目录名称不能为空' }],
        },
        {
          label: '接口目录编码',
          prop: 'code',
          labelWidth: '120',
          rules: [{ required: true, message: '接口目录编码不能为空' }],
        },
      ],
      curNode: {}, // 当前选择节点
    };
    // table列表
    const TABLE_CONFIG = {
      filters: {
        apiMode: 1, // 请求方式默认为GET
      },
      createdList: [
        { label: 'GET', value: 1 },
        { label: 'POST', value: 0 },
      ],
      // 列表表头
      columns: [
        { label: '接口名称', prop: 'apiName', width: '200px', align: 'center' },
        { label: '接口描述', prop: 'apiDesc', width: '200px', align: 'center' },
        { label: '接口地址', prop: 'apiUrl', width: '300px', align: 'center' },
        { label: '数据库表名', prop: 'dbAlias', width: '100px', align: 'center' },
        { label: '请求方式', prop: 'apiMode', dataType: 'slot', slot: 'apiMode', width: '100px', align: 'center' },
        { label: '接口状态', prop: 'status', dataType: 'slot', slot: 'status', align: 'center' },
        {
          dataType: 'option',
          label: '操作',
          width: '230px',
          fixed: 'right',
          align: 'center',
          operation: [
            {
              name: '测试',
              icon: 'el-icon-s-unfold',
              clickFun: (row) => {
                this.showDrawer(row);
              },
            },
            {
              name: '查看日志',
              icon: 'el-icon-document',
              clickFun: (row) => {
                this.serviceshow(row);
              },
            },
            {
              name: '接口文档查看',
              icon: 'el-icon-tickets',
              clickFun: (row) => {
                this.detailsshow(row);
              },
            },
            {
              name: '设置接口状态',
              icon: 'el-icon-share',
              clickFun: (row) => {
                this.changestatus(row);
              },
            },
            {
              name: '删除',
              icon: 'el-icon-delete',
              color: 'red',
              clickFun: (row) => {
                this.delApi(row);
              },
            },
          ],
        },
      ],
    };
    // dialog弹出
    const DIALOG_CONFIG = {
      detailVisible: false,
      addVisible: false,
      dialogService: false,
      dialogDetails: false,
      drawerVisible: false, // 控制抽屉显示和隐藏的变量
      detailTitle: '编辑',
      addTitle: '新增',
      dialogServiceTitle: '查看日志',
      dialogDetailsTitle: '接口详情',
    };
    return {
      ...TREE_CONFIG, // 树相关
      ...TABLE_CONFIG, // table相关
      ...DIALOG_CONFIG, // 主列表dialog相关
      // 初始化treeData为空数组，用于存储转换后的数据
      showPagination: true,
      total: 0, // 总记录数
      treeData: [],
      status: '', // 初始化接口状态为空
      pagination: {
        page: 1,
        pageSize: 20,
      },

      tableData: [], // 初始化列表为空数组

      value: '',
      activeName: 'first', // 测试抽屉，默认为first项
      input1: '', // 抽屉输入内容为空
      select: '1', // 抽屉下拉为空
      drawerData: [
        {
          key: 'key',
          value: 'value',
        },
      ], // 抽屉数据
    };
  },
  computed: {
    // 配置列表接口方法；只有配置了该计算属性才会执行table mixins中的getData方法
    dataMethod() {
      return API.treequeryTable;
    },
  },
  created() {
    // 调用新的方法来获取和转换数据
    this.fetchTreeData();
    this.getData();
  },

  methods: {
    // apiMode标签颜色
    determineTagType(apiMode) {
      return apiMode === 'GET' ? '' : 'warning';
    },
    // table列表接口调用-正确
    getData(queryParams = {}) {
      queryParams.catalogId = this.treeId;
      // console.log('111111111111111', queryParams);
      API.treequeryTable(queryParams, false)
        .then((res) => {
          console.log('----------------', res);
          // 假设 res.rows 是接口返回的数据列表
          if (Array.isArray(res.rows)) {
            this.tableData = res.rows.map((item, index) => ({
              ...item, // 保留原始数据
              // 可以在这里添加其他必要转换或计算属性
            }));
          } else {
            console.error('接口返回的数据格式不正确');
          }
          // console.log('daddajdja', this.tableData); // 请求到的n条列表数据
        })
        .catch((error) => {
          console.error('获取数据失败:', error);
        });
    },
    // table列表新增
    addData() {
      this.addTitle = '新增API接口';
      this.currentRow = null;
      // 新增，重置 form 数据，使其恢复到初始状态
      this.form = this.$options.data().form;
      this.addVisible = true;
    },
    // 新增这个方法用于响应DetailDialog组件触发的data-added事件，重新获取最新列表数据
    fetchUpdatedData() {
      const queryParams = {
        groupRelation: 'AND',
        groupTree: {},
        pageBean: {
          page: 1,
          pageSize: 10,
          showTotal: true,
        },
        params: {},
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: '',
            relation: 'AND',
            value: {},
          },
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'catalogId',
            relation: 'AND',
            value: this.treeId,
          },
        ],
        sorter: [
          {
            direction: 'ASC',
            property: '',
          },
        ],
      };
      this.getData(queryParams);
    },
    // table列表编辑
    editData(row) {
      this.detailTitle = `编辑 - ${row.apiName}`;
      this.currentRow = row;
      this.detailVisible = true;
    },
    // table列表删除
    delApi(row) {
      this.$confirm(`此操作将永久删除该接口项（${row.apiName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await API.delApiData(row.id);
          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);
        });
    },
    // dialog点击
    onCompanyConfirm(data) {
      const id = `${this.tableData.length + 1}`;
      if (data?.id) {
        console.log(data);
        const ind = this.tableData.findIndex((o) => o.id == data.id);
        ind >= 0 && this.tableData.splice(ind, 1, data);
      } else {
        this.tableData.push({ ...data, id });
      }
      console.log(this.tableData);
      this.addVisible = false;
    },
    // 查看日志按钮
    serviceshow(row) {
      this.dialogServiceTitle = `查看日志- ${row.apiName}`;
      this.currentRow = row;
      const rowId = row.id; // 获取当前行的id
      this.dialogService = true;
      // console.log('rowrow', row.id);
      this.$refs.ServiceDialog.initData({ id: rowId }); // 将id传递给ServiceDialog组件
    },
    // 接口文档查看
    detailsshow(row) {
      this.dialogDetailsTitle = `接口详情- ${row.apiName}`;
      this.currentRow = row;
      this.dialogDetails = true;
    },
    // 测试按钮
    showDrawer() {
      this.drawerVisible = true;
    },

    // 标签点击
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 改变status开关,控制上线或下架
    changestatus(row) {
      row.status = !row.status;
      // this.disabled = true;
    },
    // treeData(data) {
    //   apiList.treeAction(data, false).then(res => {
    //     console.log(res);
    //   });
    // },
    // 树接口调用
    fetchTreeData(data) {
      API.treeAction(data, false)
        .then((res) => {
          // res.value是包含节点数据的数组
          this.treeData = this.transformTreeData(res.value);
          // console.log('树', res); // 树目录
        })
        .catch((error) => {
          console.log('获取树形数据失败', error);
        });
    },
    // 树接口遍历，转换方法
    transformTreeData(data) {
      // 递归函数，用于遍历和转换数据
      return data.map((node) => {
        // 创建一个新对象，避免直接修改原始数据
        const newNode = { ...node };
        // 重命名'name'属性为'label'
        newNode.label = newNode.name;
        // delete newNode.name; // 如果不需要保留'name'属性，可以删除它
        // 如果节点有子节点，递归处理它们
        if (newNode.children && newNode.children.length > 0) {
          newNode.children = this.transformTreeData(newNode.children);
        }

        return newNode;
      });
    },
    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 },
        { label: '删除', type: 'delete', method: this.delNode },
      ];
    },
    onTreeNodeClick(node) {
      this.treeId = node.id;
      // 构建查询参数对象，按照你提供的格式示例
      const queryParams = {
        groupRelation: 'AND',
        groupTree: {},
        pageBean: {
          page: 1,
          pageSize: 10,
          showTotal: true,
        },
        params: {},
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: '',
            relation: 'AND',
            value: {},
          },
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'catalogId',
            relation: 'AND',
            value: this.treeId,
          },
        ],
        sorter: [
          {
            direction: 'ASC',
            property: '',
          },
        ],
      };
      if (node.id === this.curNode?.id) return;
      this.deptName = node.label;
      this.curNode = { ...node };
      this.form = this.$options.data().form;
      this.getData(queryParams);
    },
    // 目录新增
    async addNode(params, node) {
      const { code, name } = params;
      const { id } = node;
      const newNode = {
        code,
        name,
        parentId: id,
      };
      try {
        const { state, message } = await API.addAPITree(newNode);
        if (state) {
          this.reloadTree();
          // 手动再次获取树数据并更新相关绑定
          await this.fetchTreeData();
          //   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.editAPITree(newNode);
        if (state) {
          this.reloadTree();
          // 手动再次获取树数据并更新相关绑定
          await this.fetchTreeData();
          //   this.$message.success('编辑资源目录成功！');
        } else {
          this.$message.warning(message || '编辑接口目录失败！');
        }
      } catch (err) {
        this.$message.warning(err || '编辑接口目录失败！');
      }
    },
    // 目录删除
    async delNode(params, node) {
      try {
        const { state, message } = await API.removeAPITree(node.id);
        if (state) {
          this.reloadTree();
          // 手动再次获取树数据并更新相关绑定
          await this.fetchTreeData();
          //   this.$message.success('删除资源目录成功！');
        } else {
          this.$message.warning(message || '删除接口目录失败！');
        }
      } catch (err) {
        this.$message.warning(err || '删除资接口目录失败！');
      }
    },
  },
};
</script>
<style lang="scss" scoped>
html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.main-content {
  display: flex;
  flex-direction: column;
  height: 92vh;
}

.drawer-content {
  width: 100%;
  height: 100%;
  margin-left: 20px;
  //border: solid 1px #114d77;
  align-items: center;
}

.drawer-url {
  margin-top: 20px;
}

.drawer-select-input {
  margin-left: 4px;
}

.drawer-footer {
  margin-top: 40px;
}

.el-select {
  width: 130px;
}

.el-input {
  width: 500px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
