<template>
  <base-model :config="model_cfg">
    <template slot="dialog-body">
      <el-form
        ref="qcQuestionForm"
        v-loading="loading"
        :model="form"
        :rules="rules"
        label-width="130px"
        size="small"
      >
        <!-- 问题名称 -->
        <el-form-item :label="$t('trials:qcCfg:table:questionName')" prop="QuestionName">
          <el-input v-model="form.QuestionName" />
        </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 === 'select' || form.Type === 'radio'"
          :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('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 { addOrUpdateQCQuestionConfigure, getQCQuestionSelectList } from '@/api/dictionary'
import BaseModel from '@/components/BaseModel'
const formDataDefault = () => {
  return {
    Id: '',
    QuestionName: '',
    IsRequired: true,
    IsEnable: true,
    Type: 'select',
    TypeValue: '',
    ShowOrder: 0,
    ParentId: '',
    QuestionEnName: '',
    ParentTriggerValue: '',
    LanguageType: null
  }
}
export default {
  name: 'QcQuestionForm',
  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:qcCfg:message:msg1')))
        } 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' }],
        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() {

  },
  methods: {
    async openDialog(title, data) {
      if (!data.Id) {
        this.form = formDataDefault()
      }
      this.model_cfg.visible = true
      this.model_cfg.title = title
      var param = {
        id: data.Id ? data.Id : '',
        typeArray: ['select', 'radio']
      }
      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.qcQuestionForm.validate(valid => {
        if (valid) {
          this.btnLoading = true
          addOrUpdateQCQuestionConfigure(this.form).then(res => {
            this.btnLoading = false
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            // this.$refs['qcQuestionForm'].resetFields()
            this.model_cfg.visible = false
            this.$emit('getList')
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleCancle() {
      this.model_cfg.visible = false
    },
    typeChange(val, data) {
      if (val !== 'select' && val !== 'radio') {
        data.TypeValue = ''
      }
    },
    // 获取父问题下拉框选项
    getParentQsOpntions(param) {
      return new Promise((resolve, reject) => {
        this.loading = true
        getQCQuestionSelectList(param).then(res => {
          this.parentOptions = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    // 父问题change事件
    parentQuestionChange(val, data) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === val
        })
        if (index !== -1) {
          this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
        }
      }
      data.ParentTriggerValue = ''
    }
  }
}
</script>
