<template>
  <el-form ref="queryForm" :model="queryParams" :rules="rules" label-width="100px">
    <el-row :gutter="20">
      <el-col :span="18">
        <div class="code-editor">
          <sql-code-edit v-model="queryParams.uqSql"  :editor-placeholder="'请输入sql语句进行查询'"
                         :editor-height="300" :tab-size="2" @change="changeSqlCode"/>
        </div>
      </el-col>
      <el-col :span="6">
        <el-form-item label-width="55px" label="名称" prop="uqName">
          <el-input v-model="queryParams.uqName" placeholder="请输入名称" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label-width="55px" label="描述" prop="uqDescribe">
          <el-input v-model="queryParams.uqDescribe" placeholder="请输入描述" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <!--        <el-form-item v-for="column in uniCons" :key="column.ucId"-->
        <!--                      :label="column.ucName">-->
        <!--          <el-input :placeholder="column.ucDescribe" :type="column.ucType" v-model="column.query" clearable-->
        <!--                    @input="changeInput($event)"></el-input>-->
        <!--        </el-form-item>-->
        <el-button type="text" @click="getSqlQueryInfo">搜索</el-button>
        <el-button type="text" @click="handleReset">重置</el-button>
        <el-button type="text" @click="handleAdd">新增</el-button>
        <el-button type="text" @click="previewSqlHandle">预览</el-button>
        <el-button type="text" @click="handleTopLine">上线</el-button>
      </el-col>
    </el-row>
  </el-form>
  <div class="table">
    <!--        <el-table :data="list" v-loading="loading">-->
    <!--          <el-table-column v-for="column in uniColumns" :key="column.prop" :prop="column.prop"-->
    <!--                           :label="column.label" align="center"/>-->
    <!--        </el-table>-->
    <el-table :data="columns" row-key="columnId" :max-height="tableHeight"
              :header-cell-style="{'background':'#f5f7fa'}">
      <el-table-column label="序号" type="index" min-width="5%"/>
      <el-table-column label="查询名称" min-width="10%">
        <template #default="scope">
          <el-input v-model="scope.row.ucName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="条件描述" min-width="10%">
        <template #default="scope">
          <el-input v-model="scope.row.ucDescribe"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="key" min-width="10%">
        <template #default="scope">
          <el-input v-model="scope.row.ucKey"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="条件" min-width="10%">
        <template #default="scope">
          <el-select v-model="scope.row.ucCon" @change="ucTypeChang(scope.$index,scope.row)">
            <el-option label="=" value="EQ"/>
            <el-option label="!=" value="NE"/>
            <el-option label=">" value="GT"/>
            <el-option label=">=" value="GTE"/>
            <el-option label="<" value="LT"/>
            <el-option label="<=" value="LTE"/>
            <el-option label="LIKE" value="LIKE"/>
            <el-option label="BETWEEN" value="BETWEEN"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="显示类型" min-width="12%">
        <template #default="scope">
          <el-select v-model="scope.row.ucType" @change="ucTypeChang(scope.$index,scope.row)">
            <el-option label="文本框" value="input"/>
            <el-option label="日期控件" value="datetime"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="模拟数据" min-width="10%">
        <template #default="scope">
          <el-input v-if="scope.row.type == 1" placeholder="请输入模拟数据" v-model="scope.row.ucMock"></el-input>
          <div v-else-if="scope.row.type == 2">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-input placeholder="开始值" v-model="scope.row.ucMock.begin"></el-input>
              </el-col>
              <el-col :span="12">
                <el-input placeholder="结束值" v-model="scope.row.ucMock.end"></el-input>
              </el-col>
            </el-row>
          </div>
          <el-date-picker
              v-else-if="scope.row.type ==3"
              v-model="scope.row.ucMock"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间"
          >
          </el-date-picker>
          <el-date-picker v-else-if="scope.row.type ==4"
                          v-model="scope.row.ucMock"
                          size="small"
                          style="width: 240px"
                          value-format="yyyy-MM-dd"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="10%">
        <template #default="scope">
          <el-button type="text" size="mini" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
          <el-button type="text" @click="submitForm">提交</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="isTopLineVisited" title="上线" width="700px">
    <el-form :model="form" :rules="formRules" class="query-form" ref="formInstance">
      <el-form-item label="上级菜单">
        <el-tree-select v-model="form.parentId" :data="menuOpt" style="width: 100%;"
                        :filter-node-method="filterNodeMethod" filterable :check-strictly="true"/>
      </el-form-item>
    </el-form>
    <template #footer>
        <span>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formInstance)">
            确定
          </el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import SqlCodeEdit from "@/components/codeEdit/SqlCodeEdit.vue";
