<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
             label-width="80px">
      <el-form-item label="目标/指标" v-show="auth.target >= 1" prop="target">
        <el-input :disabled="auth.target<2" v-model="dataForm.target" placeholder="目标/指标"></el-input>
      </el-form-item>
      <el-form-item label="关键结果" v-show="auth.keyResult >= 1 && this.type == 1 " prop="keyResult">
        <div id="keyResultEditorElem" class="editor"></div>
      </el-form-item>
      <el-form-item v-show="auth.checkWeight>=1" label="考核权重" prop="checkWeight">
        <el-input v-model="dataForm.checkWeight" :disabled="auth.checkWeight<2" placeholder="考核权重"></el-input>
      </el-form-item>

      <el-form-item label="考核结果" v-show="auth.checkResult >= 1" prop="checkResult">
        <div id="checkResultEditorElem" class="editor"></div>
      </el-form-item>

      <el-form-item label="业绩排序" v-show="auth.priority >= 1" prop="priority">
        <el-input :disabled="auth.priority < 2 " v-model="dataForm.priority" placeholder="优先级别，数字越大，越在排列在表格前面"></el-input>
      </el-form-item>

      <el-form-item label="上级评分" v-show="auth.superScore >= 1">
        <el-select v-model="dataForm.acquireScore" :disabled="auth.superScore < 2" placeholder="请选择">
          <el-option
            v-for="item in superScoreData"
            :key="item.score"
            :label="item.label"
            :value="item.score"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="得分" prop="acquireScore" v-show="auth.acquireScore == 1">
        <template>
          <div style="color: red" class="conatnt-name">
            <span>{{ acquireScore }}</span>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="评分说明" v-show="auth.scoreComment >= 1" prop="scoreComment">
        <div id="scoreCommentEditorElem" class="editor"></div>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      <el-button type="danger" @click="dataFormDelete()" >删除</el-button>
    </span>
  </el-dialog>
</template>


<script>
import {apiDetailInfo, recorddetailAddOrUpdate, recorddetailDelete, weightCheck, preWeightCheck} from '@/api/api_result'
import E from 'wangeditor'

var Base64 = require('js-base64').Base64

