<template>
  <div class="dataindex">
    <el-form label-width="80px"
             label-position="left">
      <div class="avue-collapse__top">
        <el-button type="primary"
                   @click="handleAdd()">新增数据源</el-button>
        <el-button type="primary"
                   @click="handleSetting">更多设置</el-button>
      </div>
      <el-collapse class="avue-collapse">
        <el-collapse-item :name="index"
                          v-for="(item,index) in contain.activeObj.dataList"
                          :key="index">
          <template #title>
            <div class="avue-collapse__header">
              <div class="avue-flex"
                   @click="stopCollapse">
                <el-tooltip effect="dark"
                            content="激活"
                            placement="top">
                  <el-checkbox v-model="item.switch"
                               size="small"></el-checkbox>
                </el-tooltip>
                <div class="index">{{ index+1 }}.</div>
                <avue-input v-model="item.name"
                            :disabled="!item.switch"></avue-input>
              </div>
              <div class="avue-collapse__menu">
                <el-icon @click.stop="handleEdit(item,index)">
                  <el-icon-edit></el-icon-edit>
                </el-icon>
                <el-icon @click.stop="handleDel(item,index)">
                  <el-icon-delete></el-icon-delete>
                </el-icon>
              </div>
            </div>
          </template>
          <el-form-item label="数据类型">
            <avue-select v-model="item.dataType"
                         placeholder="请选择数据类型"
                         :dic="dicOption.dataType"></avue-select>
          </el-form-item>
          <template v-if="isStatic(item)">
            <el-form-item label="数据值">
              <el-button type="primary"
                         icon="el-icon-edit"
                         @click="contain.openCode({type:'data',title:'数据值',parent:'dataList',index,isObject:true})">编辑</el-button>
            </el-form-item>
          </template>
          <template v-else-if="isSql(item)">
            <el-form-item label="数据源选择">
              <avue-select :dic="DIC.sql"
                           v-model="db[item.id]"></avue-select>
            </el-form-item>
            <el-form-item label="SQL语句"
                          label-position="top">
              <monaco-editor v-model="sql[item.id]"
                             language="sql"
                             :showToolbar="false"
                             height="100"></monaco-editor>
              <el-button type="primary"
                         class="el-button--bottom"
                         icon="el-icon-edit"
                         @click="contain.openCode({type:'sql',title:'SQL语句',parent:'dataList',index,id:item.id,sql:sql})">编辑</el-button>
            </el-form-item>
          </template>
          <template v-else-if="isApi(item) || isNode(item)">
            <el-form-item label="请求方式"
                          v-if="isApi(item)">
              <div class="avue-flex">
                <avue-select v-model="item.dataMethod"
                             placeholder="请选择请求方式"
                             :dic="dicOption.dataMethod"></avue-select>
                &nbsp;
                <el-tooltip effect="dark"
                            content="跨域"
                            v-if="isApi(item)"
                            placement="top">
                  <el-checkbox v-model="item.proxy"
                               @click="handleRes"
                               size="small">跨域</el-checkbox>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="地址">
              <avue-input v-model="item.url"
                          placeholder="请输入地址"></avue-input>
            </el-form-item>
          </template>
          <template v-else-if="isWs(item)">
            <el-form-item label="WS地址">
              <el-input v-model="item.wsUrl">
              </el-input>
            </el-form-item>
          </template>
          <template v-else-if="isRecord(item)">
            <el-form-item label="分类">
              <avue-select :dic="DIC.recordType"
                           placeholder="请选择分类"
                           :empty-values="[undefined]"
                           @change="(params)=>{handleRecordTypeChange(params,item)}"
                           :props="{label:'categoryKey',value:'categoryValue'}"
                           v-model="item.recordType"></avue-select>
            </el-form-item>
            <el-form-item label="数据集">
              <avue-select :dic="DIC.record[item.id]"
                           filterable
                           placeholder="请选择数据集"
                           v-model="item.record"></avue-select>
            </el-form-item>
          </template>
          <template v-else-if="isPublic(item)">
            <el-form-item label="数据集选择">
              <avue-select :dic="DIC.public"
                           filterable
                           v-model="item.public"></avue-select>
            </el-form-item>
          </template>
          <template v-else-if="isMqtt(item)">
            <el-form-item label="MQTT地址">
              <el-input v-model="item.mqttUrl">
              </el-input>
            </el-form-item>
            <el-form-item label="订阅主题">
              <avue-input v-model="item.topicName"
                          placeholder="多个主题用,间隔"></avue-input>
            </el-form-item>
            <el-form-item label="用户名">
              <avue-input v-model="item.username"
                          placeholder="用户名"></avue-input>
            </el-form-item>
            <el-form-item label="密码">
              <avue-input v-model="item.password"
                          placeholder="密码"></avue-input>
            </el-form-item>
            <el-form-item label="MQTT配置">
              <monaco-editor v-model="item.mqttConfig"
                             :showToolbar="false"
                             height="150"></monaco-editor>
            </el-form-item>
          </template>
          <template v-else-if="isFill(item)">
            <el-form-item label="分类">
              <avue-select :dic="DIC.fillType"
                           :empty-values="[undefined]"
                           placeholder="请选择分类"
                           @change="(params)=>{handleFillTypeChange(params,item)}"
                           :props="{label:'categoryKey',value:'categoryValue'}"
                           v-model="item.fillType"></avue-select>
            </el-form-item>
            <el-form-item label="数据填报">
              <avue-select :dic="DIC.fill[item.id]"
                           filterable
                           placeholder="请选择数据填报"
                           v-model="item.fill"></avue-select>
            </el-form-item>
          </template>
        </el-collapse-item>
      </el-collapse>

      <el-form-item label="刷新时间">
        <el-input v-model="contain.activeObj.time"
                  placeholder="0">
          <template #append>
            <span>毫秒</span>
          </template>

        </el-input>
      </el-form-item>

      <el-form-item label="过滤器">
        <div class="avue-flex">
          <avue-select v-model="contain.activeObj.dataFormatterId"
                       :dic="DIC.filter"
                       :placeholder="contain.activeObj.dataFormatter?'自定义过滤器':'暂无过滤器'"
                       :props="{label:'name',value:'id'}"></avue-select>

          <el-button v-if="!contain.activeObj.dataFormatterId"
                     type="primary"
                     icon="el-icon-edit"
                     @click="contain.openCode({type:'dataFormatter',title:'编辑过滤器',dataView:dataOldRes})">编辑</el-button>
        </div>
        <avue-highlight v-if="contain.activeObj.dataFormatter"
                        :model-value="contain.activeObj.dataFormatterId?contain.config.filters[contain.activeObj.dataFormatterId].dataFormatter:contain.activeObj.dataFormatter"
                        height="100"></avue-highlight>
      </el-form-item>
      <el-form-item label="返回数据"
                    label-width="100">
        <div class="avue-flex"
             style="width:100%;justify-content: flex-end;">
          <el-button type="primary"
                     @click="handleRes">请求数据</el-button>
        </div>
      </el-form-item>
      <el-tabs class="menu__tabs"
               style="padding:0 10px;"
               v-model="resTabs">
        <el-tab-pane label="过滤器后数据"
                     :name="0">
          <json-viewer v-loading="dataLoading"
                       v-bind="$loadingParams"
                       :value="dataRes"
                       copyable
                       theme="avue-json-theme"
                       boxed></json-viewer>
        </el-tab-pane>
        <el-tab-pane label="原始数据"
                     name="1">
          <json-viewer v-loading="dataLoading"
                       v-bind="$loadingParams"
                       :value="dataOldRes"
                       copyable
                       theme="avue-json-theme"
                       boxed></json-viewer>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <database ref="database"></database>
  </div>
