<!-- Created by SMG on 2022/8/18 8:57 -->
<template>
  <div class="datepreContainer">
    <div class="datasourceMain">
      <div class="main-top">
        <div class="top-left">服务管理</div>
        <div class="top-right">
          <el-button class="right_create_table" type="primary" @click="addDataservice('edit')">添加服务</el-button>
        </div>
      </div>
      <div class="main-top">
        <div class="top-search">
          <el-select
            v-model="serchForm.source_id"
            placeholder="请选择数据源"
            clearable
            filterable
            class="top-search-item"
            style="width: 180px">
            <el-option
              :label="item.ds_name"
              :value="item.ds_id"
              v-for="(item, index) in datasourceList"
              :key="index"></el-option>
          </el-select>
          <el-input
            v-model="serchForm.search"
            class="top-search-item"
            placeholder="请输入服务编码/负责人/服务描述"></el-input>
          <el-button class="right_create_table" type="primary" @click="search()">查询</el-button>
          <el-button class="right_create_table" type="danger" @click="resetSearch()">重置</el-button>
        </div>
      </div>
      <div class="preview-wrapper-datapre">
        <div class="link-section" id="link_page_template_table" data-track-block="link_page_template_table">
          <vxe-table
            class="mytable-scrollbar"
            ref="xTable"
            align="center"
            sync-resize
            strip
            border
            resizable
            show-summary
            highlight-current-row
            highlight-hover-row
            show-footer
            auto-resize
            size="small"
            :height="tableHeight"
            style="width: 100%"
            :loading="loading"
            :data="dataserviceList">
            <template>
              <vxe-table-column
                :field="item.key"
                :title="item.label"
                v-for="(item, index) in tableHeader"
                :width="'auto'"
                :key="index"
                show-overflow>
                <template v-if="item.key == 'ds_code'" v-slot="{ row }">
                  <div>
                    <a style="color: blue" @click="editEvent(row, 'detail')">{{ row.ds_code }}</a>
                  </div>
                </template>
              </vxe-table-column>
              <vxe-table-column title="操作" width="100">
                <template v-slot="{ row }">
                  <div v-if="row.can_edit" title="编辑" class="iconClass">
                    <i class="el-icon-edit-outline" @click="editEvent(row, 'update')"></i>
                  </div>
                  <div v-if="row.can_edit" title="导出" class="iconClass">
                    <i class="el-icon-sold-out" @click="editEvent(row, 'export')"></i>
                  </div>
                </template>
              </vxe-table-column>
            </template>
          </vxe-table>
          <vxe-pager
            border
            size="medium"
            :loading="loading"
            :current-page="tablePage.currentPage"
            :page-size="tablePage.pageSize"
            :total="tablePage.totalResult"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
            @page-change="handlePageChange"></vxe-pager>
        </div>

        <el-dialog
          custom-class="fieldSetDialog"
          :visible.sync="fieldSetDialog"
          :show-close="true"
          destroy-on-close
          :close-on-click-modal="false"
          title="服务配置"
          width="70%"
          top="8vh"
          min-width="700">
          <div class="tableDetailDialog">
            <div class="dataservicemain-add">
              <el-row>
                <el-col class="columnFlex" :span="8">
                  <span>
                    <font color="red">*</font>
                    数据源：
                  </span>
                  <el-select
                    v-model="fieldSetForm.source_id"
                    placeholder="请选择数据源"
                    clearable
                    :disabled="fieldSetForm.type == 'export'"
                    class="flex2">
                    <el-option
                      :label="item.ds_name"
                      :value="item.ds_id"
                      v-for="(item, index) in datasourceList"
                      :key="index"></el-option>
                  </el-select>
                </el-col>
                <el-col class="columnFlex" :span="8">
                  <span>
                    <font color="red">*</font>
                    服务编码：
                  </span>
                  <el-input :readonly="fieldSetForm.id" v-model="fieldSetForm.ds_code" class="flex2"></el-input>
                </el-col>
                <el-col class="columnFlex" :span="8">
                  <span>
                    <font color="red">*</font>
                    服务状态：
                  </span>
                  <el-select
                    v-model="fieldSetForm.ds_status"
                    placeholder="请选择服务状态"
                    clearable
                    :disabled="fieldSetForm.type == 'export'"
                    class="flex2">
                    <el-option
                      :label="item.dict_name"
                      :value="item.dict_value"
                      v-for="(item, index) in dsStatusList"
                      :key="index"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row>
                <el-col class="columnFlex" :span="8">
                  <span>缓存时间/秒：</span>
                  <el-input
                    type="number"
                    :readonly="fieldSetForm.type == 'export'"
                    v-model="fieldSetForm.ds_cache_timeout"
                    class="flex2"></el-input>
                </el-col>
                <el-col class="columnFlex" :span="8">
                  <span>
                    <font color="red">*</font>
                    查询超时/秒：
                  </span>
                  <el-input
                    type="number"
                    :readonly="fieldSetForm.type == 'export'"
                    v-model="fieldSetForm.ds_request_timeout"
                    class="flex2"></el-input>
                </el-col>
                <el-col class="columnFlex" :span="8">
                  <span>服务描述：</span>
                  <el-input
                    :readonly="fieldSetForm.type == 'export'"
                    v-model="fieldSetForm.ds_content"
                    class="flex2"></el-input>
                </el-col>
              </el-row>
              <el-row>
                <el-col class="columnFlex" :span="8">
                  <span>
                    <font color="red">*</font>
                    应用产品：
                  </span>
                  <el-select
                    v-model="fieldSetForm.app_code"
                    placeholder="请选择应用产品"
                    clearable
                    multiple
                    :disabled="fieldSetForm.type == 'export'"
                    class="flex2">
                    <el-option
                      :label="item.app_name"
                      :value="item.app_code"
                      v-for="(item, index) in productData"
                      :key="item.app_code"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row v-if="fieldSetForm.type != 'export'">
                <el-col class="columnFlex">
                  <span>查询优化参数：</span>
                  <el-input type="textarea" :rows="3" v-model="fieldSetForm.ds_query_params" class="flex1"></el-input>
                </el-col>
              </el-row>
              <el-row v-if="fieldSetForm.type != 'export'">
                <el-col class="columnFlex">
                  <span>
                    <font color="red">*</font>
                    接口模板：
                  </span>
                  <el-input type="textarea" :rows="11" v-model="fieldSetForm.ds_template" class="flex1"></el-input>
                </el-col>
              </el-row>
              <el-row v-if="fieldSetForm.type == 'export'">
                <el-col class="columnFlex">
                  <span>
                    <font color="red">*</font>
                    导出配置：
                  </span>
                  <el-input
                    type="textarea"
                    :rows="15"
                    v-model="fieldSetForm.export_config"
                    class="flex1"
                    placeholder='JSON格式如：
