<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import type {
  meaningListType,
  wordSonSpinnerListType,
  wordSpinnerListType,
  wordSpinnerTypeListType,
} from '../interface'

import {
  getSonSpinnerListApi,
  getSpinnerListApi,
  getSpinnerTypeApi,
  postWordSaveApi,
  putWordSaveApi,
} from '#/api'

import NewWordMeaningBox from '../components/NewWordMeaningBox.vue'
import Upload from '../components/Upload.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '新增单词',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})
const _formData = {
  spell: '',
  brAccents: '',
  brAccent: '',
  usAccent: '',
  usAccents: '',
  meaningList: [
    {
      originWordId: null,
      form: null,
      simpleDesc: '',
      enDesc: '',
      subTypeStr: '',
      znDesc: '',
      originWordSpell: '',
      typeAbbr: '',
    },
  ],
}

const formRef = ref<FormInstance | undefined>()
const wordMeaning = ref()
const formData = reactive<Record<string, any>>({
  ..._formData,
})
const wordSpinnerList = ref<wordSpinnerListType[]>([{ type: 0, name: '' }])
const wordSonSpinnerList = ref<wordSonSpinnerListType[]>([
  { spell: '', znDesc: '' },
])
const wordSpinnerTypeList = ref<wordSpinnerTypeListType[]>([
  {
    abbr: '',
    code: 0,
    spell: '',
    znDesc: '',
  },
])
const postFormData = computed(() => {
  return {
    ...formData,
    brAccents: JSON.stringify([
      {
        accent: formData.brAccent || '',
        file: formData.brAccents,
      },
    ]),
    usAccents: JSON.stringify([
      {
        accent: formData.usAccent || '',
        file: formData.usAccents,
      },
    ]),
    meaningList: formData.meaningList.map((item: meaningListType) => {
      if (!item.form) item.form = 1
      return item
    }),
  }
})

const rules = reactive<FormRules>({
  spell: [{ required: true, message: '单词不能为空', trigger: 'blur' }],
})

function onOpen() {
  // if (props.diaData.id) {
  //     for (let i in props.diaData) {
  //         formData[i] = props.diaData[i];
  //     }
  //     const brData = JSON.parse(props.diaData.brAccents)[0];
  //     const usData = JSON.parse(props.diaData.usAccents)[0];
  //     formData.brAccents = brData.file;
  //     formData.brAccent = brData.accent;
  //     formData.usAccent = usData.accent;
  //     formData.usAccents = usData.file;
  //     formData.meaningList = props.diaData.meaningList
  // }
}
// 删除释义
function handleDeleteMeaning(index: number) {
  formData.meaningList = formData.meaningList.filter(
    (item: meaningListType, v: number) => v !== index,
  )
}

function handleAddDefinition() {
  formData.meaningList.push({
    originWordId: null,
    form: null,
    simpleDesc: '',
    enDesc: '',
    subTypeStr: '',
    znDesc: '',
    originWordSpell: '',
    typeAbbr: '',
  })
}

// 获取多个下拉框数据

function getSpinnerList() {
  // 获取形式数据
  getSpinnerListApi().then((res) => {
    wordSpinnerList.value = res
  })
  // 获取子词性数据
  getSonSpinnerListApi().then((res) => {
    wordSonSpinnerList.value = res
  })
  // 获取词性数据
  getSpinnerTypeApi().then((res) => {
    wordSpinnerTypeList.value = res
  })
}

function handleChangeData(index: number, item: meaningListType) {
  // formData.meaningList[index] = item;
  Object.assign(formData.meaningList[index], item)
}

async function handleSave() {
  const isValid: any = []
  isValid.push(formRef.value?.validate())

  wordMeaning.value.forEach(async (item: any) => {
    isValid.push(item.checkFlag())
  })
  Promise.all(isValid).then(() => {
    passed()
  })

  function passed() {
    postFormData.value.brAccents = undefined as any
    postFormData.value.usAccents = undefined as any
    if (props.diaData.id) {
      putWordSaveApi({ ...postFormData.value, id: props.diaData.id }).then(
        () => {
          show.value = false
          emits('onRefresh')
        },
      )
    } else {
      postWordSaveApi({ ...postFormData.value }).then(() => {
        show.value = false
        emits('onRefresh')
      })
    }
    onClear()
  }
}

function onClear() {
  Object.assign(formData, _formData)
  formData.meaningList = [
    {
      originWordId: null,
      form: null,
      simpleDesc: '',
      enDesc: '',
      subTypeStr: '',
      znDesc: '',
      originWordSpell: '',
      typeAbbr: '',
    },
  ]
}

onMounted(() => {
  getSpinnerList()
  // if (props.diaData.id) {
  // }
})
</script>

<template>
  <el-dialog
    v-model="show"
    width="700px"
    :title="title"
    class="box"
    destroy-on-close
    @open="onOpen"
  >
    <el-form ref="formRef" label-width="65px" :model="formData" :rules="rules">
      <el-form-item label="单词" prop="spell">
        <el-col :span="11">
          <el-input v-model="formData.spell" placeholder="请输入" />
        </el-col>
      </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="美音标">
            <el-input
              v-model="formData.brAccent"
              size="small"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="美音频">
            <Upload v-model="formData.brAccents" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="英音标">
            <el-input
              v-model="formData.usAccent"
              size="small"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="英音频">
            <Upload v-model="formData.usAccents" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-scrollbar class="word-meaning-content">
      <NewWordMeaningBox
        v-for="(item, index) in formData.meaningList"
        ref="wordMeaning"
        :key="item"
        :data="item"
        :index="index"
        :word-spinner-type-list="wordSpinnerTypeList"
        :word-son-spinner-list="wordSonSpinnerList"
        :word-spinner-list="wordSpinnerList"
        @change-data="handleChangeData(index, $event)"
        @delete-meaning="handleDeleteMeaning(index)"
      />
    </el-scrollbar>

    <!-- @changeList="formData.meaningList = $event" -->
    <div class="add-box">
      <el-button type="primary" @click="handleAddDefinition">
        添加释义
      </el-button>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.box {
  .el-dialog__body {
    padding-bottom: 20px;
  }

  :deep(.upload-demo) {
    .el-upload-list {
      margin: 0;
    }
  }

  .add-box {
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }
}

.word-meaning-content {
  height: 380px;
  padding: 0 20px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;

  .word-meaning {
    border-top: 2px dashed #558ef0;

    &:first-child {
      border: none;
    }
  }
}
</style>
