<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
    >
      <el-form-item label="考核规则名称" prop="ruleName">
        <el-input
          v-model="dataForm.ruleName"
          placeholder="考核规则名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="考核规则编码" prop="ruleCode">
        <el-input
          v-model="dataForm.ruleCode"
          placeholder="考核规则编码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="规则生成方式" prop="ruleMode">
        <el-select v-model="dataForm.ruleMode" placeholder="规则生成方式" @change="handleRuleMode(dataForm.ruleMode)">
          <el-option
            v-for="item in ruleModeList"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="引用" prop="referenceId" v-if="dataForm.ruleMode === '0'">
        <el-select v-model="dataForm.referenceId" clearable placeholder="引用" @change="handlereference(dataForm.referenceId)">
          <el-option
            v-for="item in kpiFormulaList"
            :key="item.id"
            :label="item.formulaName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考核周期" prop="kpiCycle">
        <el-select v-model="dataForm.kpiCycle" placeholder="考核周期">
          <el-option
            v-for="item in kpiCycleList"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入参" prop="metaDataCode" v-if="dataForm.ruleMode === '0'">
        <el-select
          v-model="dataForm.metaDataCode"
          filterable
          clearable
          placeholder="入参"
        >
          <el-option
            v-for="item in metaDataCodeList"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
        &nbsp; &nbsp;
        <el-button type="primary" @click="addRuleParam(dataForm.metaDataCode)">添加</el-button>
      </el-form-item>
      <el-table :data="dataForm.ruleParamList" v-if="dataForm.ruleMode === '0' && dataForm.ruleParamList &&dataForm.ruleParamList.length>0" border>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="id" label="参数表主键" v-if="false"></el-table-column>
        <el-table-column prop="metaDataCode" label="参数名称" :formatter="showMetaDataCodeFormatter"> </el-table-column>
        <el-table-column prop="sort" label="排序">
          <template slot-scope="scope">
              <el-input-number v-model="scope.row.sort"
                         controls-position="right"
                         :min="1" :max="paramAmount">
              </el-input-number>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button  @click="handleRemoveClick(scope.$index,dataForm.ruleParamList)" type="text" size="small">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
      ruleModeList: [],
      kpiCycleList: [],
      kpiFormulaList: [],
      metaDataCodeList: [],
      paramAmount: 100, // 公式参数数量
      dataForm: {
        id: '',
        ruleName: '',
        ruleCode: '',
        ruleMode: '',
        referenceId: '',
        kpiCycle: '',
        metaDataCode: '',
        ruleParamList: []
      }
    }
  },
  computed: {
    dataRule () {
      return {
        ruleName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        ruleCode: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        ruleMode: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        referenceId: [
          {
            required: false,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        kpiCycle: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        ruleParam: [
          {
            required: false,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRuleModeList()
    this.getKpiCycleList()
    this.getKpiFormulaList()
    this.getMetaDataCodeList()
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http
        .get(`/kpi/kpirule/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
        })
        .catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs['dataForm'].validate(valid => {
          if (!valid) {
            return false
          }
          this.$http[!this.dataForm.id ? 'post' : 'put'](
            '/kpi/kpirule/saveOrUpdate/',
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            })
            .catch(() => {})
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
    // 获取绩效考核规则生成方式
    getRuleModeList () {
      this.$http
        .get(`/sys/dict/listSimple/rule_mode`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.ruleModeList = res.data
        })
        .catch(() => {})
    },
    // 获取绩效考核周期下拉框集合
    getKpiCycleList () {
      this.$http
        .get(`/sys/dict/listSimple/kpi_cycle`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.kpiCycleList = res.data
        })
        .catch(() => {})
    },
    // 获取绩效考核公式列表
    getKpiFormulaList () {
      this.$http
        .get(`/kpi/kpiformula/getKpiFormulaList`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.kpiFormulaList = res.data
        })
        .catch(() => {})
    },
    // 获取元数据编码字典表
    getMetaDataCodeList () {
      this.$http
        .get(`/sys/dict/listSimple/meta_data_code`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.metaDataCodeList = res.data
        })
        .catch(() => {})
    },
    // 转换绩效考核元数据编码
    showMetaDataCodeFormatter: function (row, column) {
      if (row.metaDataCode) {
        let dict = this.metaDataCodeList.filter(item => item.dictValue === row.metaDataCode)[0]
        if (dict) {
          return dict.dictName
        }
      }
      return ''
    },
    // 删除参数
    handleRemoveClick (index, rows) {
      console.log(index)
      rows.splice(index, 1)
    },
    // 新增参数
    addRuleParam (metaDataCode) {
      // console.log('添加按下')
      this.handlereference(this.dataForm.referenceId)
      if (this.dataForm.ruleParamList.length === this.paramAmount) {
        return alert('参数数量不能大于公式定义参数个数')
      }
      const temp = {
        metaDataCode: metaDataCode,
        sort: this.dataForm.ruleParamList.length + 1
      }
      this.dataForm.ruleParamList.push(temp)
      this.dataForm.metaDataCode = ''
    },
    // 规则生成方式(0-元公式，1-手工打分，2-投票)
    handleRuleMode (ruleMode) {
      // console.log('规则生成方式=' + ruleMode)
      if (ruleMode === '0') {
        this.dataForm.metaDataCode = '' // 之前选中参数清空
        this.dataForm.ruleParamList = [] // 参数列表清空
        this.dataForm.referenceId = ''// 引用公式id清空
      }
    },
    // 引用公式id
    handlereference (referenceId) {
      // console.log('当前选中的引用公式id=' + referenceId)
      let kpiFormulaArray = this.kpiFormulaList
      for (var i = 0; i < kpiFormulaArray.length; i++) {
        if (kpiFormulaArray[i].id === referenceId) {
          // console.log('引用公式名称=' + kpiFormulaArray[i].formulaName + ';公式参数数量=' + kpiFormulaArray[i].paramAmount)
          this.paramAmount = kpiFormulaArray[i].paramAmount
        }
      }
    }
  }
}
</script>
