import { DataModelFieldList } from '@/api/systemData/dataModel'
import { cubeFieldList, cubeFieldListBatch } from '@/api/workFlow/FlowEngine'

export default {
  data() {
    return {}
  },
  methods: {
    goTop() {
      // window.open(this.define.HashUrl + 'workflow/flowEngine','_self')
      this.closeDialog(true)
    },
    closeDialog(isRefresh) {
      var userAgent = navigator.userAgent
      if (userAgent.indexOf('Firefox') != -1 || userAgent.indexOf('Chrome') != -1) {
        window.open('', '_self').close() //火狐默认状态非window.open的页面window.close是无效的
      } else {
        window.opener = null
        window.open('about:blank', '_self').close()
      }
    },
    prve() {
      this.activeStep -= 1
    },
    stepChick(key) {
      if (this.activeStep <= key) return
      this.activeStep = key
    },
    zOnDbChange(val) {
      //获取数据集
      cubeFieldList({ cubeDataId: val }).then((res) => {
        let reverseData = res.data.data.reverse()
        // this.mainTableFields.push(reverseData)
        this.newChangeTable(reverseData)
        this.$nextTick(() => {
          if (!this.dataForm.secondaryDbLinkId.length) {
            this.loading = false
            if (this.activeStep == 1 && this.dataForm.modeType === 2) {
              this.getmainTableList()
            }
          }
        })
      })
    },
    onDbChange(val) {
      //获取数据集
      cubeFieldListBatch(val).then((res) => {
        this.mainTableFields = res.data.data
        this.$nextTick(() => {
          this.loading = false
          if (this.activeStep == 1 && this.dataForm.modeType === 2) {
            this.getmainTableList()
          }
        })
      })
      // })
    },
    //重装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') {
            if (!o.tableName) {
              o.tableName = '其他数据表'
            }
            return o
          }
        })
        .filter((l) => l !== undefined)
      let concatList = filterList.concat(VIRTUALList)
      //根据数据表分类
      let Idlist = concatList
        .map((o, i) => {
          return {
            id: i,
            tableName: o.tableName,
            children: []
          }
        })
        .filter((l) => l !== undefined)
      //去重分类
      let NewList = this.getfilterList(Idlist, 'tableName')
      //小蝌蚪找妈妈
      NewList.forEach((item, index) => {
        concatList.forEach((value, key) => {
          if (item.tableName === value.tableName) {
            item.children.push(value)
          }
        })
      })
      return NewList
    },
    getfilterList(arr, u_key) {
      let map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    },
    //存储table
    newChangeTable(data) {
      this.tables = data
        .map((o) => {
          return {
            field: o.columnName,
            fieldId: o.id,
            fieldName: o.columnTitle,
            dataType: o.viewDataType,
            tableAliasName: o.tableAliasName,
            tableName: o.tableName,
            cubeDataId: o.cubeDataId
          }
        })
        .filter((l) => l !== undefined)
    },
    openTableBox() {
      if (!this.dataForm.dbLinkId) {
        this.$message({
          message: '请先选择数据库',
          type: 'error',
          duration: 1000
        })
        return
      }
      this.formVisible = true
    },
    async colseForm(data) {
      const type = this.dataForm.type
      let queryType = 0
      if (type == 3 || type == 4 || type == 5) queryType = 1
      let checkList = []
      if (!this.tables.length) {
        for (let i = 0; i < data.length; i++) {
          const e = data[i]
          let relationTable = data[0].table
          let typeId = i == 0 ? '1' : '0'
          let res = await DataModelFieldList(this.dataForm.dbLinkId, e.table, queryType)
          let fields = res.data.data.list.map((o) => ({ field: o.field, fieldName: o.fieldName, dataType: o.dataType }))
          let item = {
            relationField: '',
            relationTable: i == 0 ? '' : relationTable,
            table: e.table,
            fieldId: e.id,
            tableName: e.tableName,
            tableField: '',
            typeId,
            fields
          }
          checkList.push(item)
        }
        this.relationTable = checkList[0].table
        this.mainTableFields = checkList[0].fields
        this.tables = checkList
      } else {
        for (let i = 0; i < data.length; i++) {
          const e = data[i]
          let boo = this.tables.some((o) => o.table == e.table)
          if (!boo) {
            let res = await DataModelFieldList(this.dataForm.dbLinkId, e.table, queryType)
            let fields = res.data.list.map((o) => ({ field: o.field, fieldName: o.fieldName, dataType: o.dataType }))
            let item = {
              relationField: '',
              relationTable: this.relationTable,
              table: e.table,
              fieldId: e.id,
              tableName: e.tableName,
              tableField: '',
              typeId: '0',
              fields
            }
            checkList.push(item)
          }
        }
        this.tables = [...this.tables, ...checkList]
      }
    },
    async updateFields() {
      if (!this.tables.length) return
      this.dataForm.dbLinkId = this.dataForm.dbLinkId || '0'
      const type = this.dataForm.type
      let queryType = 0
      if (type == 3 || type == 4 || type == 5) queryType = 1
      for (let i = 0; i < this.tables.length; i++) {
        let res = await DataModelFieldList(this.dataForm.dbLinkId, this.tables[i].table, queryType)
        let fields = res.data.data.list.map((o) => ({ field: o.field, fieldName: o.fieldName, dataType: o.dataType }))
        this.tables[i].fields = fields
        if (this.tables[i].typeId == '1') {
          this.mainTableFields = this.tables[i].fields
          this.relationTable = this.tables[i].table
        }
      }
    },
    getDbOptions() {
      const defaultItem = {
        fullName: '',
        children: [
          {
            fullName: '默认数据库',
            id: '0'
          }
        ]
      }
      // getDataSourceListAll().then(res => {
      //   const list = [defaultItem, ...res.data.data.list]
      //   this.dbOptions = list.filter(o => o.children && o.children.length)
      // }).catch(() => {
      //   this.dbOptions = [defaultItem]
      // })
    },
    delItem(row, index) {
      this.tables.splice(index, 1)
      if (row.typeId == '1' && this.tables.length) {
        this.tables[0].typeId = '1'
        this.tables[0].relationTable = ''
        this.mainTableFields = this.tables[0].fields
        this.relationTable = this.tables[0].table
      }
    },
    changeTable(row) {
      this.relationTable = row.table
      this.mainTableFields = row.fields
      for (let i = 0; i < this.tables.length; i++) {
        this.$set(this.tables[i], 'typeId', this.tables[i].table === row.table ? '1' : '0')
        this.$set(this.tables[i], 'relationTable', this.tables[i].table === row.table ? '' : this.relationTable)
        this.$set(this.tables[i], 'relationField', '')
        this.$set(this.tables[i], 'tableField', '')
      }
    },
    exist() {
      let isOk = true
      // for (let i = 0; i < this.tables.length; i++) {
      //   const e = this.tables[i];
      //   if (e.typeId == '0') {
      //     if (!e.tableField) {
      //       this.$message({
      //         showClose: true,
      //         message: `表${e.table}外键字段不能为空`,
      //         type: 'warning',
      //         duration: 1000
      //       });
      //       isOk = false
      //       break
      //     }
      //   }
      //   if (e.typeId == '0') {
      //     if (!e.relationField) {
      //       this.$message({
      //         showClose: true,
      //         message: `表${e.table}关联主键不能为空`,
      //         type: 'warning',
      //         duration: 1000
      //       });
      //       isOk = false
      //       break
      //     }
      //   }
      // }
      return isOk
    }
  }
}
