import { CreateSerialnumber, getCateList, getVisualDevInfo, NOCreate, Update } from '@/api/onlineDev/visualDev'
import { categoryList as cubeCategoryList, cubeList, reportdatasourceList, temporarySubmit } from '@/api/workFlow/FlowEngine'
import commonMixin from '@/mixins/zeroCodegenerator/common'
import { deepClone } from '@/utils'
import { saveDrawingList } from '@/components/Generator/utils/db'

export default {
  mixins: [commonMixin],
  data() {
    return {
      visible: false,
      loading: false,
      activeStep: 0,
      dataForm: {
        id: '',
        fullName: '',
        enCode: '',
        type: 1,
        webType: 2,
        modeType: 2,
        dbLinkId: '',
        secondaryDbLinkId: [],
        dbSourceId: '',
        state: 1,
        webScene: 'PC',
        category: '',
        description: '',
        tables: ''
      },
      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: 2,
      tables: [],
      formVisible: false,
      btnLoading: false,
      formData: null,
      relationData: [],
      logicData: [],
      columnData: null,
      flowTemplateJson: null,
      categoryList: [],
      dbOptions: [],
      mainTableFields: [],
      relationTable: '',
      datasourceList: [],
      cubeList: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.getDataList()
    })
  },
  methods: {
    goTop() {
      this.closeDialog(true)
      // window.open(this.define.HashUrl + 'workflow/webDesign','_self')
    },
    init(id, type, webType) {
      getCateList().then((res) => {
        this.categoryList = res.data.data
      })
      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)
              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.flowTemplateJson = this.dataForm.flowTemplateJson && JSON.parse(this.dataForm.flowTemplateJson)
              this.tables = (this.dataForm.tables && JSON.parse(this.dataForm.tables)) || []
              // this.updateFields()
              this.loading = false
              this.dataForm.dbLinkId = Number(res.data.data.dbLinkId)
              this.dataForm.dbSourceId = Number(res.data.data.dbSourceId)
              this.dataForm.modeType = Number(res.data.data.modeType)
              this.$nextTick(() => {
                this.onDbChange(this.dataForm.dbLinkId)
              })
            })
            .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 || 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)
      })
    },
    getDataList() {
      reportdatasourceList().then((res) => {
        this.datasourceList = res.data.data
      })
    },
    dataFormSubmit() {
      const component = this.getComponent()
      this.$refs[component]
        .getData()
        .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 {
            console.log(this.formData)
            this.setFormDataFiled()
            this.columnData = res.columnData
          }
          this.dataForm.secondaryTable = JSON.stringify(this.mainTableFields)
          this.dataForm.tables = 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)
          const formMethod = this.dataForm.id ? Update : NOCreate
          this.dataForm.id = this.columnData.modelId
          this.dataForm.secondaryDbLinkId = JSON.stringify(this.dataForm.secondaryDbLinkId)
          formMethod(this.dataForm)
            .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 {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.closeDialog(true)
                  }
                })
              }
            })
            .catch(() => {
              this.btnLoading = false
            })
        })
        .catch((err) => {
          err.msg && this.$message.warning(err.msg)
        })
    },
    CreateSerial(obj, msg) {
      CreateSerialnumber(obj).then(() => {
        this.$message({
          message: msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.closeDialog(true)
          }
        })
      })
    },
    next() {
      if (this.activeStep < 1) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            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.__fathervModelName__ = 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
            //零代码
            if (!this.dataForm.id && this.dataForm.modeType === 2) {
              this.getZeroCodeFun()
            } else {
              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)
          })
      }
    },
    getZeroCodeFun() {
      // 主表 不在子表单内的组件
      let columnList = this.formData.fields
        .map((i) => {
          if (!i.fatherBoxConfig) {
            return {
              name: i.__vModelName__,
              type: i.__config__.viewDataType,
              comment: i.__config__.label
            }
          }
        })
        .filter((l) => l !== undefined)
      let faList = {
        tableComment: 'zeroCode-' + this.dataForm.fullName,
        columnList: columnList
      }
      //获取子表
      let sonColumnList = this.formData.fields
        .map((i) => {
          if (i.fatherBoxConfig) {
            return i.fatherBoxConfig
          }
        })
        .filter((l) => l !== undefined)
      let sonList = []
      if (sonColumnList && sonColumnList.length) {
        //保留唯一子表
        let NewList = this.getfilterList(sonColumnList, 'renderKey')
        sonList = NewList.map((item) => {
          let childrenList = item.children.map((i) => {
            return {
              name: i.__vModelName__,
              type: i.__config__.viewDataType,
              comment: i.__config__.label
            }
          })
          return {
            tableComment: 'zeroCode-' + this.dataForm.fullName + '-' + item.label,
            columnList: [{ name: 'FOREIGN_KEY', type: 'BIGINT', comment: '外键' }, ...childrenList]
          }
        })
      }
      let data = []
      if (sonList && sonList.length) {
        data = [faList].concat(sonList)
      } else {
        data = [faList]
      }
      let submitData = {
        datasourceId: this.dataForm.dbSourceId,
        tableList: data
      }
      this.tables = []
      this.mainTableFields = []
      this.loading = true
      temporarySubmit(submitData).then((res) => {
        // this.dataForm.dbLinkId = res.data.data.id
        this.dataForm.dbLinkId = res.data.data.master.id
        this.dataForm.secondaryDbLinkId = res.data.data.slaves.map((i) => {
          return i.id
        })
        if (this.dataForm.dbLinkId) {
          this.zOnDbChange(this.dataForm.dbLinkId)
        }
        if (this.dataForm.secondaryDbLinkId.length) {
          this.onDbChange([this.dataForm.dbLinkId, ...this.dataForm.secondaryDbLinkId])
        }
      })
    },
    getmainTableList(index) {
      // let subTable = [{table:this.columnData.dbLinkId,fields:this.tables}]
      // this.$store.commit('generator/UPDATE_SUB_TABLE', subTable)
      // this.$store.commit('generator/UPDATE_FORMITEM_LIST', this.mainTableFields)
      if (!this.dataForm.id) {
        this.setDrawListVmodel(this.mainTableFields)
      }
    },
    setFormDataFiled() {
      let inputList = this.formData.fields
      let _this = this
      inputList.forEach((item, index) => {
        let fatherBoxConfig = item.fatherBoxConfig
        if (fatherBoxConfig && fatherBoxConfig.children.length) {
          fatherBoxConfig.children.forEach((i, k) => {
            let aa = inputList.find((o) => o.__vModelName__ === i.__vModelName__)
            if (aa) {
              _this.$set(i, '__vModel__', aa.__vModel__)
            }
          })
        }
      })
    },
    setDrawListVmodel(mainTableFields) {
      let inputList = this.formData.fields
      let _this = this
      function getList(data) {
        data.forEach((item, index) => {
          if (Array.isArray(item) && item.length) {
            getList(item)
          } else {
            //寻找相近的类型生成表单组件
            inputList.forEach((element, key) => {
              if (item.columnName === element.__vModelName__) {
                _this.$set(element, '__vModel__', item.id)
                if (element.fatherBoxConfig && element.__fathervModelName__) {
                  element.__fathervModel__ = item.cubeDataId
                }
              }
            })
          }
        })
      }
      getList(mainTableFields)
      this.$nextTick(() => {
        this.setFormFields(inputList)
      })
    },
    setFormFields(inputList) {
      this.$nextTick(async () => {
        await saveDrawingList(inputList)
        this.activeStep = 2
      })
    },
    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
    }
  }
}
