<template>
  <el-row v-loading="loading">
    <el-form-item label="控件标题">
      <el-input v-model="activeData.__config__.label" placeholder="请输入控件标题" />
    </el-form-item>
    <el-form-item label="显示标题">
      <el-switch v-model="activeData.__config__.showTitle" />
    </el-form-item>
    <el-form-item label="控件栅格">
      <el-slider v-model="activeData.__config__.span" :max="24" :min="6" show-stops :step="2" show-tooltip />
    </el-form-item>
    <el-form-item v-if="activeData.actionText !== undefined" label="动作文字">
      <el-input v-model="activeData.actionText" placeholder="请输入动作文字" />
    </el-form-item>
    <el-form-item v-if="activeData.actionText !== undefined" label="连续扫码">
      <el-switch v-model="activeData.isScan"></el-switch>
    </el-form-item>
    <el-form-item label="表数据源" v-if="$store.getters.hasTable">
      <el-select v-model="activeData.__config__.tableName" placeholder="请选择子表数据源" clearable filterable @change="onTableNameChange">
        <el-option v-for="item in tableList" :key="item.tableViewName" :label="item.tableComments + ' ' + item.tableViewName" :value="item.tableViewName"> </el-option>
      </el-select>
    </el-form-item>
    <el-divider>主子表关联设置</el-divider>
    <el-form-item v-if="activeData.actionText !== undefined" label="主表字段">
      <el-select v-model="activeData.relationConf.primaryModel" placeholder="请选择控件字段" clearable filterable @change="getPrimaryColumnName($event)">
        <el-option v-for="item in formItemList" :key="item.id" :value="item.id" :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="activeData.actionText !== undefined" label="子表字段">
      <el-select v-model="activeData.relationConf.foreignModel" placeholder="请选择控件字段" clearable filterable @change="getForeignColumnName($event)">
        <el-option
          v-for="item in activeData.relationTables"
          :key="item.id"
          :value="item.id"
          :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-tooltip content="" placement="top">
      <div slot="content">注：如表单物理表字段进行了增删改情况，可以通过刷新同步主表结构进行同步更新。<br />同步新结构后，请调整表单设计，避免不必要的异常情况;</div>
      <el-button :disabled="!activeData.dbLinkId" @click="fieldCompareChange" type="success" plain style="margin: 10px 0"> 刷新同步表结构<i class="el-icon-question" /> </el-button>
    </el-tooltip>
    <el-divider>子表关联录入设置</el-divider>
    <el-form-item label="子表关联录入" label-width="100px">
      <el-switch v-model="activeData.relationConfFlag" />
    </el-form-item>
    <el-form-item>
      <template slot="label">
        <span>选择表单</span>
        <el-tooltip style="cursor: pointer" effect="dark" :content="'被选择的表单需同时符合【是一个单表表单】才会在下拉选择中展示'" placement="top">
          <i class="el-icon-question" />
        </el-tooltip>
      </template>
      <el-select v-model="activeData.relationConf.itemRelationTable" filterable placeholder="请选择" clearable @change="onRelationTableChange($event)">
        <el-option
          v-for="(item, index) in allTabelList.filter((o) => o.visualdevTableType && o.visualdevTableType == 1)"
          :label="item.fullName"
          :value="item.id"
          :key="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="字段映射关联" label-width="100px">
      <el-button @click="setRelationColumn" :disabled="renlationColumnsList.length === 0" type="success" plain> 设置 </el-button>
      <el-button @click="setFilterColumn" type="success" plain> 添加过滤条件 </el-button>
    </el-form-item>
    <el-form-item v-if="activeData.relationActionText !== undefined" label="批量动作文字" label-width="100px">
      <el-input v-model="activeData.relationActionText" placeholder="请输入批量动作文字" />
    </el-form-item>
    <el-form-item label="关联字段展示" label-width="100">
      <template v-for="(item, index) in activeData.__config__.children">
        <el-tag class="showRelationTitle" v-if="getColumnTitle(item.__vModel__)">{{ item.__config__.label }}</el-tag>
      </template>
    </el-form-item>
    <el-dialog title="字段映射关联" :visible.sync="dialogVisible" width="600px" append-to-body>
      <div>
        <el-table :data="activeData.relationColumnList" border style="width: 100%">
          <el-table-column :label="'数据关联表:' + relationPrimaryTableName">
            <template slot-scope="scope">
              <el-select v-model="scope.row.primaryId" filterable placeholder="请选择控件字段" clearable>
                <el-option v-for="(item, index) in renlationColumnsList" :label="item.label" :value="item.propId" :key="item.propId"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="'子表:' + activeData.__config__.tableName">
            <template slot-scope="scope">
              <el-select v-model="scope.row.foreignId" placeholder="请选择控件字段" clearable filterable>
                <el-option
                  v-for="item in activeData.relationTables"
                  :key="item.id"
                  :value="item.id"
                  :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column width="80">
            <template slot-scope="scope">
              <el-button type="text" @click="activeData.relationColumnList.length > 1 ? activeData.relationColumnList.splice(scope.$index, 1) : ''"
                ><i style="font-size: 20px" class="el-icon-delete"></i
              ></el-button>
              <el-button type="text" @click="activeData.relationColumnList.push({ primaryId: '', foreignId: '' })"><i style="font-size: 20px" class="el-icon-circle-plus-outline"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="字段映射关联" :visible.sync="filterDialogVisible" width="600px" append-to-body>
      <el-button type="success" plain size="mini" @click="activeData.relationConf.filterColumnList.push({ columnId: '', viewDataType: 'STRING', function: 'like', value: '' })"
        >+添加筛选条件</el-button
      >
      <el-table v-loading="loading" size="mini" :data="activeData.relationConf.filterColumnList" border style="width: 100%; margin: 10px 0">
        <el-table-column width="50" align="center">
          <template slot-scope="scope">
            <i class="el-icon-delete" style="font-size: 20px" @click="activeData.relationConf.filterColumnList.splice(scope.$index, 1)"></i>
          </template>
        </el-table-column>
        <el-table-column label="表单字段" width="180" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.columnId"
              filterable
              placeholder="请选择表单字段"
              clearable
              @change="
                scope.row.function = ''
                scope.row.viewDataType = renlationColumnsList.find((o) => o.propId === scope.row.columnId)?.config?.viewDataType
              "
            >
              <el-option v-for="(item, index) in renlationColumnsList" :label="item.label" :value="item.propId" :key="item.propId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="过滤条件" width="130" align="center">
          <template slot-scope="scope">
            <el-select
              size="mini"
              v-model="scope.row.function"
              placeholder="选择条件"
              @change="
                scope.row.function === 'between'
                  ? scope.row.viewDataType === 'NUMBER'
                    ? (scope.row.value = ['', ''])
                    : (scope.row.value = [])
                  : scope.row.function === 'in'
                    ? (scope.row.value = [])
                    : (scope.row.value = '')
              "
            >
              <el-option v-for="func of globalFunctions[scope.row.viewDataType].filter((o) => o.function !== 'in')" :key="func.function" :value="func.function" :label="func.label"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="赋值" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.viewDataType === 'STRING' || scope.row.viewDataType === 'NUMBER'">
              <template v-if="scope.row.function === 'eq' || scope.row.function === 'like' || scope.row.function === ''">
                <el-input v-model="scope.row.value" style="width: 130px; margin-left: 10px" placeholder="value"></el-input>
              </template>
              <template v-if="scope.row.function === 'between'">
                <el-input style="width: 100px" size="mini" v-model="scope.row.value[0]" placeholder="输入值"></el-input>
                <span>~</span>
                <el-input style="width: 100px" size="mini" v-model="scope.row.value[1]" placeholder="输入值"></el-input>
              </template>
            </template>
            <template v-if="scope.row.viewDataType === 'DATETIME'">
              <el-date-picker style="width: 220px" v-model="scope.row.value" type="daterange" placeholder="选择日期" clearable value-format="timestamp"></el-date-picker>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="filterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="filterDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>
