<template>
  <el-form
    ref="questionForm"
    v-loading="loading"
    :model="form"
    label-width="120px"
    size="small"
    :rules="rules"
  >
    <div class="base-dialog-body">
      <!-- 审核问题 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:questionName')"
        prop="QuestionName"
      >
        <el-input :maxLength="$inputMax"
          v-model="form.QuestionName"
        />
      </el-form-item>

      <!-- 类型 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:type')"
      >
        <el-select
          v-model="form.Type"
          @change="((val)=>{typeChange(val, form)})"
        >
          <el-option
            v-for="item of $d.QcType"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 选项 -->
      <el-form-item
        v-if="form.Type === 'select' || form.Type === 'radio'"
        :label="$t('trials:qcCfg:table:typeValue')"
        prop="TypeValue"
      >
        <el-input :maxLength="$inputMax"
          v-model="form.TypeValue"
          :placeholder="$t('trials:qcCfg:message:typeValue')"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
        />
      </el-form-item>

      <!-- 任务类型 -->
      <el-form-item
        v-if="form.Type === 'select' || form.Type === 'radio'"
        :label="$t('trials:medicalFeedbackCfg:title:taskType')"
        prop="ReadingCategory"
      >
        <el-select v-model="form.ReadingCategory" @change="((val)=>{readingCategoryChange(val, form)})">
          <el-option v-for="item of $d.ReadingCategory" :key="item.id" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>

      <!-- 父问题 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:parentQs')"
      >
        <el-select
          v-model="form.ParentId"
          clearable
          @change="((val)=>{parentQuestionChange(val, form)})"
        >
          <el-option
            v-for="item of parentOptions"
            :key="item.Id"
            :label="item.QuestionName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 父问题触发值 -->
      <el-form-item
        v-if="form.ParentId"
        :label="$t('trials:qcCfg:table:parentTriggerValue')"
        prop="ParentTriggerValue"
      >
        <el-select
          v-model="form.ParentTriggerValue"
        >
          <el-option
            v-for="item of parentTriggerValOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <!-- 序号 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:order')"
        prop="ShowOrder"
      >
        <el-input-number
          v-model="form.ShowOrder"
          controls-position="right"
          :min="0"
        />
      </el-form-item>
      <!-- 是否必填 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:isRequired')"
      >
        <el-radio-group
          v-model="form.IsRequired"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`IsRequired${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 启用状态 -->
      <el-form-item
        :label="$t('trials:qcCfg:table:isEnable')"
      >
        <el-radio-group
          v-model="form.IsEnable"
        >
          <el-radio
            v-for="item of $d.IsEnable"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item style="text-align:right;">
        <!-- 取消 -->
        <el-button
          size="small"
          type="primary"
          @click="handleClose"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- Save -->
        <el-button
          size="small"
          type="primary"
          @click="handleSave"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { getReadingMedicineTrialOtherQuestion, addOrUpdateReadingMedicineTrialQuestion } from '@/api/trials'
export default {
  name: 'MedicalAuditQSFrom',
  props: {
    data: {
      type: Object,
      default() { return {} }
    },
    trialReadingCriterionId: {
      type: String,
      default() {
        return ''
      }
    }
  },

  data() {
    var validateTypeVal = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('common:ruleMessage:specify')))
      } else {
        var arr = value.split('|')
        if (new Set(arr).size !== arr.length) {
          // '选项不允许存在相同值'
          callback(new Error(this.$t('trials:medicalFeedbackCfg:message:msg2')))
        } else {
          callback()
        }
      }
    }
    return {
      form: {
        Id: '',
        QuestionName: '',
        IsRequired: true,
        IsEnable: true,
        Type: 'select',
        TypeValue: '',
        ShowOrder: 0,
        ParentId: '',
        ParentTriggerValue: '',
        ReadingCategory: ''
      },
      rules: {
        QuestionName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }],
        TypeValue: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: validateTypeVal, trigger: 'blur' },
          { max: 200, message: `${this.$t('common:ruleMessage:maxLength')} 200` }],
        ParentTriggerValue: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        ReadingCategory: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]
      },
      trialId: '',
      loading: false,
      parentOptions: [],
      parentTriggerValOptions: []
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.initForm()
  },
  methods: {
    async initForm() {
      this.loading = true
      var param = {
        trialId: this.trialId,
        id: this.data.Id ? this.data.Id : '',
        readingCategory: this.data.ReadingCategory ? this.data.ReadingCategory : '',
        TrialReadingCriterionId: this.trialReadingCriterionId
      }
      await this.getParentQsOpntions(param)
      if (this.data.ParentId) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === this.data.ParentId
        })
        if (index !== -1) {
          this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
        }
      }
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            this.form[k] = this.data[k]
          }
        }
      }
      this.loading = false
    },
    // 更新qc问题配置信息
    handleSave() {
      this.$refs.questionForm.validate(valid => {
        if (!valid) return
        this.loading = true
        this.form.TrialId = this.trialId
        this.form.TrialReadingCriterionId = this.trialReadingCriterionId
        addOrUpdateReadingMedicineTrialQuestion(this.form).then(res => {
          this.loading = false
          if (res.IsSuccess) {
            // 关闭弹窗并刷新
            this.$emit('close')
            this.$emit('getList')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
        }).catch(() => { this.loading = false })
      })
    },
    // 获取父问题下拉框选项
    getParentQsOpntions(param) {
      return new Promise((resolve, reject) => {
        getReadingMedicineTrialOtherQuestion(param).then(res => {
          this.parentOptions = res.Result
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    readingCategoryChange(val, form) {
      if (val) {
        var param = {
          trialId: this.trialId,
          id: this.form.Id,
          readingCategory: val,
          TrialReadingCriterionId: this.trialReadingCriterionId
        }
        this.parentOptions = []
        this.parentTriggerValOptions = []
        this.getParentQsOpntions(param)
        this.form.ParentId = ''
        this.form.ParentTriggerValue = ''
      }
    },
    // 父问题change事件
    parentQuestionChange(val, form) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === val
        })
        if (index !== -1) {
          this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
          this.form.ReadingCategory = this.parentOptions[index].ReadingCategory
        }
      }
      this.form.ParentTriggerValue = ''
    },
    typeChange(val, data) {
      if (val !== 'select' && val !== 'radio') {
        data.TypeValue = ''
      }
    },
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss">

</style>
