<template>
  <el-form v-if="standardMajorTree.length" ref="form" :disabled="disabled" :model="form" :rules="rules">
    <el-form-item prop="majors" :class="{'major-disabled': disabled}">
      <el-cascader
        v-if="standardMajorTree.length"
        v-model="form.majors"
        :props="cascaderConfig"
        :options="standardMajorTree"
        :disabled="disabled"
        clearable filterable
        style="width: 100%">
      </el-cascader>
    </el-form-item>
    <el-form-item v-if="!disabled" class="form-item-readonly">
      <el-button type="primary" size="small" round @click="handleSubmit">保存</el-button>
      <el-button size="small" round @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
  <div v-else class="f-yellow">
    如果测验结果可信，则表明您的性格极富有弹性，兼有多种性格特征。但专门对应于这种性格的专业或职业很少，系统无法给您提供有效的专业门类推荐。
    如果测验过程中有疏漏或误解，则需进一步澄清；您也可以重新测评予以调整结果。
  </div>
</template>

<script>
export default {
  name: 'test-major-picker',
  model: {
    prop: 'selectedCodes',
    event: 'change'
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    majorTree: {
      type: Array,
      default: () => []
    },
    selectedCodes: {
      type: Array,
      default: () => []
    },
    selectedNames: {},
    selectLimit: {
      type: Number,
      default: 7
    }
  },
  data() {
    return {
      cascaderConfig: {
        multiple: true,
        emitPath: false
      },
      form: {
        majors: []
      },
      rules: {
        majors: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length == 0) return callback('请选择专业类')
              return callback()
            }
          },
          {
            validator: (rule, value, callback) => {
              if (this.selectLimit <= 0) return callback()
              if (value?.length > this.selectLimit) callback(`最多选择${this.selectLimit}个专业类`)
              return callback()
            }
          }]
      }
    }
  },
  computed: {
    standardMajorTree() {
      return this.convertStandardTree(this.majorTree, 'name', 'code', 'nodes')
    }
  },
  watch: {
    selectedCodes: {
      immediate: true,
      handler: function(val) {
        // 把选中值设置为模板
        if (!val?.length) return
        this.form.majors = [...val]
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate().then(() => {
        this.$emit('submit', this.form.majors)
      })
    },
    handleCancel() {
      this.form.majors = [...this.selectedCodes]
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
/deep/.major-disabled .el-cascader__tags .el-tag {
  background-color: #ffba00;
}

/deep/.major-disabled .el-tag.el-tag--info {
  color: #FFFFFF;
}

/deep/.major-disabled .el-cascader__tags .el-tag .el-icon-close {
  background-color: #FFFFFF;
  color: #C0C4CC;
}
</style>
