import { Create, CreateSerialnumber, getCateInfo, getCateList, getVisualDevInfo, Update } from '@/api/onlineDev/visualDev'
import { categoryList as cubeCategoryList, cubeList, reportdatasourceList, temporarySubmit } from '@/api/workFlow/FlowEngine'
import commonMixin from '@/mixins/generator/common'
import { deepClone, loopRelationList } from '@/utils'
import { debounce } from 'throttle-debounce'
import { saveDrawingList } from '@/components/Generator/utils/db'
import { cubeFieldList } from '@/api/newbi/dataset'

export default {
  mixins: [commonMixin],
  data() {
    return {
      visible: false,
      loading: false,
      activeStep: 0,
      dataForm: {
        id: '',
        fullName: '',
        enCode: '',
        visualdevType: 1,
        webType: 2,
        modeType: 1,
        dbLinkId: '',
        dbSourceId: '',
        primaryTableName: '',
        state: 1,
        webScene: 'PC',
        category: '',
        description: '',
        visualdevTables: '',
        Strategy: 1
      },
      dataRule: {
        fullName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        enCode: [
          { required: true, message: '编码不能为空', trigger: 'blur' },
          { validator: this.formValidate('enCode'), trigger: 'blur' }
        ],
        category: [{ required: true, message: '分类不能为空', trigger: 'change' }],
        state: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      stepLoading: false,
      maxStep: 4,
      tables: [],
      formVisible: false,
      btnLoading: false,
      formData: null,
      relationData: [],
      logicData: [],
      columnData: null,
      flowTemplateJson: null,
      categoryList: [],
      dbOptions: [],
      mainTableFields: [],
      relationTable: '',
      cubeList: [],
      datasourceList: [],
      tableList: [],
      tableFlag: false,
      tableFlagComment: '当前物理表主键无自增策略，自动选择为“业务系统自动生成”',
      allTabelList: [], //表单列表

      isAddColumn: false,
      cubeResult: {}
    }
  },
  created() {
    this.getList()
    this.$nextTick(() => {
      // this.getDataList()
      this.getDbSource()
    })
  },
  methods: {
    openPrview() {
      window.open('#/previewModel?isPreview=1&token=saber-token&id=' + this.dataForm.id, '_blank')
    },
    goTop() {
      if (this.dataForm.id) {
        window.location.href = '#/previewModel?isPreview=1&token=saber-token&id=' + this.dataForm.id
      } else {
        this.closeDialog(true)
      }
      // window.open(this.define.HashUrl + 'workflow/webDesign','_self')
    },
    init(id, type, webType) {
      getCateList().then((res) => {
        let origin = res.data.data || []
        origin.forEach((i) => delete i.children)
        let categoryList = deepClone(origin)
        let parents = categoryList.filter((i) => !i.parentId).sort((b, a) => b.sortCode - a.sortCode)
        parents.forEach((p) => {
          let children = categoryList.filter((i) => i.parentId === p.id)
          if (children) {
            p.children = children.sort((b, a) => b.sortCode - a.sortCode)
            children.forEach((pp) => {
              let children2 = categoryList.filter((i) => i.parentId === pp.id)
              if (children2) pp.children = children2.sort((b, a) => b.sortCode - a.sortCode)
            })
          }
        })
        parents.unshift({ fullName: '顶级分类', id: 0 })
        this.categoryList = parents
      })
      this.activeStep = 0
      this.tables = []
      this.dataForm.id = id || ''
      // this.getDbOptions()
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.loading = true
          getVisualDevInfo(this.dataForm.id)
            .then((res) => {
              this.dataForm = res.data.data
              this.dataForm.webType = this.dataForm.webType || 2
              // this.maxStep = parseInt(this.dataForm.webType)
              this.formData = this.dataForm.formData && JSON.parse(this.dataForm.formData)
              for (let i = 0; i < this.formData.fields.length; i++) {
                if (this.formData.fields[i].__config__.jnpfKey === 'table') {
                  this.$set(this.formData.fields[i], 'oldDbLinkId', this.formData.fields[i].dbLinkId)
                }
              }
              this.columnData = this.dataForm.columnData && JSON.parse(this.dataForm.columnData)
              this.relationData = this.dataForm.relationData && JSON.parse(this.dataForm.relationData)
              this.logicData = this.dataForm.logicData && JSON.parse(this.dataForm.logicData)
              this.columnData.dbLinkId = this.dataForm.dbLinkId && JSON.parse(this.dataForm.dbLinkId)
              this.columnData.modelId = this.dataForm.id
              this.columnData.dbSourceId = this.dataForm.dbSourceId
              this.columnData.primaryTableName = this.dataForm.primaryTableName
              this.flowTemplateJson = this.dataForm.flowTemplateJson && JSON.parse(this.dataForm.flowTemplateJson)
              this.tables = (this.dataForm.visualdevTables && JSON.parse(this.dataForm.visualdevTables)) || []
              // this.updateFields()
              this.loading = false
              this.dataForm.dbLinkId = Number(res.data.data.dbLinkId)
              this.dataForm.dbSourceId = Number(res.data.data.dbSourceId)
              this.dataForm.Strategy = Number(res.data.data.primaryStrategy)
              this.dataForm.modeType = Number(res.data.data.modeType)
              this.$nextTick(() => {
                this.onDbSource(this.dataForm.dbSourceId)
                this.onDbChange(this.dataForm.dbLinkId)
              })
              // 设置浏览器标题
              document.title = this.dataForm.fullName + ' - 表单编辑'
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          let uid = this.getUUid()
          this.columnData = {
            modelId: uid
          }
          this.dataForm.type = type
          this.dataForm.enCode = this.getEncode()
          this.dataForm.webType = webType && webType !== 'undefined' ? webType : 2
          // this.maxStep = parseInt(this.dataForm.webType)
        }
      })
    },
    getUUid() {
      return 'xxxxxxxxxxxx4xxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
      })
    },
    getEncode() {
      return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        return (c === 'x' ? (Math.random() * 12) | 0 : 'r&0x3' | '0x8').toString(12)
      })
    },
    getDbSource() {
      reportdatasourceList().then((res) => {
        let list = res.data.data
        if (list && list.length){
          this.datasourceList = list.filter((i) => i.dsTypeSyl === 'mysql')
        }else {
          this.datasourceList = []
        }
      })
    },
    getList() {
      this.btnLoading = true
      let query = {
        cateId: '',
        current: 1,
        size: 1000,
        name: ''
      }
      getCateInfo(query).then((res) => {
        this.allTabelList = res.data.data.records
        this.btnLoading = false
      })
    },
    getDataList() {
      // 获取数据集列表
      cubeCategoryList({ current: 1, size: 10000 }).then((res) => {
        let category = res.data.data
        category.forEach((item) => {
          item.parent = category.find((i) => i.id === item.parentId)
        })
        let finalCategory = category.map((item) => {
          let value = item.id
          let label = item.wsName
          let parent = item.parent
          while (parent) {
            label = parent.wsName + ' / ' + label
            parent = parent.parent
          }
          return { value, label }
        })
        cubeList({ current: 1, size: 100000 }).then((res) => {
          let list = res.data.data.records
          this.cubeList = finalCategory
            .map((item) => {
              return {
                label: item.label,
                value: -item.value,
                children: list.filter((j) => j.workspaceId === item.value).map((k) => ({ label: k.cubeName, value: k.id }))
              }
            })
            .filter((i) => i.children.length)
        })
      })
    },
    dataFormSubmit() {
      const component = this.getComponent()
      let fun = this.getData()
      if (this.activeStep === 2) {
        fun = this.$refs[component].getData()
      }
      fun
        .then((res) => {
          this.btnLoading = true
          if (this.dataForm.webType == 1) {
            this.formData = res.formData
          } else if (this.dataForm.webType == 3) {
            this.flowTemplateJson = res.formData
          } else {
            this.columnData = res.columnData
          }
          this.dataForm.visualdevTables = JSON.stringify(this.tables)
          this.dataForm.formData = JSON.stringify(this.formData)
          this.dataForm.columnData = JSON.stringify(this.columnData)
          this.dataForm.relationData = JSON.stringify(this.relationData)
          this.dataForm.logicData = JSON.stringify(this.logicData)
          this.dataForm.flowTemplateJson = JSON.stringify(this.flowTemplateJson)
          // 主表信息
          let TablePrimary = this.formData.fields.filter((o) => o.__config__.jnpfKey !== 'table')
          let TablePrimaryFlatten = loopRelationList(TablePrimary)
          let baseVisualdevTablePrimary = {
            formData: JSON.stringify({ fields: TablePrimaryFlatten }),
            visualdevTables: JSON.stringify(this.tables),
            dbLinkId: this.dataForm.dbLinkId,
            primaryStrategy: this.dataForm.Strategy,
            primaryTableName: this.dataForm.primaryTableName,
            deleteDataCheckReferenceRelation: this.formData.deleteDataCheckReferenceRelation,
            deleteDataIgnoringReferenceRelationIds: JSON.stringify(this.formData.deleteDataIgnoringReferenceRelationIds)
          }
          // 子表信息
          let TableForeign = this.formData.fields.filter((o) => o.__config__.jnpfKey === 'table')
          let baseVisualdevTableForeign = TableForeign.map((o) => {
            if (o.__config__.children && o.__config__.children.length) {
              return {
                formData: JSON.stringify({ fields: o.__config__.children }),
                visualdevTables: JSON.stringify(o.tables),
                dbLinkId: o.dbLinkId,
                oldDbLinkId: o.oldDbLinkId,
                foreignColumnId: o.relationConf.foreignModel,
                foreignColumnName: o.relationConf.foreignModelName,
                primaryColumnId: o.relationConf.primaryModel,
                primaryColumnName: o.relationConf.primaryModelName
              }
            }
          })
          // 关联信息
          let relationMapList = loopRelationList(this.formData.fields)
          let AssociationColumn = relationMapList.filter((o) => o.relationData && o.relationData.RelationTableCubeId)
          let PrimaryAssociationColumn = []
          if (AssociationColumn.length) {
            for (let o = 0; o < AssociationColumn.length; o++) {
              let data = {
                associationVisualdevTableId: AssociationColumn[o].relationData.itemRelationTable, //关联表单id
                associationCubeId: AssociationColumn[o].relationData.RelationTableCubeId, //关联表单数据集id
                associationColumnId: [], // 被关联表字段id集合
                visualdevTableColumnId: '', //主表字段id
                associationType: AssociationColumn[o].relationData.isCheck ? 2 : 1, //1多行关联 2多列关联
                associationPrimaryId: AssociationColumn[o].relationData.PrimaryId, // 被关联表主键id
                associationSeparator: AssociationColumn[o].relationData.associationSeparator, // 分隔符
                plaintext: '' // 明文
              }
              let isCheckFlag = AssociationColumn[o].relationData.isCheck
              if (AssociationColumn[o].relationData.itemRelationList.length) {
                let itemRList = AssociationColumn[o].relationData.itemRelationList
                if (isCheckFlag) {
                  let sumbitData = deepClone(data)
                  for (let z = 0; z < itemRList.length; z++) {
                    if (itemRList[z].columnId && itemRList[z].drawId && itemRList[z].drawId === AssociationColumn[o].__vModel__) {
                      sumbitData.associationColumnId.push(itemRList[z].columnId)
                      sumbitData.plaintext = itemRList[z].plaintext
                    }
                  }
                  sumbitData.visualdevTableColumnId = AssociationColumn[o].__vModel__
                  PrimaryAssociationColumn.push(sumbitData)
                } else {
                  for (let z = 0; z < itemRList.length; z++) {
                    if (itemRList[z].columnId && itemRList[z].drawId) {
                      let sumbitData = deepClone(data)
                      sumbitData.associationColumnId.push(itemRList[z].columnId)
                      sumbitData.visualdevTableColumnId = itemRList[z].drawId
                      sumbitData.plaintext = itemRList[z].plaintext
                      PrimaryAssociationColumn.push(sumbitData)
                    }
                  }
                }
              }
            }
          }
          baseVisualdevTablePrimary.associationColumnSize = PrimaryAssociationColumn.length
          baseVisualdevTablePrimary.associationTable = JSON.stringify(this.columnData.associationTable)
          const formMethod = this.dataForm.id ? Update : Create
          this.dataForm.id = this.columnData.modelId
          let param = {
            baseVisualdev: { ...this.dataForm, associationRelation: JSON.stringify(PrimaryAssociationColumn) },
            baseVisualdevTablePrimary,
            baseVisualdevTableForeign,
            deleteCubeId: this.$store.state.generator.deleteCubeList
          }
          this.btnLoading = false
          // return
          formMethod(param)
            .then((res) => {
              //查询当前表单是否存在流水号控件
              let serialRow = this.formData.fields.find((o) => o.__config__.jnpfKey === 'serialNumber')
              if (serialRow) {
                let incNumberRow = serialRow.serialgz.find((o) => o.type === 'incNumber')
                let obj = { modelId: this.dataForm.id, resetCycle: incNumberRow.resetCycle, startValue: incNumberRow.startValue }
                this.CreateSerial(obj, res.data.msg)
              } else {
                const locat = XEUtils.locat()
                locat.hashQuery.id = this.dataForm.id
                const url = XEUtils.serialize(locat.hashQuery)
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    location.replace('#/form/webDesign?' + url)
                    this.btnLoading = false
                  }
                })
              }
            })
            .catch(() => {
              this.btnLoading = false
            })
        })
        .catch((err) => {
          err.msg && this.$message.warning(err.msg)
        })
    },
    CreateSerial(obj, msg) {
      const locat = XEUtils.locat()
      locat.hashQuery.id = this.dataForm.id
      const url = XEUtils.serialize(locat.hashQuery)
      CreateSerialnumber(obj).then(() => {
        this.$message({
          message: msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            location.replace('#/form/webDesign?' + url)
            this.btnLoading = false
          }
        })
      })
    },
    next() {
      if (this.activeStep < 1) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // const type = this.dataForm.type
            // if (!this.tables.length) {
            //   if (type == 3 || type == 4 || type == 5) {
            //     this.$message.warning('请至少选择一个数据表')
            //     return
            //   }
            //   this.$store.commit('generator/SET_TABLE', false)
            //   this.activeStep += 1
            // } else {
            //   if (!this.exist()) return
            //   let subTable = this.tables.filter(o => o.typeId == '0')
            //   this.$store.commit('generator/UPDATE_SUB_TABLE', subTable)
            //   this.$store.commit('generator/SET_TABLE', true)
            //   this.$store.commit('generator/UPDATE_FORMITEM_LIST', this.mainTableFields)
            //   this.activeStep += 1
            // }
            //   if (!this.exist()) return
            // let subTable = this.tables.filter(o => o.typeId == '0')
            //低代码
            if (this.dataForm.modeType === 1) {
              let subTable = [{ table: this.columnData.dbLinkId, fields: this.tables }]
              this.$store.commit('generator/UPDATE_SUB_TABLE', subTable)
              this.$store.commit('generator/SET_TABLE', true)
              this.$store.commit('generator/UPDATE_FORMITEM_LIST', this.mainTableFields)
            }
            this.$store.commit('generator/UPDATE_DELETECUBE_LIST', [])
            this.activeStep += 1
          }
        })
      } else if (this.activeStep == 1) {
        this.$refs['generator']
          .getData()
          .then((res) => {
            // // 当存在子表单时 要按照规则讲主子表数据格式化
            // res.formData.fields.forEach((i,k)=>{
            //     if (i.__config__.jnpfKey === 'table' && i.__config__.children && i.__config__.children.length){
            //       i.__config__.children.forEach((o,z)=>{
            //         o.fatherBoxConfig = deepClone(i.__config__)
            //         o.fatherActionText = i.actionText
            //         o.__fathervModel__ = i.__vModel__
            //       })
            //       res.formData.fields = res.formData.fields.concat(i.__config__.children)
            //     }
            // })
            // res.formData.fields = res.formData.fields.filter((item,k)=> item.__config__.jnpfKey !== 'table')

            this.formData = res.formData
            this.relationData = res.relationData
            this.logicData = res.logicData
            this.activeStep += 1
            // this.loading = true
            // setTimeout( ()=>{
            //   this.loading = false
            // }, 2000 )
          })
          .catch((err) => {
            err.msg && this.$message.warning(err.msg)
          })
      } else {
        this.$refs['columnDesign']
          .getData()
          .then((res) => {
            this.columnData = res.columnData
            this.activeStep += 1
          })
          .catch((err) => {
            err.msg && this.$message.warning(err.msg)
          })
      }
    },
    getComponent() {
      const webType = this.dataForm.webType || 2
      let component = 'columnDesign'
      if (webType == 1) {
        component = 'generator'
      } else if (webType == 3) {
        component = 'process'
      } else {
        component = 'columnDesign'
      }
      return component
    },
    getData() {
      return new Promise((resolve, reject) => {
        if (!this.columnData.columnList.length) reject({ msg: '列表字段不允许为空', target: 2 })
        if (this.columnData.type == 2) {
          this.columnData.treeList.forEach((item) => {
            if (item.treeDataSource === 'dictionary' && !item.treeDictionary) reject({ msg: '请选择数据字典', target: 2 })
            if (item.treeDataSource === 'api') {
              if (!item.treePropsValue) reject({ msg: '请输入主键字段', target: 2 })
              if (!item.treePropsLabel) reject({ msg: '请输入显示字段', target: 2 })
              if (!item.treePropsChildren) reject({ msg: '请输入子级字段', target: 2 })
            }
            if (!item.treeRelation) reject({ msg: '请选择关联字段', target: 2 })
          })
        }
        if (this.columnData.type == 3) {
          if (!this.columnData.groupField) reject({ msg: '请选择分组字段', target: 2 })
        }
        resolve({ columnData: this.columnData, target: 2 })
      })
    },
    addColumn() {
      // return false
      this.isAddColumn = true
      const joinFields = this.columnData.joinFields
      if (!joinFields) {
        this.cubeResult = {
          sourceid: this.columnData.dbSourceId,
          tableName: this.columnData.primaryTableName
        }
      } else {
        this.cubeResult = {
          columnList: joinFields.columnList,
          isEdit: 1,
          ...joinFields.cubeData
        }
      }
    },
    async onSubmit(e) {
      this.columnData.joinFields = e
      const linksJoin = this.columnData.joinFields.cubeData.linksJoin
      const joinFieldsColumnList = this.columnData.joinFields.columnList.filter((i) => !i.hiddenStatus)
      const linksJoinParse = JSON.parse(linksJoin)
      let cubeField = await cubeFieldList({ cubeDataId: this.columnData.dbLinkId })
      cubeField = cubeField.data.data
      const linksJoinParsee = linksJoinParse.map((item) => {
        return {
          tableName: item.target,
          // 小写
          joinType: item.joinType,
          tableColumns: joinFieldsColumnList
            .filter((o) => o.tableName === item.target)
            .map((o) => {
              return {
                columnName: o.columnName,
                columnTitle: o.columnTitle
              }
            }),
          joinColumns: item.joinKeys.map((o) => {
            return {
              masterColumnId: cubeField.find((c) => c.columnName === o.sourceKey).id,
              joinColumnName: o.targetKey
            }
          })
        }
      })
      this.columnData.associationTable = linksJoinParsee
      const list = []
      // this.columnData.columnList = this.columnData.columnList.filter((v) => !v.config.isJoin)
      linksJoinParse.forEach((item) => {
        joinFieldsColumnList
          .filter((v) => v.tableName === item.target)
          .forEach((v) => {
            const old = JSON.parse(JSON.stringify(v))
            const field = `${item.target}_${v.columnName}`
            v.id = field
            v.__type__ = 'join'
            v.columnName = field
            let data = {
              ...v,
              __config__: {
                label: v.columnTitle,
                jnpfKey: v.columnName,
                isJoin: true,
                associatedFrom: {}
              },
              __vModelName__: field,
              __vModel__: field,
              label: v.columnTitle,
              title: v.columnTitle,
              prop: field,
              field: field,
              align: 'left',
              sortable: true,
              showSummary: false,
              width: 0,
              children: [],
              visible: false,
              config: {
                associatedFrom: {},
                isJoin: true,
                ...old
              }
            }
            list.push(data)
          })
      })
      // this.columnData.columnList = this.columnData.columnList.concat(list)
      this.columnData.joinList = list
      this.mainTableFields = [...this.mainTableFields.filter((v) => !v.config), ...list]
    }
  }
}
