<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>
          <el-input v-model="item.stateName" placeholder="请输入问题" @blur="verifyItem($event, index,'请输入问题！')">
            <template #prefix>
              <span>{{ index + 1 }}、</span>
            </template>
            <template #suffix>
              <el-button type="primary" icon="Delete" plain style="margin-right: -1em"
                         @click="deleteItem(index)"/>
            </template>
          </el-input>
        </template>
        <!-- 输入框 -->
        <el-input v-model="item.statePlaceholder" v-if="item.stateType === 'input'" placeholder="内容提示语"
                  @blur="verifyItem($event, index,'请输入输入时提示语！')"/>
        <el-input v-model="item.stateValue" v-if="item.stateType === 'input'" placeholder="答案"
                  @blur="verifyItem($event, index,'请输入答案！')"/>
        <!-- 单选框 -->
        <el-radio-group v-model="item.stateValue" v-if="item.stateType === 'radio'">
          <el-radio
            :label="itemValueKey.stateItemLabel"
            v-for="(itemValueKey,indexValues) in item.items"
            :key=indexValues
            style="margin-bottom: 0.5em">
            <el-input v-model="itemValueKey.stateItemName" placeholder="请输入选择内容"
                      @blur="verifyItem($event, index,'请输入选择项！')">
              <template #suffix>
                <el-button type="primary" icon="Plus" plain class="marginButton2"
                           @click="additemValues(index, indexValues)" v-if="item.items.length-1 === indexValues"/>
                <el-button type="primary" icon="Delete" plain style="margin-right: -1em"
                           @click="deleteitemValues(index, indexValues)" v-if="item.items.length > 2"/>
              </template>
            </el-input>
          </el-radio>
        </el-radio-group>
        <!-- 多选框 -->
        <el-checkbox-group v-model="item.stateValues" v-if="item.stateType === 'checkbox'" @change="changeCheckBox(index)">
          <el-checkbox
            :label="itemValueKey.stateItemLabel"
            v-for="(itemValueKey,indexValues) in item.items"
            :key="indexValues"
            :name="'checkbox'+ itemValueKey.stateItemLabel +indexValues"
            style="margin-bottom: 0.5em">
            <el-input v-model="itemValueKey.stateItemName" placeholder="请输入选择内容"
                      @blur="verifyItem($event, index, '请输入选择项！')">
              <template #suffix>
                <el-button type="primary" icon="Plus" plain class="marginButton2"
                           @click="additemValues(index, indexValues)" v-if="item.items.length-1 === indexValues"/>
                <el-button type="primary" icon="Delete" plain style="margin-right: -1em"
                           @click="deleteitemValues(index, indexValues)" v-if="item.items.length > 2"/>
              </template>
            </el-input>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-if="modelValue.length > 0">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="reset">清空数据</el-button>
        <el-button @click="deleteItemAll">删除所有选项</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script setup>

import {isEmptyStr} from '@/utils/validate'
import {ElMessage} from 'element-plus'
import {toRefs} from "vue";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['refresh'])

const props = defineProps({
  modelValue: {
    type: Array,
    required: true
  },
  checkValue: {
    type: Number,
    required: true
  }
})
const { checkValue } = toRefs(props);

