<template>
  <div>
    <el-card style="margin: 8px">
      <el-form :inline="true" :model="selectForm" class="demo-form-inline" label-width="120px">
        <el-form-item label="图表名称">
          <el-input v-model="selectForm.dataSourceName" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 8px">
      <el-button plain type="primary" icon="Plus" @click="constructionData">新增</el-button>
    </el-card>
    <el-card style="margin: 8px">
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="dataSourceName" label="数据源名称" align="center" />
        <el-table-column prop="requestMethod" label="请求方式" align="center" />
        <el-table-column prop="requestUrl" label="请求地址" align="center" />
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button text type="primary" size="small" @click="editDataSource(scope.row)">修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              text
              @click="delDataSource(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        v-model:current-page="selectForm.pageNum"
        v-model:page-size="selectForm.pageSize"
        :page-sizes="[10,20,50,100]"
        layout="total, sizes, prev, pager, next, jumper"
        v-if="total>0"
        :total="total"
        @size-change="pageChange"
        @current-change="pageChange"
      />
    </el-card>

    <el-dialog v-model="constructionDataFormVisible" draggable width="800">
      <template #header>
        <div style="width: 100%">
          <span>{{ constructionDataForm.dataSourceId ? '修改' : '构造' }}数据源</span>
          <div style="text-align:right;display: inline-block;width: calc(100% - 100px)">
            <span>简易模式</span>
            <el-switch v-model="isEasy" />
          </div>
        </div>
      </template>
      <el-form :model="constructionDataForm">
        <el-form-item label="数据名称" prop="dataSourceName">
          <el-input v-model="constructionDataForm.dataSourceName" />
        </el-form-item>
        <el-form-item label="请求地址" prop="requestUrl">
          <el-input v-model="constructionDataForm.requestUrl">
            <template #prepend>
              <el-select v-model="constructionDataForm.requestMethod" style="width: 100px">
                <el-option label="get" value="get" />
                <el-option label="post" value="post" />
                <el-option label="socket" value="socket" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="请求数据" v-if="isEasy">
          <el-table :data="paramsTableData" style="width: 100%">
            <el-table-column label="字段名称" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.name" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.remark" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="测试数据" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.test" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120">
              <template #default="scope">
                <el-button link size="small" type="primary"
                           @click="paramsTableData.splice(scope.$index, 1)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="width: 100%" @click="paramsTableData.push({})">
            添加字段
          </el-button>
        </el-form-item>
        <el-form-item label="输出数据">
          <el-table :data="constructionDataForm.designDataFieldList" style="width: 100%">
            <el-table-column label="字段名称" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.name" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column v-if="!isEasy" label="字段层级" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.tier" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="120">
              <template #default="scope">
                <el-input v-model="scope.row.remark" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120">
              <template #default="scope">
                <el-button link size="small" type="primary"
                           @click="constructionDataForm.designDataFieldList.splice(scope.$index, 1)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="width: 100%" @click="constructionDataForm.designDataFieldList.push({})">
            添加字段
          </el-button>
          <el-button v-if="isEasy" style="width: 100%;margin: 12px 0 0 0"
                     @click="findTier">
            查找
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="constructionDataFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="createData ">
            {{ constructionDataForm.dataSourceId ? '确定' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axios from 'axios';
import request from '@/utils/request';
import { options } from './tool.js';
import { addDataSourceApi, delDataSourceApi, editDataSourceApi, getDataSourceList } from './api/boardSource';
import { ElMessage, ElMessageBox } from 'element-plus';

const comparisonTable = {
  starttime: '开始时间',
  time: '时间',
  value: '值'
};

const isEasy = ref(false);
const loading = ref(false);
const paramsTableData = ref([]);
const selectForm = ref({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0);
const tableData = ref([{}]);
const constructionDataForm = ref({ designDataFieldList: [] });
const constructionDataFormVisible = ref(false);
const getList = async () => {
  loading.value = true;
  getDataSourceList(selectForm.value)
    .then((res) => {
      console.log(res);
      tableData.value = res.rows;
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
const queryList = async () => {
  selectForm.value.pageNum = 1;
  await getList();
};
const pageChange = () => {
  getList();
};
const constructionData = () => {
  paramsTableData.value = [];
  constructionDataForm.value = { designDataFieldList: [] };
  constructionDataFormVisible.value = true;
};
const editData = () => {
  paramsTableData.value = [];
  constructionDataForm.value = { designDataFieldList: [] };
  constructionDataFormVisible.value = true;
};
const delData = () => {
  paramsTableData.value = [];
  constructionDataForm.value = { designDataFieldList: [] };
  constructionDataFormVisible.value = true;
};
const editDataSource = (e) => {
  constructionDataFormVisible.value = true;
  constructionDataForm.value = e;
};
const delDataSource = (e) => {
  ElMessageBox.confirm(
    '要删除这条数据源吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      delDataSourceApi(e.dataSourceId).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功'
        });
        getList();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      });
    });
};
const createData = () => {
  if (!constructionDataForm.value.designDataFieldList) {
    constructionDataForm.value.designDataFieldList = [];
  }
  if (constructionDataForm.value.dataSourceId) {
    editDataSourceApi(constructionDataForm.value).then(() => {
      constructionDataFormVisible.value = false;
      ElMessage({
        type: 'success',
        message: '修改成功'
      });
      getList();
    });
  } else {
    addDataSourceApi(constructionDataForm.value).then(() => {
      constructionDataFormVisible.value = false;
      ElMessage({
        type: 'success',
        message: '创建成功'
      });
      getList();
    });
  }
  // let nowData = JSON.parse(localStorage.getItem('DATANODE') || '[]');
  // nowData.push(constructionDataForm.value);
  // localStorage.setItem('DATANODE', JSON.stringify(nowData));
};
const findTier = () => {
  constructionDataForm.value.designDataFieldList = [];
  let params = {};
  (paramsTableData.value || []).forEach((item) => {
    params[item.name] = item.test;
  });

  (options.isD ? request : axios.request)({
    method: constructionDataForm.value.requestMethod,
    url: constructionDataForm.value.requestUrl,
    params: constructionDataForm.value.requestMethod === 'get' ? params : '',
    data: constructionDataForm.value.requestMethod === 'post' ? params : ''
  }).then(res => {
    let data = (options.isD ? res : res.data);
    console.log(data);
    if (data?.data) {
      Object.keys(data.data?.[0]).forEach(key => {
        constructionDataForm.value.designDataFieldList.push({
          name: key,
          remark: comparisonTable[key],
          tier: `data,map%${key}`
        });
      });
    } else if (data?.rows) {
      console.log(data?.rows);
      Object.keys(data.rows?.[0]).forEach(key => {
        constructionDataForm.value.designDataFieldList.push({
          name: key,
          remark: comparisonTable[key],
          tier: `rows,map%${key}`
        });
      });
    } else {
      let exclude = ['code'];
      Object.keys(data).forEach(key => {
        if (!exclude.includes(key.toLowerCase())) {
          if (typeof data[key] === 'string' || typeof data[key] === 'string') {
            constructionDataForm.value.designDataFieldList.push({
              name: key,
              remark: comparisonTable[key],
              tier: `${key}`
            });
          }
        }
      });
    }
  });

};
onMounted(async () => {
  await queryList();
});
</script>
<style lang="less" scoped>
.pagination {
  float: right;
  margin: 12px 0;
}
</style>