[{
  "field_name":"age",
  "field_desc":"年龄",
  "field_type":"bigint"  \\varchar/bigint/date（3选1）
}]'></el-input>
                </el-col>
              </el-row>
            </div>
            <div style="background-color: #fff; margin-top: 5px">
              <el-col class="footbtns">
                <el-button size="mini" @click="calcCancelFn">取 消</el-button>
                <el-button size="mini" v-if="fieldSetForm.type != 'detail'" type="primary" @click="saveDataservice(1)">
                  确 定
                </el-button>
              </el-col>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { handleEncryptParams } from '@/utils/aesCrypto'
import Cookies from 'js-cookie'
export default {
  name: 'datasourceMain',
  data() {
    return {
      panelShow: true,
      loading: false,
      dataserviceList: [], // 表格数据
      datasourceList: [],
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
      },
      fieldSetForm: {},
      serchForm: {},
      fieldSetDialog: false,
      tableHeader: [
        {
          key: 'ds_code',
          label: '服务编码',
        },
        {
          key: 'datasource_name',
          label: '数据源',
        },
        {
          key: 'ds_status_name',
          label: '服务状态',
        },
        {
          key: 'ds_request_timeout',
          label: '超时时间/秒',
        },
        {
          key: 'ds_content',
          label: '服务描述',
        },
        {
          key: 'owner_name',
          label: '负责人',
        },
        {
          key: 'create_time_format',
          label: '创建时间',
        },
        {
          key: 'update_time_format',
          label: '修改时间',
        },
      ], // 表头数据
      tableHeight: '', // 表格高度
      user_role: 'user',
      dsStatusList: [],
      productData: [],
    }
  },
  computed: {
    ...mapGetters(['sidebar']),
  },
  components: {},
  created() {
    this.btnShowPer()
  },
  activated() {
    this.setTableHeight()
    this.getSourceList()
    this.getDsStatusList()
    this.applicationList()
  },
  watch:{
    $route: {
      handler: function (newVal, oldVal) {
        if(newVal.query.sessionId){
          console.log('监听到的sessionId',newVal.query.sessionId);
          Cookies.set('sessionId',newVal.query.sessionId)
        }
      },
      deep: true,
      immediate: true,
    }
  },
  mounted() {},
  methods: {
    async applicationList() {
      const params = {
        apiCode: '/application/list',
        dispatcherSystem: 'system',
        param: {},
      }
      try {
        const res = await this.$store.dispatch('bi/commonAPI', params)
        if (res.code === 0) {
          this.productData = res.data
          this.productType = res.data?.[0]?.app_code
        }
      } finally {
      }
    },
    async getDsStatusList() {
      const params = {
        apiCode: '/enum/getDictByCode',
        dispatcherSystem: 'common',
        param: {
          enum_code: 'ds_status',
        },
      }
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.dsStatusList = res.data
        this.getDataServicePreview()
      } else {
        this.$message.error(res.msg)
      }
    },
    async getSourceList() {
      const params = {
        apiCode: '/datasource/getSource',
        dispatcherSystem: 'datapre',
        param: {},
      }
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.datasourceList = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    btnShowPer() {
      const modulesJson = JSON.parse(window.localStorage.getItem('modules'))

      if (modulesJson.user_role == 'super_admin' || modulesJson.user_role == 'platform_admin') {
        // this.showMenuBtn = true
        // this.showDatasetBtn = true
        this.user_role = 'admin'
      } else {
      }
    },
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getDataServicePreview()
    },
    stopDatasource(row) {
      this.updateStatus(row.ds_id, 0)
    },
    startDatasource(row) {
      this.updateStatus(row.ds_id, 1)
    },
    async updateStatus(id, status) {
      this.loading = true

      const params = {
        apiCode: '/datasource/updateStatus',
        dispatcherSystem: 'datapre',
        param: {
          id,
          status,
        },
      }
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.getDataServicePreview()
        this.loading = false
        this.$message.success('操作成功！')
      } else {
        this.$message.error(res.msg)
        this.loading = false
      }
    },
    editEvent(row, type) {
      this.fieldSetForm = {
        id: row.id,
        source_id: row.source_id,
        ds_status: row.ds_status + '',
        ds_code: row.ds_code,
        ds_content: row.ds_content,
        ds_cache_timeout: row.ds_cache_timeout,
        ds_request_timeout: row.ds_request_timeout,
        ds_template: row.ds_template,
        ds_query_params: row.ds_query_params,
        type,
        export_config: row.export_config,
        app_code: row.appcodeArray,
      }
      this.fieldSetDialog = true
    },
    /**
     * 数据集预览
     * @param {参数类型} 参数名 参数说明
     * @param {参数类型} 参数名 参数说明
     * @return {返回值类型} 返回值说明
     */
    async getDataServicePreview() {
      this.loading = true

      const params = {
        apiCode: '/manager/list',
        dispatcherSystem: 'dataservice',
        param: {
          currentPage: this.tablePage.currentPage,
          pageSize: this.tablePage.pageSize,
          search: this.serchForm.search,
          source_id: this.serchForm.source_id,
        },
      }
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.dataserviceList = res.data
        this.dataserviceList.forEach((item) => {
          this.dsStatusList.forEach((ds) => {
            if (item.ds_status == ds.dict_value) {
              item.ds_status_name = ds.dict_name
            }
          })
        })

        this.tablePage.totalResult = res.total
        this.loading = false
      } else {
        this.$message.error(res.msg)
        this.loading = false
      }
    },

    // 表格高度计算
    setTableHeight() {
      this.$nextTick(() => {
        this.tableHeight = this.calcHeight(['#link_page_template_table'], false) || '100%'
      })
    },
    // 计算高度
    calcHeight(area = ['#link_page_template_table'], otherHeight = 0) {
      const windowHeight = document.documentElement.clientHeight
      let areaHeight = area.reduce((total, current) => {
        total +=
          document.documentElement.querySelector(current) &&
          document.documentElement.querySelector(current).clientHeight
            ? document.documentElement.querySelector(current).clientHeight
            : 0
        return total
      }, 0)
      areaHeight += area.length * 6
      const height = windowHeight - otherHeight - 190
      return height
    },
    resetSearch() {
      this.serchForm = {}
    },
    search() {
      this.tablePage.currentPage = 1
      this.getDataServicePreview()
    },
    addDataservice() {
      this.fieldSetForm = {
        ds_status: '1',
        ds_request_timeout: 60,
        type: 'add',
      }
      this.fieldSetDialog = true
    },
    calcCancelFn() {
      // this.fieldSetForm = {
      // }
      this.fieldSetDialog = false
      this.loading = false
    },
    async saveDataservice() {
      this.loading = true
      this.is_validata = false
      this.validata()
      if (!this.is_validata) {
        return
      }
      let apiCode = '/manager/save'
      if (this.fieldSetForm.type == 'export') {
        apiCode = '/manager/saveExport'
      }
      const params = {
        apiCode,
        dispatcherSystem: 'dataservice',
        param: {
          id: this.fieldSetForm.id,
          source_id: this.fieldSetForm.source_id,
          ds_status: this.fieldSetForm.ds_status,
          ds_code: this.fieldSetForm.ds_code,
          ds_content: this.fieldSetForm.ds_content,
          ds_cache_timeout: this.fieldSetForm.ds_cache_timeout,
          ds_request_timeout: this.fieldSetForm.ds_request_timeout,
          ds_template: this.fieldSetForm.ds_template,
          ds_query_params: this.fieldSetForm.ds_query_params,
          export_config: this.fieldSetForm.export_config,
          target_app_code: this.fieldSetForm.app_code,
        },
      }
      params.param = handleEncryptParams(params.param)
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.addAppView(res.data.api_id)
        this.getDataServicePreview()
        this.loading = false
        this.$message.success('操作成功！')
        this.fieldSetDialog = false
      } else {
        this.loading = false
        this.$message.error(res.msg)
      }
    },
    async addAppView(api_id) {
      const params = {
        apiCode: '/auth/addAppView',
        dispatcherSystem: 'common',
        param: {
          target_app_code: this.fieldSetForm.app_code,
          obj_id: api_id,
          obj_type: 'dataservice',
        },
      }
      const res = await this.$store.dispatch('bi/commonAPI', params)
      if (res.code === 0) {
        this.fieldSetDialog = false
      } else {
        this.loading = false
        this.$message.error(res.msg)
      }
    },
    validata() {
      if (!this.fieldSetForm.source_id) {
        this.$message.error('请选择数据源')
        return
      }
      if (!this.fieldSetForm.ds_code) {
        this.$message.error('请输入服务编码')
        return
      }
      if (!this.fieldSetForm.ds_status) {
        this.$message.error('请选择服务状态')
        return
      }
      if (!this.fieldSetForm.ds_request_timeout) {
        this.$message.error('请输入查询超时')
        return
      }
      if (!this.fieldSetForm.ds_template) {
        this.$message.error('请输入接口模板')
        return
      }
      if (this.fieldSetForm.type == 'export' && !this.fieldSetForm.export_config) {
        this.$message.error('请输入导出配置')
        return
      }
      if (this.fieldSetForm.app_code.length == 0) {
        this.$message.error('请选择应用产品')
        return
      }
      this.is_validata = true
    },
  },
}
</script>

