<template>
  <div>
    <amis-sdk :amis-json="{ ...amisJson, ...{ value: defaultValueExp, variables: variables } }" v-model="nowComputedField.columnFormula" ref="amis"></amis-sdk>
    <!--    {{ nowComputedField.columnFormula }}-->
    <el-button style="width: 100%" round @click="addFuncClick">设置{{ defaultValueExp }}</el-button>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="'默认值表达式'"
      :visible.sync="showEditComputedField"
      append-to-body
      class="dataset-edit-computed-fields"
      width="920px"
    >
      <div class="panels">
        <div class="main">
          <div class="label label-title">
            <aceEditor ref="editor" v-model="nowComputedField.columnFormula" height="480" lang="javascript" snippets wrap />
          </div>
        </div>
        <div class="panel" style="margin-right: 10px">
          <div class="label">点击引用字段</div>
          <div class="search-box">
            <el-input v-model="computedSearchKey" clearable placeholder="输入以搜索" size="mini"></el-input>
          </div>
          <div class="fields">
            <div class="tab">表单字段</div>
            <template v-for="field of drawAllListed">
              <div :key="field.__vModel__" :title="field.__config__.label" class="weidu" @click="onComputedAddField(field)">
                {{ field.__config__.label }}
              </div>
            </template>
            <div class="tab">API变量</div>
            <!--            <template v-for="field of apiVarListed">-->
            <!--              <div :key="field.label" :title="field.label" class="zhibiao" @click="onComputedAddAPIField(field)">-->
            <!--                {{ field.label }}-->
            <!--              </div>-->
            <!--            </template>-->
            <!--            <template v-for="field of tobeChooseWeiduSearched">-->
            <!--              <div v-if="nowComputedField.columnTitle !== field.columnTitle" :key="field.columnTitle" :title="field.columnName" class="weidu" @click="onComputedAddField(field)">-->
            <!--                {{ field.columnTitle + '【' + field.columnName + '】' }}-->
            <!--              </div>-->
            <!--            </template>-->
            <!--            <div class="tab">指标</div>-->
            <!--            <template v-for="field of tobeChooseZhibiaoSearched">-->
            <!--              <div v-if="nowComputedField.columnTitle !== field.columnTitle" :key="field.columnTitle" :title="field.columnName" class="zhibiao" @click="onComputedAddField(field)">-->
            <!--                {{ field.columnTitle + '【' + field.columnName + '】' }}-->
            <!--              </div>-->
            <!--            </template>-->
          </div>
        </div>
        <div class="panel">
          <div class="label">点击引用函数</div>
          <div class="search-box">
            <el-select v-model="funcAttr" size="mini" style="width: 110px" @change="onSearchFunc">
              <el-option v-for="(attr, i) of funcAttrList" :key="i" :label="attr.message" :value="attr.value"></el-option>
            </el-select>
            <el-input v-model="funcKey" clearable placeholder="搜索" size="mini" style="width: 90px" @input="onSearchFunc"></el-input>
          </div>
          <div class="functions">
            <div v-for="(func, i) of functionListSearched" :title="func.description" class="func" @click="onComputedAddFunc(func.method)">
              {{ func.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="btns">
        <el-button size="mini" @click="showEditComputedField = false"> 取消</el-button>
        <el-button size="mini" type="primary" @click="onEditComputedFieldConfirm"> 确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cubeDetail, jsfuncAttrList, jstableFunctionList } from '@/api/newbi/dataset'
import { getDatasourceDetail } from '@/components/Dataset-filter/report'
import aceEditor from '@/components/AceEditor'
import { deepClone, loopActiveTabelList, loopCustomTabelList } from '@/utils'
import AmisSdk from '@/components/AmisSdk.vue'
export default {
  props: ['dbLinkId', 'defaultValueExp', 'drawList', 'activeData'],
  components: { AmisSdk, aceEditor },
  name: 'customExpression',
  data() {
    return {
      showEditComputedField: false,
      datasource: null,
      functionList: [], // 用于创建计算字段的函数列表
      functionListSearched: [],
      funcAttr: -1,
      funcAttrList: [],
      funcKey: '',
      computedSearchKey: '',
      tobeChooseWeidu: [], // 计算字段编辑框里维度字段
      tobeChooseZhibiao: [], // 计算字段编辑框里指标字段
      drawAllList: [],
      apiVarList: [],
      nowComputedField: {
        columnFormula: ''
      }, // 当前计算字段
      amisJson: {
        type: 'input-formula',
        name: 'formula',
        evalMode: true,
        value: '',
        variableMode: 'tabs',
        variables: [],
        functions: functionsCumtom,
        env: true,
        inputSettings: {
          isError: false
        }
      },
      functions: [],
      columnFormula: '',
      variables: []
    }
  },
  created() {
    // this.fillback(this.dbLinkId)
    this.getInitData()
    this.getFuncList()
    this.getValList()
    // this.apiVarListed()
  },
  watch: {
    'nowComputedField.columnFormula'(val) {
      this.onEditComputedFieldConfirm()
    }
  },
  mounted() {},
  computed: {
    // 计算字段编辑框里维度字段
    drawAllListed() {
      let key = this.computedSearchKey
      // return this.drawAllList.filter((i) => {
      //   return i.__config__.label.toUpperCase().includes(key)
      // })
      const field = this.drawAllList
        .filter((i) => {
          return i.__config__.label.toUpperCase().includes(key)
        })
        .map((i) => {
          return {
            label: i.__config__.label,
            value: i.__vModelName__,
            tag: i.__vModelName__.replace(/^.*formulaF_(\w+)/, '$1')
          }
        })
      this.variables.push({
        label: '表单字段',
        children: field
      })
      const fieldd = this.apiVarList
        .filter((i) => {
          return i.label.toUpperCase().includes(key)
        })
        .map((i) => {
          i.value = `$${i.value}`
          return i
        })

      this.variables.push({
        label: 'API变量',
        children: fieldd
      })
      //   birthday: '2024-03-11 13:44:14',
      //   sex: 1,
      //   roleId: '1767063960479801346',
      //   deptId: '1767063960857288705',
      //   postId: '1767063961364799490',
      //   userTypeName: null,
      //   roleName: '管理员',
      //   deptName: '杨帆',
      //   postName: '首席执行官',
      const systemField = [
        {
          label: '登录账号',
          value: 'systemGlobal_account'
        },
        {
          label: '用户昵称',
          value: 'systemGlobal_name'
        },
        {
          label: '用户姓名',
          value: 'systemGlobal_realName'
        },
        {
          label: '电话',
          value: 'systemGlobal_phone'
        }
      ]
      // this.variables.push({
      //   label: '全局变量',
      //   children: systemField
      // })
    },
    // 计算字段编辑框里指标字段
    apiVarListed() {}
  },
  methods: {
    // 获取表单的变量
    getValList() {
      this.apiVarList = []
      let list = deepClone(this.drawList)
      let mapList = this.activeData.__config__.relationTable ? loopActiveTabelList(list, this.activeData.__config__.relationTable) : deepClone(this.drawList)
      this.drawAllList = loopCustomTabelList(list)
      mapList.forEach((item, key) => {
        let config = item.__config__
        if (config.ApiReturn && config.ApiReturn.length) {
          let list = config.ApiReturn.map((o) => {
            return {
              label: o.varName,
              value: o.varName
            }
          }).filter((l) => l !== undefined)
          this.apiVarList = [...this.apiVarList, ...list]
        }
      })
    },
    addFuncClick() {
      this.showEditComputedField = true
      this.$nextTick(() => {
        this.$refs.editor.editor.setValue('')
        if (this.defaultValueExp) this.onComputedAddFunc(this.defaultValueExp)
      })
    },
    // 获取初始化数据,
    getInitData() {
      //获取数据集
      // cubeFieldList({ cubeDataId: this.dbLinkId }).then((res) => {
      //   let tableFieldsWeidu = res.data.data.filter((i) => i.dimensionType === 'WEIDU').sort((a, b) => a.sortNum - b.sortNum)
      //   let tableFieldsZhibiao = res.data.data.filter((i) => i.dimensionType === 'ZHIBIAO').sort((a, b) => a.sortNum - b.sortNum)
      //   this.tobeChooseWeidu = tableFieldsWeidu.filter((i) => i.columnAttr == 'NORMAL')
      //   this.tobeChooseZhibiao = tableFieldsZhibiao.filter((i) => i.columnAttr == 'NORMAL')
      // })
      // jsfuncAttrList().then((res) => {
      //   let list = res.data.data
      //   this.funcAttrList = list
      //   console.log(this.functions)
      // })
    },
    async fillback(id) {
      let cubeRes = await cubeDetail({ cubeDataId: id })
      if (!cubeRes.data.code === 200) return
      let { datasourceId } = cubeRes.data.data
      // 获取数据源详情
      getDatasourceDetail({ id: datasourceId }).then((res) => {
        this.datasource = res.data.data
        this.getFuncList()
      })
    },
    // 获取当前数据源类型下计算函数
    getFuncList() {
      jstableFunctionList().then((res) => {
        this.functionList = res.data.data
        this.functionListSearched = [...this.functionList]
        this.funcAttr = -1
      })
    },
    onSearchFunc() {
      let { name } = this.funcAttrList.find((i) => i.value == this.funcAttr)
      let funcKey = this.funcKey.toLowerCase()
      let list = []
      if (this.funcAttr == -1) {
        list = [...this.functionList]
      } else {
        list = this.functionList.filter((i) => i.funcAttr == name)
      }
      this.functionListSearched = list.filter((i) => {
        let name = i.name.toLowerCase()
        let description = i.description.toLowerCase()
        return name.includes(funcKey) || description.includes(funcKey)
      })
    },
    // 表单字段拼入字段
    onComputedAddField(field) {
      this.$refs.editor.editor.insert(`[${field.__config__.label}]`)
    },
    // api变量拼入字段
    onComputedAddAPIField(field) {
      this.$refs.editor.editor.insert(`[$${field.label}]`)
    },
    // 计算字段拼入函数
    onComputedAddFunc(method) {
      const beautify_js = require('js-beautify')
      const beautify_css = require('js-beautify').css
      const beautify_html = require('js-beautify').html

      let content = beautify_js(method, {
        indent_size: 2,
        html: {
          end_with_newline: true,
          js: {
            indent_size: 2
          },
          css: {
            indent_size: 2
          }
        },
        css: {
          indent_size: 1
        },
        js: {
          'preserve-newlines': true
        }
      })
      this.$refs.editor.editor.insert(method)
    },
    onEditComputedFieldConfirm() {
      let { columnFormula } = this.nowComputedField
      if (!columnFormula) {
        return this.$message({ message: '请补充完整', type: 'warning' })
      }
      this.$emit('onChangeExp', columnFormula)
      this.showEditComputedField = false
    }
  }
}
</script>

<style scoped lang="scss">
.panels {
  display: flex;
  .main {
    flex: 1;
    margin-right: 10px;
    .label-title {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .panel {
    flex: 0 0 200px;
    width: 200px;
    font-size: 12px;
    .tab {
      line-height: 30px;
    }
    .functions,
    .fields {
      height: 430px;
      overflow-y: auto;
      padding: 0 10px 10px;
      background-color: #fff;
    }
    .search-box {
      height: 35px;
    }
    .weidu {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #1d54d5;
      background-color: #e4eafa;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
    .zhibiao {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #00b375;
      background-color: #d4f2e8;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
    .func {
      line-height: 24px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      padding: 0 10px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 3px 0;
      cursor: pointer;
    }
  }
}
.btns {
  text-align: right;
  margin-top: 10px;
  .el-button {
    width: 100px;
  }
}
:deep(.amis-scope .cxd-FormulaEditor-FuncList.withDoc) {
  max-height: 80% !important;
}
</style>