</template>

<script>
import { getList as getCategoryList } from '@/api/category'
import MonacoEditor from '@/page/components/monaco-editor'
import crypto from '@/utils/crypto'
import database from '@/page/setup/database.vue'
import { getList as getDbList } from "@/api/db";
import { getList as getRecordList } from "@/api/record";
import { getList as getFillList } from "@/api/fill";
import { dicOption } from '@/option/config'
import { uuid } from '@/utils/utils'
import { format as sqlFormat } from 'sql-formatter'
export default {
  inject: ["contain"],
  provide () {
    return {
      dataParent: this
    };
  },
  components: {
    database,
    MonacoEditor
  },
  data () {
    return {
      resTabs: 0,
      dataLoading: false,
      dataRes: '',
      dataOldRes: '',
      sql: {},
      db: {},
      DIC: {
        filter: [],
        sql: [],
        record: {},
        recordType: [],
        fill: {},
        fillType: [],
        public: [],
        project: [],
        devices: []
      },
      dicOption,
    }
  },
  created () {
    this.initDataList();
    this.handleRes(false);
  },
  methods: {
    stopCollapse (e) {
      return e.stopPropagation()
    },
    handleEdit (item, index) {
      this.handleSetting(index)
    },
    handleAdd () {
      if (!Array.isArray(this.contain.activeObj.dataList)) this.contain.activeObj.dataList = []
      this.contain.activeObj.dataList.push({
        name: '数据源',
        id: uuid(),
        switch: true,
        dataType: 0
      })
    },
    handleDel (item, index) {
      this.$confirm(`是否删除【${item.name}】数据源?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.contain.activeObj.dataList.splice(index, 1)
        this.handleRes()
      }).catch(() => {

      });
    },
    isStatic (item) {
      return item.dataType == 0
    },
    isApi (item) {
      return item.dataType == 1
    },
    isSql (item) {
      return item.dataType == 2
    },
    isWs (item) {
      return item.dataType === 3
    },
    isRecord (item) {
      return item.dataType == 4
    },
    isPublic (item) {
      return item.dataType == 5
    },
    isMqtt (item) {
      return item.dataType == 6
    },
    isNode (item) {
      return item.dataType == 7
    },
    isFill (item) {
      return item.dataType == 8
    },
    handleFillTypeChange (params, item) {
      getFillList({
        type: params.value,
        current: 1,
        size: 100,
      }).then(res => {
        const data = res.data.data;
        this.DIC.fill[item.id] = data.records.map(ele => {
          return {
            label: ele.name,
            value: ele.id
          }
        })
      });
    },
    handleRecordTypeChange (params, item) {
      getRecordList({
        dataModule: params.value,
        current: 1,
        size: 100,
      }).then(res => {
        const data = res.data.data;
        this.DIC.record[item.id] = data.records.map(ele => {
          return {
            label: ele.name,
            value: ele.id
          }
        })
      });
    },
    handleRes (tip = true) {
      this.dataRes = ''
      this.dataOldRes = ''
      this.contain.activeObj.dataList.forEach((item, index) => {
        if (!this.isSql(item)) return
        try {
          this.sql[item.id] = sqlFormat(this.sql[item.id], {
            language: 'spark',
            tabWidth: 2,
            keywordCase: 'upper',
            linesBetweenQueries: 2,
          });
        }catch{
          
        }
        item.sql = JSON.stringify({
          id: this.db[item.id],
          sql: this.sql[item.id]
        });
        // item.sql = crypto.encrypt(JSON.stringify({
        //   id: this.db[item.id],
        //   sql: this.sql[item.id]
        // }))
      })
      this.dataLoading = true
      this.contain.handleRefresh().then(({ news, old }) => {
        this.dataLoading = false
        this.dataRes = news
        this.dataOldRes = old
        if (tip) this.$message.success('请求数据成功')
      }).catch(() => {
        this.dataLoading = false
      }).finally(() => {
        this.dataLoading = false
      })
    },
    handleSetting (index) {
      this.resTabs = 0
      this.dataRes = '';
      this.dataOldRes = ''
      this.handleRes(false)
      this.$refs.database.activeName = index;
      this.$refs.database.box = true;
    },
    initDataList () {
      (this.contain.activeObj.dataList || []).forEach((item, index) => {
        if (item.sql && this.isSql(item)) {
          let mode = JSON.parse(item.sql);
          this.db[item.id] = mode.id;
          this.sql[item.id] = mode.sql;
        }
      })
      this.DIC.public = this.contain.list.filter(ele => {
        return (ele.component || {}).prop == 'data'
      }).map(ele => {
        return {
          label: ele.name,
          value: ele.index
        }
      })
      this.DIC.filter = Object.keys(this.contain.config.filters).map(key => this.contain.config.filters[key])
      getDbList({
        current: 1,
        size: 100,
      }).then(res => {
        const data = res.data.data;
        this.DIC.sql = data.records.map(ele => {
          return {
            label: ele.name,
            value: ele.id
          }
        })
      });
      getCategoryList({
        categoryModule: 'record',
        current: 1,
        size: 99,
      }).then(res => {
        this.loading = false
        const data = res.data.data;
        this.DIC.recordType = [{ categoryKey: '全部', categoryValue: '' }].concat(data);
      })
      getCategoryList({
        categoryModule: 'fill',
        current: 1,
        size: 99,
      }).then(res => {
        this.loading = false
        const data = res.data.data;
        this.DIC.fillType = [{ categoryKey: '全部', categoryValue: '' }].concat(data);
      })
    },
  }
}
</script>