<style lang="scss" scoped>
.datepreContainer {
  display: flex;
}
.tableDetailDialog {
  min-height: 330px;
  min-width: 700px;
  height: calc(100vh - 250px);
}
.dataservicemain-add {
  min-height: 300px;
  height: calc(100vh - 280px);
  padding-top: 10px;
  padding-right: 10px;
  //border: 1px solid red;
  background-color: #fff;
}

.sidebar {
  height: calc(100vh - 50px);
  overflow: hidden;
  .left_select {
    width: 220px;
    margin-top: 2px;
  }
  .left__operate {
    position: relative;
    width: 220px;
    height: 100%;
    background: #fff;
    padding-left: 6px;
    .create {
      display: flex;
      height: 40px;
      align-items: center;
      ::v-deep.el-button--text {
        font-size: 12px;
        margin-left: 0;
        flex: 1;
        padding: 5px 0;
        .el-icon-folder-add {
          font-size: 14px;
        }
      }
      ::v-deep .folder.el-button--text {
        flex: 1;
        color: #757575;
        display: flex;
        align-items: center;
        font-size: 12px;
        padding: 5px 0;
        .el-icon-folder-add {
          font-size: 14px;
        }
      }
    }
    .my__report {
      border-top: 1px solid #e7e7e7;
      padding-top: 5px;
      height: 92%;
      overflow: hidden scroll;
      .title {
        font-size: 14px;
        color: #101010;
        margin: 0;
        margin-left: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        i {
          font-size: 20px;
          margin-right: 5px;
          transition: transform 0.3s ease-in-out;
        }
        i.up {
          transform: rotate(-180deg);
        }
      }
      .report__list {
        .folder {
          .folder__name {
            font-size: 14px;
            margin-left: 2px;
            display: flex;
            margin-top: 5px;
            align-items: center;
            color: #000;
            width: 100%;
            position: relative;
            cursor: pointer;
            i {
              font-size: 14px;
              margin-right: 6px;
            }
            span {
              opacity: 0.6;
            }
          }
          .el-icon-arrow-down {
            font-size: 18px;
            margin-left: 5px;
            transition: transform 0.2s ease-in-out;
          }
          i.up {
            transform: rotate(-180deg);
          }
          .folder__input {
            width: 150px;
          }
          .report {
            margin-left: 14px;
            margin-top: 10px;
            .report__name {
              font-size: 14px;
              margin-left: 8px;
              display: flex;
              align-items: center;
              color: #000;
              width: 100%;
              position: relative;
              cursor: pointer;
              i {
                font-size: 20px;
                margin-right: 6px;
              }
              span {
                opacity: 0.6;
              }

              .reportSQL,
              .reportDB {
                font-size: 14px;
                padding-right: 5px;
              }
              .reportSQL {
                color: #ffc800;
              }
              .reportDB {
                padding-right: 13px;
                color: #246dff;
              }
            }
            .report__input {
              width: 120px;
            }
          }
          .shortcut_btn {
            position: absolute;
            right: 20px;
            top: 4px;
            border-right: 1px dashed #000;
            width: 14px;
            height: 14px;
          }
        }
      }
    }
  }
  .width100 {
    width: 100%;
    padding-left: 15px;
    padding-top: 5px;
  }
}
.top-search {
  float: left;
  .top-search-item {
    float: left;
    width: 300px;
    margin-right: 10px;
  }
}
.datasourceMain {
  width: calc(100vw - 330px);
  flex: 1;
  padding: 0px 0px;
  height: 100%;
  border-left: 1px solid #ddd;
  overflow: auto;
  .main-top {
    padding-left: 10px;
    display: flex;
    font-size: 14px;
    align-items: center;
    justify-content: space-between;
    background-color: white;
    height: 40px;
    border-bottom: 1px solid #ddd;
    .top-left {
      font-weight: bold;
    }
    .top-right {
      .right_create_table {
        margin: 0 10px;
      }
    }
  }
  .preview-wrapper-datapre {
    /*width: 100%;*/
    height: 100%;
    background-color: rgba(255, 255, 255, 0.747);

    ::v-deep .el-tabs__header {
      margin: 0 0 5px;
    }
    ::v-deep .el-tabs__nav-scroll {
      padding-left: 10px;
    }
    .iconClass {
      margin-left: 18px;
      font-size: 16px;
      cursor: pointer;
      float: left;
    }

    .mytable-scrollbar {
      /*max-width: calc(100vw - 310px);*/
      /*overflow: auto;*/
    }
  }
  ::v-deep .vxe-table--render-default.size--small {
    font-size: 12px;
  }
  ::v-deep .el-dialog__body {
    padding: 0px 10px 10px 10px;
  }
  .fieldSetDialog {
    .columnFlex {
      display: flex;
      padding-bottom: 15px;
      span {
        display: inline-block;
        width: 121px;
        text-align: right;
      }

      .flex1 {
        width: 100%;
      }
      .flex2 {
        width: 80%;
      }
    }

    .footbtns {
      text-align: right;
    }
  }
}
</style>
