<template>
  <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 100%"
    border
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" align="center"/>
    <el-table-column property="title" label="标题" align="center"/>
    <el-table-column label="图片" align="center">
      <template #default="scope">
        <img :src="scope.row.coverImg" width="50" />
      </template>
    </el-table-column>
    <el-table-column
        prop="createTime"
        :label="$t('businessMangage.createTime')"
        align="center"
      >
        <template #default="scope">
          {{ getDate(scope.row.createDate) }}
        </template>
      </el-table-column>
  </el-table>
  <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 50, 100]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  <div style="margin-top: 20px">
    <el-button @click="handleClose"
      >取消</el-button
    >
    <el-button type="primary" @click="addModel()">确认关联</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElTable } from 'element-plus'
import { modelAllList, personMouldIdList, associatedMould } from '@/apis/apiManage.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 multipleTableRef = ref()
const multipleSelection = ref([])
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);

const handleSizeChange = (val) => {
  pageSize.value = val;
  modelAllListFunc(pageNum.value, pageSize.value);
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  modelAllListFunc(pageNum.value, pageSize.value);
};
const modelAllListFunc = async (PageNum, PageSize) => {
  try {
    const res = await modelAllList(PageNum, PageSize);
    debugger
    const modelIds = await personMouldIdList(props.serviceId);
    let idIndx = []
    if(modelIds.data && modelIds.data.length > 0) {
      res.data.list.forEach((ele, idx) => {
        modelIds.data.forEach((item) => {
          if (ele.id === item.personMouldId) {
            idIndx.push(idx)
          }
        })
      })
    }
    tableData.value = res.data.list;
    total.value = res.data.total * 1;
    // 选中关联模版
    if(idIndx.length) {
      setTimeout(()=> {
        let list = []
        idIndx.forEach(d => {
          list.push(tableData.value[d])
        })
        toggleSelection(list)
      }, 500)
    }
  } catch (error) {
    console.log(error, "err");
  }
};

const addModel = async () => {
  console.log(multipleSelection.value)
  let mouldIds = []
  multipleSelection.value.forEach(res => {
    mouldIds.push(res.id)
  })
  const data = {
    mouldIds: mouldIds,
    serviceId: props.serviceId
  }
  const res = await associatedMould(data);
  if(res.code === 200) {
    ElMessage.success("关联成功！");
    handleClose()
  }
};

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