<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :loading="btnLoading" @click="doSave"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div class="detail-panel form-panel">
      <el-form :model="formData" ref="editCustomWeightsForm" label-width="128px">
        <el-form-item label="字段名称：" prop="name" :verify="['NotNull']">
          <el-select v-model="formData.name" placeholder="请选择字段名称" style="width:auto">
            <el-option v-for="data in fieldList" :key="data.key" :label="data.value" :value="data.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字段值：" prop="fieldValue" :verify="['NotNull']">
          <el-input v-model="formData.fieldValue"></el-input>
        </el-form-item>
        <el-form-item label="自定义权重：" prop="weights" :verify="['NotNull','Number']">
          <el-input v-model="formData.weights"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" v-show="false">
          <el-input v-model="formData.enabled" value="Y"></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      btnLoading: false,
      dialogDataloading: false,
      formData: {
        ID: 0,
        name: '',
        fieldValue: '',
        weights: ''
      }, // 当前自定义权重临时数据
      emptyFormData: {},
      fieldList: [] // 字段名称
    }
  },
  watch: {
    ID: 'init'
  },
  methods: {
    init() {
      if (this.ID && this.ID !== 'new') {
        this.loadData()
      } else {
        this.clearForm()
      }
      this.btnLoading = false
      !this.fieldList.length && this.loadFieldList()
    },

    async loadData() {
      let res = await axios.get(`/ui/customweights/${this.ID}`)
      res = res.data
      res.status === 1 && Object.assign(this.formData, res.data)
    },

    clearForm() {
      Object.assign(this.formData, this.emptyFormData)
    },

    validateWeight() {
      let weights = this.formData.weights
      if (!weights) {
        this.Dialog('请输入权重 ！')
        return false
      }

      if (!/(^-?\d+\.?\d+$)|(^-?\d+$)/.test(weights)) {
        this.Dialog('权重只能为数值 ！')
        return false
      }

      weights = weights - 0
      if (weights < Number.MIN_SAFE_INTEGER || weights > Number.MAX_SAFE_INTEGER) {
        this.Dialog(`权重值超出安全数值范围(${Number.MIN_SAFE_INTEGER} - ${Number.MAX_SAFE_INTEGER}) ！`)
        return false
      }
      return true
    },

    // 保存自定义权重事件
    async doSave() {
      try {
        await util.validateForm(this.$refs['editCustomWeightsForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }

      if (this.validateWeight() === false) {
        return
      }
      this.formData.enabled = !this.formData.enabled ? 'Y' : this.formData.enabled

      this.btnLoading = true
      let res
      if (!this.ID || this.ID === 'new') {
        res = await axios.post('/ui/customweights', this.formData).catch(e => {
        // console.log(e)
        })
      } else {
        if (!this.formData.ID) {
          this.MsgPop('传入id错误 ！', 'error')
          this.btnLoading = false
          return
        }
        res = await axios.put(`/ui/customweights/${this.formData.ID}`, this.formData).catch(e => {
        // console.log(e)
        })
      }

      this.btnLoading = false
      if (!res) {
        this.MsgPop('请求错误', 'error')
        return
      }

      let data = res.data
      if (data.status === 1) {
        util.showResponseMessage(data)
        this.$emit('success')
      } else {
        this.Dialog(data.message)
      }
    },

    // 加载选择内容Dialog中内容类型字段数据
    async loadFieldList() {
      this.dialogDataloading = true
      let res = await axios.get('/ui/customweights/fieldlist')
      let data = res.data
      this.fieldList = data.status === 1 ? data.data : []
      this.dialogDataloading = false
    },

    // 消息Dialog封装
    Dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },

    // 消息显示封装
    MsgPop(msg, type) {
      if (!type) {
        this.$message(msg)
        return
      }
      this.$message({
        message: msg,
        type: type
      })
    }
  },
  created() {
    Object.assign(this.emptyFormData, this.formData)
    this.init()
  }
}
</script>