export default {
  data () {
    var validNum = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('数值不能为空'))
      }
      if (!/^(((0)\.([0-9]{1,2}))$)/.test(value)) {
        callback(new Error('请输入大于0小于1的小数'))
      }
      let data = await weightCheck({
        'recordResultId': this.recordResultId,
        'weight': value,
        'type': this.type,
        'id': this.dataForm.id
      })
      if (data && data.code !== 0) {
        callback(new Error(data.msg))
      }
      callback()
    }
    var scoreComment = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('评分不能为空'))
      }
      callback()
    }
    var validPriority = async (rule, value, callback) => {
      if (value !== 0) {
        if (!value) {
          callback(new Error('优先级不能为空'))
        }
      }
      if (!/^(0|[1-9][0-9]*)$/.test(value)) {
        callback(new Error('请输入大于或等于0的整数'))
      }
      callback()
    }
    return {
      visible: false,
      keyResultEditor: null,
      checkResultEditor: null,
      recordResultId: null,
      scoreCommentEditor: null,
      auth: [],
      recordType: 0,
      type: 0,
      superScoreData: [{
        score: 0,
        label: ' '
      }, {
        score: 4,
        label: '4分-卓越'
      }, {
        score: 3.875,
        label: '3.75(+)-优秀'
      }, {
        score: 3.75,
        label: '3.75分-合格'
      }, {
        score: 3.667,
        label: '3.75(-)-优秀'
      }, {
        score: 3.583,
        label: '3.5(+)-合格'
      }, {
        score: 3.583,
        label: '3.5(+)-合格'
      }, {
        score: 3.5,
        label: '3.5分-合格'
      }, {
        score: 3.375,
        label: '3.5(-)-合格'
      }, {
        score: 3.25,
        label: '3.25分-不合格，待改进'
      }
      ],
      dataForm: {
        id: 0,
        target: '',
        keyResult: '',
        checkWeight: 0.15,
        checkResult: '',
        superScore: '',
        acquireScore: '',
        scoreComment: '',
        priority: 0
      },
      dataRule: {
        scoreComment: [
          {required: scoreComment, message: '评分不能为空', trigger: 'blur'}
        ],
        checkWeight: [
          {validator: validNum, required: true, trigger: 'blur'}
        ],
        priority: [
          {validator: validPriority, required: true, trigger: 'blur'}
        ]
      }
    }
  },
  mounted () {

  },
  computed: {
    acquireScore () {
      const score1 = this.superScoreData.filter(i => this.dataForm.acquireScore === i.score)
      return score1.length > 0 ? score1[0].score : 0
    }
  },
  methods: {
    async init (id, type, recordResultId, auth, recordType) {
      this.type = type
      this.recordResultId = recordResultId
      this.auth = auth
      this.recordType = recordType
      this.dataForm.id = id || 0
      let data = await preWeightCheck({
        'recordResultId': this.recordResultId,
        'type': this.type,
        'id': this.dataForm.id
      })
      if (data && data.code !== 0) {
        this.$message({
          message: data.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
          }
        })
        return
      }
      if (this.keyResultEditor !== null) {
        this.keyResultEditor.txt.html('')
      }
      if (this.checkResultEditor !== null) {
        this.checkResultEditor.txt.html('')
      }
      if (this.scoreCommentEditor !== null) {
        this.scoreCommentEditor.txt.html('')
      }
      this.visible = true
      this.$nextTick(async () => {
        this.$refs['dataForm'].resetFields()
        if (this.keyResultEditor === null) {
          this.keyResultEditor = new E('#keyResultEditorElem')
          this.keyResultEditor.customConfig.uploadImgServer = '/uploadPicture'
          this.keyResultEditor.customConfig.uploadFileName = 'file'
          this.keyResultEditor.customConfig.uploadImgParams = ''
          this.keyResultEditor.customConfig.debug = true
          this.keyResultEditor.create()
          if (this.auth.keyResult < 2) {
            this.keyResultEditor.$textElem.attr('contenteditable', false)
          }
        }
        if (this.checkResultEditor === null) {
          this.checkResultEditor = new E('#checkResultEditorElem')
          this.checkResultEditor.customConfig.uploadImgServer = '/uploadPicture'
          this.checkResultEditor.customConfig.uploadFileName = 'file'
          this.checkResultEditor.customConfig.uploadImgParams = ''
          this.checkResultEditor.customConfig.debug = true
          this.checkResultEditor.create()
          if (this.auth.checkResult < 2) {
            this.checkResultEditor.$textElem.attr('contenteditable', false)
          }
        }
        if (this.scoreCommentEditor === null) {
          this.scoreCommentEditor = new E('#scoreCommentEditorElem')
          this.scoreCommentEditor.customConfig.uploadImgServer = '/uploadPicture'
          this.scoreCommentEditor.customConfig.uploadFileName = 'file'
          this.scoreCommentEditor.customConfig.uploadImgParams = ''
          this.scoreCommentEditor.customConfig.debug = true
          this.scoreCommentEditor.create()
          if (this.auth.scoreComment < 2) {
            this.scoreCommentEditor.$textElem.attr('contenteditable', false)
          }
        }
        if (this.dataForm.id && this.dataForm.id > 0) {
          const data = await apiDetailInfo(this.dataForm.id)
          if (data && data.code === 0) {
            this.dataForm = data.detailInfo
            if (this.keyResultEditor !== null) {
              this.keyResultEditor.txt.html(this.dataForm.keyResult || '')
            }
            if (this.checkResultEditor !== null) {
              this.checkResultEditor.txt.html(this.dataForm.checkResult || '')
            }
            if (this.scoreCommentEditor !== null) {
              this.scoreCommentEditor.txt.html(this.dataForm.scoreComment || '')
            }
          }
        }
      })
    },
    changeSuperScore () {

    },
    alertInfo (msg) {
      this.$message({
        message: msg,
        type: 'success',
        duration: 1500,
        onClose: () => {
        }
      })
    },
    stringIsNull (str) {
      if (typeof str === 'undefined' || str === null || str === '') {
        return true
      }
      return false
    },
    async dataFormSubmit () {
      if (this.auth.target === 2) {
        if (this.stringIsNull(this.dataForm.target)) {
          this.alertInfo('目标不能为空')
          return
        }
      }
      if (this.auth.keyResult === 2 && this.type === 1) {
        if (this.stringIsNull(this.keyResultEditor.txt.html())) {
          this.alertInfo('关键结果不能为空')
          return
        }
      }
      if (this.auth.checkWeight === 2) {
        if (this.stringIsNull(this.dataForm.checkWeight)) {
          this.alertInfo('权重不能为空')
          return
        }
        let data = await weightCheck({
          'recordResultId': this.recordResultId,
          'weight': this.dataForm.checkWeight,
          'type': this.type,
          'id': this.dataForm.id
        })
        if (data && data.code !== 0) {
          this.alertInfo(data.msg)
          return
        }
      }
      if (this.auth.checkResult === 2) {
        if (this.stringIsNull(this.checkResultEditor.txt.html())) {
          this.alertInfo('考核结果不能为空')
          return
        }
      }
      const score1 = this.superScoreData.filter(i => this.dataForm.acquireScore === i.score)
      let superScore1 = ''
      if (score1 !== null && score1 !== '' && score1.length > 0) {
        superScore1 = score1[0].label
      }
      if (this.auth.superScore === 2) {
        if (this.stringIsNull(superScore1)) {
          this.alertInfo('上级评分不能为空')
          return
        }
      }
      if (this.auth.scoreComment === 2) {
        if (this.dataForm.acquireScore !== 3.5 || this.dataForm.acquireScore !== 3.75) {
          if (this.stringIsNull(this.scoreCommentEditor.txt.html())) {
            this.alertInfo('评分说明不能为空')
            return
          }
        }
      }
      if (this.auth.priority === 2) {
        if (this.dataForm.priority !== 0) {
          if (!this.dataForm.priority) {
            this.alertInfo('优先级不能为空')
            return
          }
        }
        if (!/^(0|[1-9][0-9]*)$/.test(this.dataForm.priority)) {
          this.alertInfo('请输入大于或等于0的整数')
          return
        }
      }

      recorddetailAddOrUpdate({
        'id': this.dataForm.id || undefined,
        'type': this.type,
        'target': this.dataForm.target,
        'keyResult': Base64.encode(this.keyResultEditor.txt.html()),
        'checkWeight': this.dataForm.checkWeight,
        'checkResult': Base64.encode(this.checkResultEditor.txt.html()),
        'superScore': superScore1,
        'acquireScore': this.dataForm.acquireScore,
        'scoreComment': Base64.encode(this.scoreCommentEditor.txt.html()),
        'recordId': this.recordResultId,
        'recordType': this.recordType,
        'priority': this.dataForm.priority
      }).then(res => {
        if (res && res.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList', res.recordId)
            }
          })
        }
      })
    },
    async dataFormDelete () {
      let id = this.dataForm.id
      if (typeof id === 'undefined' || id === null || id === '') {
        this.$message({
          message: '是添加按钮，不能删除',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
          }
        })
        return
      }
      const data = await recorddetailDelete(this.dataForm.id)
      if (data && data.code === 0) {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      }
    }
  }
}
</script>