//删除单(多)选元素
const deleteitemValues = (index, indexValues) => {
  if (props.modelValue[index].items.length <= 2) {
    proxy.$modal.msgError("选择数据不能小于两条！");
    return
  }
  props.modelValue[index].items.splice(index, 1);
}
//新增单(多)选元素
const additemValues = (index) => {
  if (props.modelValue[index].items.length >= 6) {
    proxy.$modal.msgError("选择数据不能大于六条！");
    return
  }
  const arr = props.modelValue[index].items.map(({stateItemLabel})=> stateItemLabel);
  let max = Math.max(...arr);
  let orderNum = max === -Infinity ? 0: ++max
  props.modelValue[index].items.push({
    stateItemLabel: orderNum,
    stateItemName: null,
    orderNum: orderNum,
  });
}
//增加元素
const addItem = (type) => {
  const arr = props.modelValue.map(({orderNum})=> orderNum);
  let max = Math.max(...arr);
  let orderNum = max === -Infinity ? 0: ++max
  switch (type) {
    case 'input': {
      //输入框元素
      props.modelValue.push({
        stateName: null,
        stateValue: null,
        stateType: 'input',
        statePlaceholder: null,
        stateVerify: null,
        orderNum: orderNum,
      })
      break;
    }
    case 'radio': {
      //单选元素
      props.modelValue.push({
        stateName: null,
        stateValue: null,
        stateType: 'radio',
        statePlaceholder: null,
        stateVerify: null,
        orderNum: orderNum,
        items: [{
          stateItemLabel: 1,
          stateItemName: null,
          orderNum: 1,
        },
          {
            stateItemLabel: 2,
            stateItemName: null,
            orderNum: 2,
          }
        ]
      })
      break;
    }
    case 'checkbox': {
      //单选元素
      props.modelValue.push({
        stateName: null,
        stateValue: '',
        stateValues: [],
        stateType: 'checkbox',
        statePlaceholder: null,
        stateVerify: null,
        orderNum: orderNum,
        items: [
          {
            stateItemLabel: 1 ,
            stateItemName: null,
            orderNum: 1,
          },
          {
            stateItemLabel: 2 ,
            stateItemName: null,
            orderNum: 2,
          }
        ]
      })
      break;
    }
  }
}
//删除元素
const deleteItem = (index) => {
  props.modelValue.splice(index, 1);
}
//输入后的回调 校验是否填写
const verifyItem = (event, index, msg) => {
  if (isEmptyStr(event.target.value) || (Array.isArray(event.target.value) && event.target.value === 0)) {
    if (msg === '请输入答案！' && !Number(checkValue.value) === 1){
      return
    }
    props.modelValue[index].stateVerify = msg
  } else {
    props.modelValue[index].stateVerify = null
  }
}

//检查所有元素是否已经填写
const checkItem = () => {
  return new Promise((resolve, reject) => {
    props.modelValue.forEach(item => {
      if (isEmptyStr(item.stateName)) {
        reject("问题为空！")
        item.stateVerify = "问题不能为空！"
        return false
      } else if (isEmptyStr(item.stateValue) && Number(checkValue.value) === 1) {
        reject("答案为空！")
        item.stateVerify = "答案不能为空！"
        return false
      } else if (item.stateType === 'input' && isEmptyStr(item.statePlaceholder)) {
        reject("输入框提示语为空！")
        item.stateVerify = "输入框提示语不能为空！"
        return false
      } else if (item.stateType === 'radio' || item.stateType === 'checkbox') {
        item.items.forEach(x => {
          if (isEmptyStr(x.stateItemName)) {
            reject("选择项为空！")
            item.stateVerify = "选择项不能为空！"
            return false
          } else {
            item.stateVerify = null
          }
        })
      } else {
        item.stateVerify = null
      }
    })
    resolve("校验通过");
  })
}

//提交数据
const onSubmit = () => {
  if (Array.isArray(props.modelValue) && props.modelValue.length === 0) {
    ElMessage.error('请添加元素！')
    return false;
  }
  checkItem().then(res => {
    emit('refresh');
  })

}
//清空数据 但是不删除元素
const reset = () => {
  props.modelValue.map((item, index) => {
    Object.keys(item).forEach((key) => {
      if (key !== 'items' && key !== 'stateType') {
        item[key] = null
      } else if (key === 'items') {
        item[key].map((items, indexItem) => {
          items.stateItemName = null
          return items
        })
      }
    })
    return item
  })
}
//删除所有元素
const deleteItemAll = () => {
  props.modelValue.splice(0, props.modelValue.length);
}
//处理多选的选择存储问题
const changeCheckBox = (index) =>{
  props.modelValue[index].stateValue = props.modelValue[index].stateValues.join(',')
}
//  抛出函数 被调用
defineExpose({
  addItem
});
</script>


<style scoped lang="scss">

</style>
