<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 { personMouldListApi, userPersonMouldIdListApi, associatedUserMouldsApi } from '@/apis/userManage.js'
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const { locale } = useI18n();
const lanChange = ref(locale);

const emit = defineEmits(["close"]);
const props = defineProps({
  cUserId: {
    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 personMouldListApi(1, 10000);
    const modelIds = await userPersonMouldIdListApi(props.cUserId);
    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,
    userId: props.cUserId
  }
  const res = await associatedUserMouldsApi(data);
  if(res.code === 200) {
    ElMessage.success((lanChange.value) == "zh-cn" ? "关联成功！" : 'Successfully associated!');
    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>