import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'
import tableComponent from '@/components/table.vue'
import Axios from 'axios'

/**
 * 页面组件设置
 *
 *  version = "1.0.0";
 *  author = "徐飞";
 *  email = "xu.fei@data-u.com";
 * */
export default {
  name: 'detail',
  components: {breadcrumbComponent, tableComponent},
  mixins: [routerUserMenu],
  data() {
    return {
      // 组件id（修改和查看）
      id: false,
      // 新建对象
      tableInfo: {
        tableName: '',
        tableComment: '',
        databaseId: '',
        tableDesc: ''
      },
      hiveInfo: {
        hivePartition: '',
        hiveSeparatorRow: '',
        hiveSeparatorColumn: ''
      },
      // 页面打开类型，0：新建，1：复制，2：修改
      dialogState: 0,
      databaseOptions: [],
      detailList: [],
      detailListDrop: [],
      isFloat: false,
      isNullList: [{text: '是', value: 1,disabled:true}, {text: '否', value: 0}],
      isNull: [{text: '可空', value: 1, disabled: true}, {text: '不可空', value: 0}],
      checkIsNull: false,
      typeList: []
    }
  },
  computed: {
    showHive: {
      get: function () {
        let opt = this.databaseOptions.filter((ele) => {
          return ele.id == this.tableInfo.databaseId
        })
        if (opt && opt.length > 0) {
          return opt[0].resourceType == '1'
        } else {
          return false
        }
      },
      set: function (newValue) {
      }
    },
  },
  mounted() {
    // 初始化
    this.init()
  },
  methods: {
    //  如果有id，则获取id对应的部门信息赋值给formInfo
    init() {
      // 获取url参数
      let params = this.$route.params
      this.loadType()
      console.log(params)
      if (params.ifcopy == 0) {
        // 如果有id，则加载组件对象
        this.id = params.id
        this.dialogState = 2
        this.getDetailByEdit()
      } else if (params.ifcopy == 1) {
        this.id = params.id
        this.dialogState = 1
        this.getDetailByCopy()
      } else {
        this.dialogState = 0
        this.listDatabaseOption()
      }
    },
    // 通过编辑进入该页面时实现数据回显
    getDetailByEdit() {
      let _this = this
      this.$api.storage.listDatabaseOption()
        .then(res => {
          if (res.code == '1') {
            _this.databaseOptions = res.data
            _this.$api.storage.getTableInfoById(_this.id)
              .then(res => {
                if (res.code == 1) {
                  _this.tableInfo = res.data
                  _this.$nextTick(() => {
                    _this.$refs.tableInfo.clearValidate()
                  })
                  // let opt = _this.databaseOptions.filter((ele) => {
                  //   return ele.id == _this.tableInfo.databaseId
                  // })
                  // _this.$api.storage.listColumTypeByDatabaseType(opt[0].resourceType)
                  //   .then(res => {
                  //     if (res.code == 1) {
                  //       _this.typeList = res.data
                  _this.$api.storage.listColumsByTableId(_this.id)
                    .then(res => {
                      if (res.code == 1) {
                        _this.detailList = res.data
                      }
                    })
                  // }
                  // })
                }
              })
          }
        })
    },
    // 通过复制进入该页面时实现数据回显
    getDetailByCopy() {
      let detailData = []
      let _this = this
      this.$api.storage.listDatabaseOption()
        .then(res => {
          if (res.code == '1') {
            _this.databaseOptions = res.data
            //  加载字段信息从而选中数据库
            _this.$api.storage.listColumsByTableId(_this.id)
              .then(res => {
                if (res.code == '1') {
                  _this.tableInfo.databaseId = res.data[0].databaseId
                  _this.$nextTick(() => {
                    _this.$refs.tableInfo.clearValidate()
                  })
                  detailData = res.data

                  // let opt = _this.databaseOptions.filter((ele) => {
                  //   return ele.id == _this.tableInfo.databaseId
                  // })
                  // _this.$api.storage.listColumTypeByDatabaseType(opt[0].resourceType)
                  //   .then(res => {
                  //     if (res.code == 1) {
                  //       _this.typeList = res.data
                  _this.detailList = detailData
                  // }
                  // })
                }
              })
          }
        })
    },
    // 加载字段类型
    loadType() {
      // let opt = this.databaseOptions.filter((ele) => {
      //   return ele.id == this.tableInfo.databaseId
      // })
      this.$api.storage.listColumTypeByDatabaseType(2)
        .then(res => {
          if (res.code == 1) {
            this.typeList = res.data
          }
        })
    },
    // 下载模板
    downloadTemplate() {
      location.href = Axios.defaults.baseURL + '/mdm/mdm/storageManage/downloadTemplateColums'
    },
    // 上传文件
    uploadFile(params) {
      console.log(params)
      let form = new FormData()
      form.append('file', params.file)
      form.append('chunk', '0') // 添加form表单中其他数据
      this.$api.storage.loadTemplateColums(form)
        .then(res => {
          if (res.code == 1) {
            this.$message.success("上传成功")
            this.detailList = res.data
          } else {
            this.$message.error("上传失败")
          }
        })
    },
    //获取数据库下拉列表
    listDatabaseOption() {
      this.$api.storage.listDatabaseOption()
        .then(res => {
          if (res.code == '1') {
            this.databaseOptions = res.data
          }
        })
    },

    // 提交保存
    add() {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.tableInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.tableInfo
          for (let list of this.detailList) {
            if (!list.hasOwnProperty('columnUpdateType')) {
              list['columnUpdateType'] = 'modify'
            }
          }
          for (let j=0;j<this.detailList.length;j++){
            if (this.detailList[j].ifPrimary==1&&this.detailList[j].ifNull==1){
              this.$message.error("主键不可为空！")
              return
            }
          }
          params['columns'] = this.detailList
          params['hiveSeparatorColumn'] = _this.hiveInfo.hiveSeparatorColumn
          params['hivePartition'] = _this.hiveInfo.hivePartition
          params['hiveSeparatorRow'] = _this.hiveInfo.hiveSeparatorRow

          _this.$api.storage.createTable(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.go('MetaData')
              }
            })
        } else {
          return false
        }
      })
    },

    // 更新
    update() {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.tableInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.tableInfo
          for (let list of this.detailList) {
            if (!list.hasOwnProperty('columnUpdateType')) {
              list['columnUpdateType'] = 'modify'
            }
          }
          for (let i = 0; i < this.detailListDrop.length; i++) {
            this.detailList.push(this.detailListDrop[i])
          }
          for (let j=0;j<this.detailList.length;j++){
            if (this.detailList[j].ifPrimary==1&&this.detailList[j].ifNull==1){
              this.$message.error("主键不可为空！")
              return
            }
          }
          params['columns'] = this.detailList
          params['hiveSeparatorColumn'] = _this.hiveInfo.hiveSeparatorColumn
          params['hivePartition'] = _this.hiveInfo.hivePartition
          params['hiveSeparatorRow'] = _this.hiveInfo.hiveSeparatorRow
          params['id'] = _this.id
          _this.$api.storage.updateTable(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.go('MetaData')
              }
            })
        } else {
          return false
        }
      })
    },
    //删除行
    deleteRow(scope) {
      if (this.id) {
        if (this.detailList[scope.$index].id) {
          this.detailListDrop.push({
            id: this.detailList[scope.$index].id,
            columnUpdateType: 'drop',
            columnName: this.detailList[scope.$index].columnName
          })
        }
      }
      this.detailList.splice(scope.$index, 1)
    },
    //增加行
    addRow() {
      this.detailList.push({
        columnName: '',
        columnComment: '',
        columnType: '',
        length: 0,
        numericScale: '',
        ifPrimary: '',
        ifNull: '',
        isFloatPoint: '',
        columnUpdateType: 'add'
      })
    },
    //改变字段类型时判断小数位是否被禁止
    changeFloat(scope) {
      let arr = this.typeList.filter(ele => {
        return ele.isFloatPoint == 1
      }).map(ele => {
        return ele.id
      })
      if (arr.indexOf(scope.row.columnType) >= 0) {
        //  这里禁止小数位
        scope.row.isFloatPoint = 1
      } else {
        //  允许
        scope.row.isFloatPoint = 0
      }
    },
  }
}
