import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'
import multipleSelectTree from '@/components/multiple-select-tree.vue'
import {editStatusOptions, enableStatusOptions} from '@/utils/public-options'
import {toTree} from '@/utils/util'
import {editStatusForCompute, editStatusForInput} from '../../../../utils/public-options'

/**
 * KPI创建
 *
 *  version = "1.0.0";
 *  author = "liucui";
 *  email = "liu.cui@data-u.com";
 * */
export default {
  name: 'KPIDetail',
  components: {
    breadcrumbComponent, multipleSelectTree
  },
  mixins: [routerUserMenu],
  data () {
    return {
      // 函数对象
      kpiFunctionOptions: [],
      // 关联字段互斥ID
      mutexTableId: '',
      // 预览
      visible: false,
      previewData: '',
      // 数据对象 按表分组的字段
      colGroup: {},
      // 规则字段
      colOptions: [],
      // 主题树
      tree: [],
      // KPI类型
      typeOptions: [],
      // 符号
      signOptions: [],
      // 规则类型
      ruleTypeOptions: [],
      // 数据库
      databaseOptions: [],
      // 表设置数据表
      tableOptions: [],
      // 定义字段
      columnOptions: [],
      // 计算关联表内容，通过字段设置动态添加的
      relTableOptions: [],
      // 编辑状态、启用状态的对应关系
      formatterOptions: {
        'editStatusShow': editStatusOptions,
        'editStatusForCompute': editStatusForCompute,
        'editStatusForInput': editStatusForInput,
        'enableStatusShow': enableStatusOptions
      },
      // 组件id（修改和查看）
      id: false,
      // 新建对象
      formInfo: {
        // 唯一标识
        id: '',
        // KPI名称
        name: '',
        // KPI类型ID
        type: '',
        // 主题编码
        topicCodes: [],
        // KPI规则/数据类型ID
        ruleTypeId: '',
        // KPI编码
        kpiCode: '',
        // 单位
        unit: '',
        // KPI描述
        description: '',
        // 启用状态
        enableStatus: '',
        // 编辑状态
        editStatus: '',
        // 数据库ID
        databaseId: '',
        // 定义和输入类型对象
        definedTypeInfo: {
          // 表ID
          tableId: '',
          // 字段ID
          columnId: ''
        },
        // 计算类型对象
        computedTypeInfo: {
          // 是否跨表
          acrossTable: 'yes',
          // 字段设置
          contents: [{tableId: '', columnId: [], options: []}, {tableId: '', columnId: [], options: []}],
          // 关联字段设置
          relOptions: [{
            tableId: '',
            columnId: '',
            relTableId: '',
            relColumnId: '',
            leftOptions: [],
            rightOptions: [],
            mutexTableId: '',
            mutexRelTableId: ''
          }],
          // 规则设置
          ruleOptions: [{leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'false'}]
        },
        // 函数类型提交对象数组
        functionKpiColumns: [{
          // 表ID
          tableId: '',
          // 字段ID
          columnId: ''
        }],
        functionId: '',
        functionDesc: '',
        columnNum: 0,
        tableId: '',
        chooseColumnIds: []
      },

      // 页面打开类型，false可编辑 true不可编辑
      readStatus: false,
      // 0新建 2修改
      dialogState: 0
    }
  },
  computed: {
    // 组件设置是否只读
    readonly: {
      // getter
      get: function () {
        return this.readStatus
      },
      // setter
      set: function (newValue) {}
    },
    /* 转换数据格式 */
    treeData: {
      get: function () {
        let tree = this.tree
        // 线性数组转成树后渲染
        let defaultProps = {
          id: 'code',
          parent_id: 'pcode',
          label: 'name'
        }
        let newTree = toTree(tree, '0', defaultProps)
        return newTree
      }
    },
    limitNum: {
      // getter
      get: function () {
        return this.formInfo.columnNum
      },
      // setter
      set: function (newValue) {}
    }
  },
  mounted () {
    // 加载函数下拉列表
    this.getKpiFunctionOptions()
    // 获取KPI类型
    this.getKpiTypeOptions()
    // 符号
    this.getSignOptions()
    // 规则类型
    this.getRuleTypeOptions()
    // 数据库
    this.getDatabaseOptions()
    // 获得主题树
    this.getTree()
    // 加载table
    this.getTableOptions()
    // 加载表
    this.getColumnOptions()
    // 初始化
    this.init()
    this.formInfo.chooseColumnIds = []
  },
  methods: {
    getKpiFunctionOptions () {
      this.$api.kpiFunction.list().then(
        res => {
          if (res.code == 1) {
            this.kpiFunctionOptions = res.data
          }
        })
    },
    init () {
      // 获取url参数
      let params = this.$route.params
      if (params.hasOwnProperty('readonly')) {
        this.readStatus = true
      }
      if (params.hasOwnProperty('id')) {
        // 如果有id，则加载组件对象
        this.id = params.id
        // 如果有id，则获取id对应的部门信息赋值给formInfo
        this.getDetail()
      }
      // 根据页面参数设置当前页面类型
    },
    /* 获取整个树 */
    getTree () {
      this.$api.kpiTopic.topicTtree().then(res => {
        if (res.code == 1) {
          this.tree = res.data
        }
      })
    },
    /* 获取KPI类型列表 */
    getKpiTypeOptions () {
      this.$api.kpiCommon.listTypes().then(
        res => {
          if (res.code == 1) {
            this.typeOptions = res.data
          }
        })
    },
    /* 获取符号列表 */
    getSignOptions () {
      this.$api.kpiCommon.listSigns().then(
        res => {
          if (res.code == 1) {
            this.signOptions = res.data
          }
        })
    },
    /* 获取规则类型列表 */
    getRuleTypeOptions () {
      let params = { kpiType: this.formInfo.type }
      this.$api.kpiCommon.listRuleTypesByKpiType(params).then(
        res => {
          if (res.code == 1) {
            this.ruleTypeOptions = res.data
          }
        })
    },
    /* 获取数据库列表 */
    getDatabaseOptions () {
      this.$api.kpiConfig.listMdmDatabases().then(
        res => {
          if (res.code == 1) {
            this.databaseOptions = res.data
          }
        })
    },
    /* 获取表信息 */
    getTableOptions (obj) {
      let params = { databaseId: obj }
      this.$api.kpiConfig.listMdmTablesByDatabase(params).then(
        res => {
          if (res.code == 1) {
            this.tableOptions = res.data
          }
        }
      )
    },
    /* 获取字段信息 */
    getColumnOptions (obj) {
      let params = {tableId: obj}
      this.$api.kpiConfig.listMdmColumnsByTable(params).then(
        res => {
          if (res.code == 1) {
            this.columnOptions = res.data
          }
        }
      )
    },
    /* 函数table改变事件 */
    kpiTableChange (obj) {
      this.getColumnOptions(obj.tableId)
    },
    /* KPI函数选择事件 */
    kpiFunctionChange (obj, event) {
      let id = event
      let options = this.kpiFunctionOptions
      for (let i = 0; i < options.length; i++) {
        if (id === options[i].id) {
          this.formInfo.functionDesc = options[i].functionDesc
          this.formInfo.columnNum = options[i].columnNum
          break
        }
      }
    },
    /* 加载字段信息按表分组(主要用于详情回显的时候) */
    getColumnsGroupByTable (obj) {
      let params = {databaseId: obj}
      this.$api.kpiConfig.listMdmColumnsGroupByTable(params).then(
        res => {
          if (res.code == 1) {
            this.colGroup = res.data
            // 1.初始化先字段设置所有完成才能设置关联表、关联字段，否则有问题
            let contents = this.formInfo.computedTypeInfo.contents
            for (let i = 0; i < contents.length; i++) {
              this.initSettingTableChange(i, contents[i].tableId)
            }
            // 2.关联表选项
            this.relTableOptions = []
            for (let i = 0; i < contents.length; i++) {
              let tableId = contents[i].tableId
              for (let j = 0; j < this.tableOptions.length; j++) {
                if (tableId == this.tableOptions[j].id) {
                  let table = this.tableOptions[j]
                  this.relTableOptions.push(table)
                }
              }
            }
            // 3.加载关联字段
            let relOptions = this.formInfo.computedTypeInfo.relOptions
            for (let i = 0; i < relOptions.length; i++) {
              this.leftRelTableChange(i, relOptions[i].tableId)
              this.rightRelTableChange(i, relOptions[i].relTableId)
            }

            // 4.加载规则字段
            this.settingColumnChange()
          }
        }
      )
    },
    /* 选择类型 */
    typeChange (obj) {
      if (obj.type === 2 || obj.type === 4) {
        this.formInfo.editStatus = 0
      }
      if (obj.type === 3) {
        this.formInfo.editStatus = 1
      }
      this.getRuleTypeOptions()
    },
    /* 定义/计算类型->选择数据库 */
    databaseChange (obj) {
      this.getTableOptions(obj.databaseId)
    },
    /* 定义类型选择表 */
    tableChange (obj) {
      this.getColumnOptions(obj.definedTypeInfo.tableId)
    },
    /* 计算类型数据库查询字段与表关系 */
    computedDatabaseChange (obj) {
      this.getTableOptions(obj.databaseId)
      this.getColumnsGroupByTable(obj.databaseId)
    },
    /* 计算类型 是否跨表 */
    acrossTableChange (obj) {
      let contents = this.formInfo.computedTypeInfo.contents
      if (obj === 'yes') {
        contents.push({tableId: '', columnId: [], options: []})
      } else {
        contents.pop({tableId: '', columnId: [], options: []})
      }
    },
    initSettingTableChange (index, event) {
      // 1.字段设置字段
      let tableId = event
      this.mutexTableId = event
      for (let i = 0; i < this.colGroup.length; i++) {
        if (tableId == this.colGroup[i].tableId) {
          let options = this.colGroup[i].columns
          this.formInfo.computedTypeInfo.contents[index].options = options
        }
      }
    },
    /* 字段设置表change事件 */
    settingTableChange (index, event) {
      // 清空下列的值
      if (this.formInfo.computedTypeInfo.acrossTable == 'no') {
        this.formInfo.computedTypeInfo.contents[index].columnId = []
      } else {
        if (index === 0) {
          this.formInfo.computedTypeInfo.contents[index].columnId = []
          this.formInfo.computedTypeInfo.contents[index + 1].columnId = []
        } else {
          this.formInfo.computedTypeInfo.contents[index].columnId = []
        }
        // 互斥操作
        this.mutexTableId = event
      }
      this.formInfo.computedTypeInfo.relOptions = [{tableId: '', columnId: '', relTableId: '', relColumnId: '', leftOptions: [], rightOptions: []}]
      this.formInfo.computedTypeInfo.ruleOptions = [{leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'false'}]
      // 1.字段设置字段
      let tableId = event
      for (let i = 0; i < this.colGroup.length; i++) {
        if (tableId == this.colGroup[i].tableId) {
          let options = this.colGroup[i].columns
          this.formInfo.computedTypeInfo.contents[index].options = options
        }
      }
      // 2.设置关联表
      let contents = this.formInfo.computedTypeInfo.contents
      this.relTableOptions = []
      for (let i = 0; i < contents.length; i++) {
        let tableId = contents[i].tableId
        for (let j = 0; j < this.tableOptions.length; j++) {
          if (tableId == this.tableOptions[j].id) {
            let table = this.tableOptions[j]
            this.relTableOptions.push(table)
          }
        }
      }
      // 3.关联字段
      let relOptions = this.formInfo.computedTypeInfo.relOptions
      for (let i = 0; i < relOptions.length; i++) {
        this.leftRelTableChange(i, relOptions[i].tableId)
        this.rightRelTableChange(i, relOptions[i].relTableId)
      }
      // 加载规则字段
      this.settingColumnChange()
    },
    /* 字段设置表更改，规则字段列表改变 */
    settingColumnChange () {
      this.colOptions = []
      let contents = this.formInfo.computedTypeInfo.contents
      for (let i = 0; i < contents.length; i++) {
        let columnId = contents[i].columnId
        let options = contents[i].options
        for (let j = 0; j < options.length; j++) {
          for (let k = 0; k < columnId.length; k++) {
            if (options[j].id == columnId[k]) {
              let option = options[j]
              this.colOptions.push(option)
            }
          }
        }
      }
    },
    /* 关联表设置选择表 */
    leftRelTableChange (index, event) {
      let tableId = event
      this.formInfo.computedTypeInfo.relOptions[index].mutexRelTableId = event
      for (let i = 0; i < this.colGroup.length; i++) {
        if (tableId == this.colGroup[i].tableId) {
          let options = this.colGroup[i].columns
          this.formInfo.computedTypeInfo.relOptions[index].leftOptions = options
          break
        }
      }
    },
    /* 字段设置选择表 */
    rightRelTableChange (index, event) {
      let tableId = event
      this.formInfo.computedTypeInfo.relOptions[index].mutexTableId = event
      for (let i = 0; i < this.colGroup.length; i++) {
        if (tableId == this.colGroup[i].tableId) {
          let options = this.colGroup[i].columns
          this.formInfo.computedTypeInfo.relOptions[index].rightOptions = options
          break
        }
      }
    },
    /* 关键字段 减操作 */
    relMinus (index, event) {
      if (this.formInfo.computedTypeInfo.relOptions.length > 1) {
        this.formInfo.computedTypeInfo.relOptions.splice(index, 1)
      }
    },
    /* 关联字段 加操作 */
    relPlus () {
      let param = {tableId: '', columnId: '', relTableId: '', relColumnId: ''}
      this.formInfo.computedTypeInfo.relOptions.push(param)
    },
    /* 规则减操作 */
    ruleMinus (index, event) {
      if (this.formInfo.computedTypeInfo.ruleOptions.length > 1) {
        this.formInfo.computedTypeInfo.ruleOptions.splice(index, 1)
      }
    },
    /* 规则加操作 */
    rulePlus () {
      let param = { leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'false' }
      this.formInfo.computedTypeInfo.ruleOptions.push(param)
    },
    /* 添加常量 */
    ruleConstant () {
      let param = {leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'true'}
      this.formInfo.computedTypeInfo.ruleOptions.push(param)
      let length = this.formInfo.computedTypeInfo.ruleOptions.length
      this.formInfo.computedTypeInfo.ruleOptions[length - 2].rightSign = ''
    },
    /* 查询详情 */
    getDetail (obj) {
      if (this.readStatus === true) {
        this.dialogState = 1
      } else {
        this.dialogState = 2
      }
      let _this = this
      let params = {id: this.id}
      _this.$api.kpiConfig.getById(params)
        .then(res => {
          if (res.code === '1') {
            _this.$message.success(res.msg)
            console.log('添加chooseColumnIds属性然后赋值，否则无法修改el-select')
            let data = res.data
            this.$set(data, 'chooseColumnIds', [])
            _this.formInfo = data
            // 数据类型列表初始化
            this.getRuleTypeOptions()
            // 定义类型
            if (_this.formInfo.type === 1 || _this.formInfo.type === 3) {
              this.databaseChange(_this.formInfo)
              this.tableChange(_this.formInfo)
              // 在这里给计算类型的属性加上值，否则template v-if和v-for会有问题
              _this.formInfo.computedTypeInfo = {
                acrossTable: 'yes',
                contents: [{tableId: '', columnId: [], options: []}, {tableId: '', columnId: [], options: []}],
                relOptions: [{tableId: '', columnId: '', relTableId: '', relColumnId: '', leftOptions: [], rightOptions: []}],
                ruleOptions: [{leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'false'}]
              }
            }
            // 计算类型
            if (_this.formInfo.type === 2) {
              // 防止修改KPI类型报错
              _this.formInfo.definedTypeInfo = {tableId: '', columnId: ''}
              this.computedDatabaseChange(_this.formInfo)
            }

            // 函数类型
            let arr = []
            if (_this.formInfo.type === 4) {
              let options = _this.formInfo.functionKpiColumns
              for (let i = 0; i < options.length; i++) {
                arr.push(options[i].columnId)
              }
              this.formInfo.chooseColumnIds = arr
              this.formInfo.tableId = options[0].tableId
              this.databaseChange(_this.formInfo)
              this.kpiTableChange(_this.formInfo)
              this.kpiFunctionChange(_this.formInfo, _this.formInfo.functionId)

              // 给定义类型添加默认值
              _this.formInfo.definedTypeInfo = {tableId: '', columnId: ''}
              // 在这里给计算类型的属性加上值，否则template v-if和v-for会有问题
              _this.formInfo.computedTypeInfo = {
                acrossTable: 'yes',
                contents: [{tableId: '', columnId: [], options: []}, {tableId: '', columnId: [], options: []}],
                relOptions: [{tableId: '', columnId: '', relTableId: '', relColumnId: '', leftOptions: [], rightOptions: []}],
                ruleOptions: [{leftSign: '', columnId: '', rightSign: '', constant: '', isConstant: 'false'}]
              }
            }

            _this.$forceUpdate()

            _this.$nextTick(() => {
              _this.$refs.formInfo.clearValidate()
            })
          } else {
            _this.$message.error(res.msg)
          }
        })
    },
    /* 函数对象提交前需要组合 */
    functionHandle () {
      this.formInfo.functionKpiColumns = []
      let options = this.formInfo.chooseColumnIds
      for (let i = 0; i < options.length; i++) {
        let obj = {tableId: this.formInfo.tableId, columnId: options[i]}
        this.formInfo.functionKpiColumns.push(obj)
      }
    },
    /* 提交新增节点 */
    add () {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 转换数据
          if (_this.formInfo.type === 4) {
            this.functionHandle()
          }
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          _this.$api.kpiConfig.save(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false
        }
      })
    },
    /* 更新操作 */
    update () {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 转换数据
          if (_this.formInfo.type === 4) {
            this.functionHandle()
          }
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          _this.$api.kpiConfig.update(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false
        }
      })
    },
    /* 预览功能 */
    preview () {
      this.previewData = ''
      let rules = this.formInfo.computedTypeInfo.ruleOptions
      for (let i = 0; i < rules.length; i++) {
        if (rules[i].isConstant === null || rules[i].isConstant === 'false') {
          let columnName = ''
          for (let j = 0; j < this.colOptions.length; j++) {
            if (rules[i].columnId == this.colOptions[j].id) {
              columnName = this.colOptions[j].columnName
              break
            }
          }
          this.previewData += rules[i].leftSign + columnName + rules[i].rightSign
        } else {
          this.previewData += rules[i].leftSign + rules[i].constant + rules[i].rightSign
        }
      }
      this.$alert(this.previewData, '预览规则')
    },
    paramChange (obj) {
      console.log('12344444444')
      console.log(this.formInfo.chooseColumnIds)
      console.log('12344444444abcdddd')
    },
    /* 返回 */
    goBack () {
      this.$router.go(-1) // 返回上一层
    }
  }
}