<script>
import comMixin from './mixin'
import { createCubeByTable, cubeFieldList, cubeFieldOption } from '@/api/workFlow/FlowEngine'
import { fieldCompare, getConfigData } from '@/api/onlineDev/visualDev'
import { globalFunctions } from '@/utils/dict'

export default {
  props: ['activeData', 'dbtableList', 'dbSourceId', 'columnModelId', 'allTabelList'],
  mixins: [comMixin],
  data() {
    return {
      tableList: [],
      loading: false,
      dialogVisible: false,
      filterDialogVisible: false,
      renlationColumnsList: [],
      relationPrimaryTableName: ''
    }
  },
  created() {
    this.tableList = this.dbtableList
    this.activeData.__config__.dbSourceId = this.dbSourceId
    if (this.activeData.relationConf.itemRelationTable) this.onRelationTableChange(this.activeData.relationConf.itemRelationTable)
  },
  computed: {
    globalFunctions() {
      return globalFunctions
    },
    formItemList() {
      return this.$store.state.generator.dbItemList
    }
  },
  methods: {
    // 刷新同步主表结构
    fieldCompareChange() {
      fieldCompare(this.activeData.dbLinkId).then((res) => {
        let data = res.data.data[0]
        let creatData = data.fieldsCreat
          .map((i) => {
            return i.columnName
          })
          .join(',')
        let updateData = data.fieldsUpdate
          .map((i) => {
            return i.columnName
          })
          .join(',')
        let deletedData = data.fieldsDeleted
          .map((i) => {
            return i.columnName
          })
          .join(',')
        // 自定义模板
        const notifyTemplate = `
<!--            <div>-->
                <p style="text-align: initial;"><span>新增字段：</span><span>${creatData || '暂无更新'}</span></p>
                <p style="text-align: initial;"><span>修改字段：</span><span>${updateData || '暂无更新'}</span></p>
                <p style="text-align: initial;"><span>删除字段：</span><span>${deletedData || '暂无更新'}</span></p>
<!--            </div>-->
        `
        const h = this.$createElement
        this.$notify({
          title: '提示',
          message: notifyTemplate,
          dangerouslyUseHTMLString: true,
          duration: 0
        })
      })
    },
    onTableNameChange(tableName) {
      this.loading = true
      this.$set(this.activeData.__config__, 'tableName', tableName)
      for (let i = 0; i < this.activeData.__config__.children.length; i++) {
        this.$set(this.activeData.__config__.children[i].__config__, 'relationTable', tableName)
        this.$set(this.activeData.__config__.children[i], '__vModel__', '')
      }
      this.onTableViewName(tableName)
    },
    onTableViewName(val) {
      const param = new URLSearchParams()
      param.append('tableName', val)
      param.append('datasourceId', this.dbSourceId)
      param.append('modelId', this.columnModelId)
      param.append('modelName', this.activeData.__config__.label)
      createCubeByTable(param).then((res) => {
        this.onDbChange(res.data.data.id)
        this.$set(this.activeData, '__vModel__', res.data.data.id)
      })
    },
    onDbChange(val) {
      this.activeData.dbLinkId = val
      //获取数据集
      cubeFieldList({ cubeDataId: val }).then((res) => {
        // this.mainTableFields = res.data.data
        let reverseData = res.data.data.reverse()
        this.activeData.relationTables = reverseData
        //获取数据集详细信息
        cubeFieldOption({ cubeId: val }).then((value) => {
          let FieldObj = value.data.data
          //分组后过滤后的数据集 渲染组件
          this.activeData.mainTableFields = this.getmapList(reverseData, FieldObj)
          this.$nextTick(() => {
            this.activeData.tables = []
            this.newChangeTable(reverseData, FieldObj)
            this.loading = false
          })
        })
      })
    },
    //重装list
    getmapList(data, obj) {
      //判断是否为虚拟字段 是否为主键 是否为关联字段
      let filterList = data
        .map((o, i) => {
          if (obj[o.id]) {
            if (o.columnAttr === 'NORMAL' && o.hiddenStatus === 0 && obj[o.id].primaryKey === false && obj[o.id].isJoin === false) {
              o.isRequiredType = obj[o.id].required || obj[o.id].isJoined
              return o
            }
          }
        })
        .filter((l) => l !== undefined)
      //查询计算字段
      let VIRTUALList = data
        .map((o, i) => {
          if (o.columnAttr === 'VIRTUAL') {
            return o
          }
        })
        .filter((l) => l !== undefined)
      return filterList.concat(VIRTUALList)
    },
    //存储table
    newChangeTable(data, obj) {
      if (!this.activeData.tables.length) {
        let fields = data
          .map((o) => {
            if (obj[o.id]) {
              if (o.columnAttr === 'NORMAL' && obj[o.id].primaryKey === false && obj[o.id].isJoin === false) {
                return {
                  field: o.columnName,
                  fieldId: o.id,
                  fieldName: o.columnTitle,
                  dataType: o.viewDataType,
                  tableAliasName: o.tableAliasName,
                  tableName: o.tableName
                }
              }
            }
          })
          .filter((l) => l !== undefined)
        //查询计算字段
        let VIRTUALList = data
          .map((o, i) => {
            if (o.columnAttr === 'VIRTUAL') {
              return {
                field: o.columnName,
                fieldId: o.id,
                fieldName: o.columnTitle,
                dataType: o.viewDataType,
                tableAliasName: o.tableAliasName,
                tableName: o.tableName ? o.tableName : '其他数据表'
              }
            }
          })
          .filter((l) => l !== undefined)
        this.activeData.tables = [...fields, ...VIRTUALList]
      }
    },
    getPrimaryColumnName(v) {
      this.activeData.relationConf.primaryModelName = this.formItemList.find((o) => o.id === v).columnName
    },
    getForeignColumnName(v) {
      this.activeData.relationConf.foreignModelName = this.activeData.relationTables.find((o) => o.id === v).columnName
    },
    setRelationColumn(v) {
      this.dialogVisible = true
      if (!this.activeData.relationColumnList.length) {
        this.activeData.relationColumnList.push({ primaryId: '', foreignId: '' })
      }
    },
    setFilterColumn() {
      this.filterDialogVisible = true
      if (!this.activeData.relationConf.filterColumnList || !this.activeData.relationConf.filterColumnList.length) {
        this.activeData.relationConf.filterColumnList = [{ columnId: '', viewDataType: 'STRING', function: 'like', value: '' }]
      }
    },
    onRelationTableChange(v) {
      this.loading = true
      getConfigData(v).then((res) => {
        let data = res.data.data
        this.relationPrimaryTableName = data.primaryTableName
        let columnData = JSON.parse(data.columnData)
        this.renlationColumnsList = columnData.columnList
        this.loading = false
      })
    },
    getColumnTitle(id) {
      let data = this.activeData.relationColumnList.find((item) => item.foreignId === id)
      return !!data
    }
  }
}
</script>
<style scoped lang="scss">
.showRelationTitle + .showRelationTitle {
  margin-left: 10px;
}
</style>
