<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="108px">
      <el-form-item label="规则名称:" prop="ruleName">
        <el-input
          :disabled="ruleTypeDisabled"
          placeholder="请输入"
          maxlength="50"
          v-autoTrim="{ obj: form, key: 'ruleName' }"
          v-model="form.ruleName"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="规则描述:" prop="ruleDescription">
        <el-input
          placeholder="请输入"
          maxlength="300"
          v-autoTrim="{ obj: form, key: 'ruleDescription' }"
          v-model="form.ruleDescription"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="规则详情:" prop="ruleDetails" v-if="!isScore">
        <editor
          :content="content"
          ref="editor"
          :isEdit="!!$route.query.rulesId"
        ></editor>
      </el-form-item>
      <el-form-item v-else label="规则类型:" prop="ruleType">
        <el-select
          :disabled="ruleTypeDisabled"
          v-model="form.ruleType"
          size="small"
          clearable
          placeholder="请选择规则类型"
        >
          <el-option
            v-for="item in ruleTypeOpts"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="isScore && form.rulesId"
        label="脚本名称:"
        prop="scriptName"
      >
        <el-input
          style="width: 400px"
          disabled
          placeholder=""
          v-model="form.scriptName"
        >
        </el-input>
      </el-form-item>

      <!-- 文件上传 -->
      <el-form-item label="文件上传" v-if="isScore">
        <el-upload
          :multiple="false"
          action=""
          class="upload-demo"
          list-type="card"
          :file-list="fileList"
          :http-request="uploadHandle"
          :on-remove="fileRemove"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <div class="btns">
        <!-- 公有列表进，另存为+取消 另存为为新增一条数据 新增数据均为私有 1 -->
        <!-- 私有列表进，保存+另存为+取消 0 -->
        <!-- 新增进，保存+取消 -1 -->
        <el-button
          type="primary"
          v-if="share === '0' || share === '-1'"
          @click="save(false)"
          >保存</el-button
        >
        <el-button
          type="primary"
          v-if="share === '0' || share === '1'"
          @click="save(true)"
          >另存为</el-button
        >
        <el-button type="primary" plain @click="cancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import editor from './components/editor'
import { ruleTypeOpts } from './common'
import { del } from 'vue'

export default {
  name: 'gradingRuleDetail', // 评分规则
  components: { editor },
  data() {
    return {
      share: '-1', //控制显示按钮
      scriptUpdate: false, // 脚本是否更新
      form: {
        rulesId: '',
        ruleName: '',
        share: '-1',
        ruleDescription: '',
        ruleDetails: '',
        ruleType: '',
        scriptName: '',
      },
      ruleTypeDisabled: false,
      fileList: [], // 文件上传列表
      content: '',
      rules: {
        ruleName: [{ required: true, message: '请输入', trigger: 'blur' }],
        ruleDescription: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        ruleDetails: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      isScore: false, // 评分规则新增类型
      ruleTypeOpts, // 规则类型
    }
  },

  computed: {},

  methods: {
    fileRemove() {
      this.fileList = []
    },
    uploadHandle(f) {
      this.fileList = [f.file]
      this.scriptUpdate = true
    },
    save(isAdd) {
      let ruleDetails = null

      if (!this.isScore) {
        ruleDetails = this.$refs.editor.editor.getText().trim()
        this.form.ruleDetails = ruleDetails
      }
      // 调用save时，应写成save()，给不给参数均可，不写小括号的话，isAdd会是事件源，则为true
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.isScore && ruleDetails && ruleDetails.length > 1000000) {
            this.$message.error('规则详情长度不得超过100万！')
            return
          }

          if (isAdd || !this.$route.query.rulesId) {
            // 另存为或新增页面
            this.form.rulesId = ''
            this.form.share = '0'
          }

          if (this.form.rulesId) {
            this.$axios({
              method: 'post',
              url: this.$api.sceneLibrary.queryCsbById,
              data: {
                rulesId: this.form.rulesId,
              },
            }).then((res) => {
              if (res.code === 200) {
                if (res.info === 0) {
                  this.saveFn()
                  return
                }

                this.$confirm(
                  '该评分规则已经被场景测试包引用，保存后同步更新场景测试包中的评分规则，是否确认保存？',
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
                ).then(() => {
                  this.saveFn()
                })
              } else {
                this.$message.error(
                  res.message || '获取该评分规则是否被场景测试包引用失败'
                )
              }
            })
            return
          }

          this.saveFn()
        }
      })
    },
    saveFn() {
      if (this.isScore) {
        let formData = new FormData()
        let source = { ...this.form }
        source['ruleId'] = source.rulesId
        delete source.rulesId
        const json = JSON.stringify({
          ...source,
          uploadNewFile: this.scriptUpdate,
        })
        const blob = new Blob([json], {
          type: 'application/json',
        })
        formData.append('content', blob)
        this.scriptUpdate && formData.append('file', this.fileList[0])
        this.$axios({
          method: 'post',
          url: this.$api.sceneLibrary.queryScoringRulesInfo,
          data: formData,
          withCredentials: true,
          headers: {
            'Content-type': 'multipart/form-data',
          },
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.cancel()
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
      } else {
        this.$axios({
          method: 'post',
          url: this.$api.sceneLibrary.saveScoringRules,
          data: {
            ...this.form,
          },
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.cancel()
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
      }
    },
    cancel() {
      this.$router.replace({ path: '/gradingRulesList' })
    },
  },

  mounted() {
    this.isScore = this.$route.query.isScore ? true : false // 判断是否评分规则新增
    if (this.$route.query.rulesId) {
      let rulesId = ''
      this.form.rulesId = rulesId = this.$route.query.rulesId
      this.form.share = this.share = this.$route.query.share
      // 场景评价
      if (this.isScore) {
        const { ruleName, ruleDescription, ruleType, scriptName } =
          this.$store.state.evaluationInfo
        this.form = Object.assign(this.form, {
          ruleName,
          ruleDescription,
          ruleType,
          scriptName,
        })
        this.ruleTypeDisabled = true
      } else {
        this.$axios({
          method: 'post',
          url: this.isScore
            ? this.$api.sceneLibrary.queryScoringRulesInfo
            : this.$api.sceneLibrary.queryScoringRules,
          data: {
            rulesId,
          },
        }).then((res) => {
          if (res.code == 200 && res.info) {
            this.form = res.info
            this.content = res.info.ruleDetails
          } else {
            this.$message.error(res.message || '获取信息失败')
          }
        })
      }
    }
  },
}
</script>

<style lang='less' scoped>
.el-form {
  width: 60%;
  padding-top: 60px;
  margin: 0 auto;

  .el-input {
    width: 100%;
  }
}

.btns {
  padding-top: 30px;
  text-align: center;
}
</style>
