<template>
  <el-card class="box-card">
    <el-form :model="props.modelValue" label-width="120px" label-position="top" size="large">
      <el-form-item
        v-for="(item,index) in props.modelValue"
        :key="index"
        :error="item.stateVerify" >
        <template #label>
          <span>{{ index + 1 }}、{{ item.stateName }}</span>
        </template>
        <el-input v-model="item.stateValue" v-if="item.stateType === 'input'" :placeholder="item.statePlaceholder" :disabled="!buttonStatus"/>
        <el-radio-group v-model="item.stateValue" v-if="item.stateType === 'radio'">
          <el-radio
            :label="itemValues.stateItemLabel"
            v-for="(itemValues,indexValues) in item.items"
            :key="indexValues"
            style="margin-bottom: 0.5em"
            :disabled="!buttonStatus">
            {{ itemValues.stateItemName }}
          </el-radio>
        </el-radio-group>
        <el-checkbox-group v-model="item.stateValues" v-if="item.stateType === 'checkbox'" @change="changeCheckBox">
          <el-checkbox
            :label="itemValues.stateItemLabel"
            v-for="(itemValues,indexValues) in item.items"
            :key=indexValues
            :disabled="!buttonStatus">
            {{ itemValues.stateItemName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-if="modelValue.length > 0 && buttonStatus">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import {isEmptyStr} from "@/utils/validate";
import {watch} from "vue";
const {proxy} = getCurrentInstance();
const emit = defineEmits(['refresh'])

const props = defineProps({
  modelValue: {
    type: Array,
    required: true
  },
  buttonStatus: {
    type: Boolean,
    default: false
  }
})
const checkItem = () => {
  return new Promise((resolve, reject) => {
    props.modelValue.forEach(item => {
      if (isEmptyStr(item.stateValue)) {
        reject("答案为空！")
        item.stateVerify = "答案不能为空！"
        return false
      }else {
        item.stateVerify = ''
      }
    })
    resolve("校验通过");
  })
}

//提交
const onSubmit= () =>{

  checkItem().then(res =>{
    emit('refresh');
  })
};

const reset= () =>{
  props.modelValue.map((item, index) => {
    Object.keys(item).forEach((key) => {
      if (key === 'stateValue' && (item["stateType"] === 'input' || item["stateType"] === 'radio' )) {
        item[key] = ''
      } else if (key === 'stateValue' && item["stateType"] === 'checkbox'){
        item[key] = []
      }
    })
    return item
  })
}
//处理多选的选择存储问题
const changeCheckBox = (index) =>{
  props.modelValue[index].stateValue = props.modelValue[index].stateValues.join(',')
}

</script>
<style scoped lang="scss">

</style>