import {useRouter} from "vue-router";
import {getSqlInfo, previewSql, saveSqlQueryParams, sqlToLine} from "@/api/custom-query/sql-search";
import {getMenuOpt} from '@/api/system/menuman.js'
import {ElMessage} from "element-plus";

const queryForm = ref()
const menuOpt = ref([])
const isTopLineVisited = ref(false)
const form = ref({
  parentId: ''
})
const formInstance = ref()
const formRules = ref({
  parentId: [{required: true, message: '请选择上级菜单', trigger: 'blur'}]
})
const router = useRouter();
const queryId = reactive(router.currentRoute.value.params.queryId)
const queryParams = reactive({
  uqSql: '',
  uqName: null,
  uqDescribe: null,
  // columnList: []
})
const loading = ref(false)
const rules = ref({
  uqName: [{required: true, message: '请输入名称', trigger: 'blur'}],
  uqDescribe: [{required: true, message: '请输入描述', trigger: 'blur'}]
})
const tableHeight = ref(document.documentElement.scrollHeight - 245 + 'px')
const list = ref([])
const columns = ref([])
const uniCons = ref([])

const getSqlQueryInfo = () => {
  getSqlInfo(queryId).then(res => {
    if (res.code === 1000) {
      columns.value = res.data.uniCons
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//重置搜索
const handleReset = () => {
  queryParams.uqSql = ''
  queryForm.value.resetFields()
}
const handleAdd = () => {
  let row = {
    id: null,
    uqId: queryId,
    ucName: '',
    ucCon: '',
    ucDescribe: '',
    ucKey: '',
    ucMock: '',
    ucType: '',
    type: 1
  }
  columns.value.push(row)
}
const submitForm = () => {
  let data = {
    queryId: queryId,
    uniSql: queryParams.uqSql,
    uniCons: columns.value,
    uniColumns: []
  }
  saveSqlQueryParams(data).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      getSqlQueryInfo()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//实时获取sql语句
const changeSqlCode = (val) => {
  queryParams.uqSql = val
}

const previewSqlHandle = () => {
  let data = {
    queryId: queryId,
    uniSql: queryParams.uqSql,
    uniCons: [],
    uniColumns: []
  }
  previewSql(data).then(res => {
    console.log(res)
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      columns.value = res.data.table.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//点击上线按钮弹出选择菜单框
const handleTopLine = () => {
  getMenuOpt().then(res => {
    menuOpt.value = [{
      value: 0,
      label: "一级目录",
      children: res.data
    }]
  })
  isTopLineVisited.value = true
}
const restForm = () => {
  form.value = {
    parentId: ''
  }
}
//取消
const handleCancel = () => {
  restForm();
  isTopLineVisited.value = false;
};
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid, fields) => {
    if (!valid) return
    let data = {
      menuId: form.value.parentId,
      queryId: queryId,
      uniSql: queryParams.uqSql,
      uniCons: columns.value,
      uniColumns: []
    }
    sqlToLine(data).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        router.push({path: `/custom/query/sql`})
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
getSqlQueryInfo()
</script>

<style lang="scss" scoped>
.code-editor {
  border: 1px solid #b3b3b3;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}
</style>
