<template>
  <div>
    <el-checkbox-group v-model="checkboxGroup" size="small" class="checkbox">
      <el-checkbox v-for="(item, index) in tableData" :key="index" :label="item.id" border>
        <img :src="item.coverImg" width="50" />
        <p>{{ item.title }}</p>
      </el-checkbox>
    </el-checkbox-group>
    <div style="margin-top: 20px">
      <el-button @click="handleClose"
        >{{ $t('personMould.cancel') }}</el-button
      >
      <el-button type="primary" @click="addModel()">{{ $t('personMould.confirm') }}</el-button>
    </div>
</div>
</template>

<script setup>
import { ref } from 'vue'
import { voiceMouldListApi, userVoiceIdListApi, associatedUserVoicesApi } from '@/apis/userManage.js'
import dayjs from "dayjs";

const emit = defineEmits(["close"]);
const props = defineProps({
  serviceId: {
    required: true,
  }
});

const getDate = (val) => {
  return dayjs(val).format("YYYY-MM-DD");
};

const checkboxGroup = ref([])
const total = ref(0);
const tableData = ref([]);

const modelAllListFunc = async () => {
  try {
    const res = await voiceMouldListApi(1, 10000);
    const modelIds = await userVoiceIdListApi(props.serviceId);
    tableData.value = res.data.list;
    total.value = res.data.total * 1;
    setTimeout(()=> {
      if(modelIds.data && modelIds.data.length > 0) {
          modelIds.data.forEach((item) => {
            checkboxGroup.value.push(item)
          })
      }
    }, 500)

  } catch (error) {
    console.log(error, "err");
  }
};

const addModel = async () => {
  const data = {
    mouldIds: checkboxGroup.value,
    cUserId: props.serviceId
  }
  const res = await associatedUserVoicesApi(data);
  if(res.code === 200) {
    ElMessage.success("关联成功！");
    handleClose()
  }
};

function handleClose() {
  emit("close");
}
onMounted(() => {
  modelAllListFunc(1, 10);
});
</script>

<style lang="scss" scoped>
.checkbox {
  max-height: 500px;
  overflow: auto;
  :deep .el-checkbox.el-checkbox--small {
    width: 110px;
    height:110px;
    margin-bottom: 10px;
  }
}
</style>