<template>
  <base-model :config="model_cfg">
    <template slot="dialog-body">
      <el-form
        ref="medicalAuditForm"
        v-loading="loading"
        :model="form"
        :rules="rules"
        label-width="140px"
        size="small"
      >
        <el-form-item :label="$t('trials:MIMqcCfg:table:questionName')" prop="QuestionName">
          <el-input v-model="form.QuestionName" type="textarea"
          :rows="2"/>
        </el-form-item>
        <el-form-item
          :label="$t('common:title:languageType')"
          prop="LanguageType"
        >
          <el-select
            v-model="form.LanguageType"
          >
            <el-option
              v-for="item of $d.LanguageType"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </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 !== 'textarea' && form.Type !== 'input'" :label="$t('trials:qcCfg:table:typeValue')" prop="TypeValue">
          <el-input v-model="form.TypeValue" :placeholder="$t('trials:qcCfg:message:typeValue')" />
        </el-form-item>
        <!-- 是否通用 -->
        <el-form-item
          :label="$t('dictionary:medicalAudit:label:IsGeneral')"
          prop="IsGeneral"
        >
          <el-switch
            v-model="form.IsGeneral"
          />
          <span>{{ $fd('YesOrNo', form.IsGeneral) }}</span>
        </el-form-item>
        <!-- 任务类型 -->
        <el-form-item
          v-if="!form.IsGeneral"
          :label="$t('trials:auditRecord:table:criterion')"
          prop="CriterionTypeEnum"
        >
          <el-select v-model="form.CriterionTypeEnum">
            <el-option v-for="item of $d.CriterionType" :key="item.id" :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: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: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.YesOrNo"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </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>
    </template>
    <template slot="dialog-footer">
      <el-button :disabled="btnLoading" size="small" type="primary" @click="handleCancle">
        {{ $t('common:button:cancel') }}
      </el-button>
      <el-button size="small" type="primary" :loading="btnLoading" @click="handleSave">
        {{ $t('common:button:save') }}
      </el-button>
    </template>
  </base-model>
</template>
<script>
import { addOrUpdateReadingMedicineSystemQuestion, getReadingMedicineSystemOtherQuestion } from '@/api/dictionary'
import BaseModel from '@/components/BaseModel'
const formDataDefault = () => {
  return {
    Id: '',
    QuestionName: '',
    IsRequired: true,
    IsEnable: true,
    Type: 'select',
    TypeValue: '',
    ShowOrder: 0,
    ParentId: '',
    ParentTriggerValue: '',
    ReadingCategory: '',
    CriterionTypeEnum: null,
    LanguageType: null,
    IsGeneral: true
  }
}
export default {
  name: 'MedicalAuditForm',
  components: { BaseModel },
  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 {
      btnLoading: false,
      form: formDataDefault(),
      rules: {
        QuestionName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 300, message: `${this.$t('common:ruleMessage:maxLength')} 300` }],
        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' }
        ],
        LanguageType: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]
      },
      model_cfg: { visible: false, showClose: true, width: '600px', title: '' },
      parentOptions: [],
      parentTriggerValOptions: [],
      loading: false
    }
  },
  mounted() {
    // if (Object.keys(this.data).length && this.data.Id) {
    //   this.form = { ...this.data }
    // }
  },
  methods: {
    async openDialog(title, data) {
      if (!data.Id) {
        this.form = formDataDefault()
      }
      this.model_cfg.visible = true
      this.model_cfg.title = title
      var param = {
        trialId: this.trialId,
        id: data.Id ? data.Id : '',
        readingCategory: data.ReadingCategory ? data.ReadingCategory : ''
      }
      await this.getParentQsOpntions(param)
      if (data.ParentId) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === data.ParentId
        })
        if (index !== -1) {
          this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
        }
      }
      if (Object.keys(data).length && data.Id) {
        this.form = { ...data }
      }
    },
    handleSave() {
      this.$refs.medicalAuditForm.validate(valid => {
        if (valid) {
          this.btnLoading = true
          if (this.form.IsGeneral) {
            this.form.CriterionTypeEnum = null
          }
          addOrUpdateReadingMedicineSystemQuestion(this.form).then(res => {
            this.btnLoading = false
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.model_cfg.visible = false
            this.$emit('getList')
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleCancle() {
      this.model_cfg.visible = false
    },
    // 获取父问题下拉框选项
    getParentQsOpntions(param) {
      return new Promise((resolve, reject) => {
        this.loading = true
        getReadingMedicineSystemOtherQuestion(param).then(res => {
          this.parentOptions = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    readingCategoryChange(val, form) {
      if (val) {
        var param = {
          trialId: this.trialId,
          id: this.form.Id,
          readingCategory: val
        }
        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 = ''
      }
    }
  }
}
</script>
