<template>
  <div class="dsion-step2">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handelImport" :disabled="status === 1">导入</a-button>
        <a-button type="primary" @click="handelAdd" :disabled="status === 1">添加</a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="createActions(record)" />
      </template>
    </BasicTable>

    <FormImport @register="registerImportModal" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, watch } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    EditRecordRow,
    ActionItem,
  } from '/@/components/Table';
  import { table2Columns } from '../data.config';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { buildUUID } from '/@/utils/uuid';
  import FormImport from './import.vue';
  import { useModal } from '/@/components/Modal';
  import {
    deleteBandingBandingTaskClass,
    getBandingTaskClassList,
    postBandingBandingTaskClass,
    putBandingBandingTaskClass,
  } from '/@/services/apis/BandingTaskClassController';
  import { cloneDeep } from 'lodash-es';

  const [registerImportModal, { openModal: openImportModal }] = useModal();

  const [registerTable, { reload, insertTableDataRecord, deleteTableDataRecord, getDataSource }] =
    useTable({
      api: getBandingTaskClassList,
      title: '班级列表',
      rowKey: 'id',
      columns: table2Columns,
      useSearchForm: false,
      showTableSetting: true,
      bordered: true,
      immediate: false,
      canResize: true,
      pagination: false,
      actionColumn: {
        width: 120,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
    });

  const searchInfo = reactive<Recordable>({});

  const props = defineProps({
    taskId: { type: String, default: '' },
    status: { type: Number, default: 0 },
  });

  watch(
    () => props.taskId,
    async (newVal) => {
      if (newVal) {
        searchInfo.bandingTaskId = newVal;
      }
    },
  );

  const currentEditKeyRef = ref('');
  const { createMessage } = useMessage();

  const handelAdd = () => {
    insertTableDataRecord({ id: buildUUID(), _newRow: true });
  };

  const handleEdit = async (record: EditRecordRow) => {
    currentEditKeyRef.value = record.id;
    await record.onEdit?.(true);
  };

  const handleCancel = (record: EditRecordRow) => {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  };

  const handleDelete = async (record: EditRecordRow) => {
    if (record._newRow) {
      deleteTableDataRecord(record.id);
    } else {
      await deleteBandingBandingTaskClass([record.id]);
    }
  };

  const handleSave = async (record: EditRecordRow) => {
    const valid = await record.onValid?.();
    if (valid) {
      const data = cloneDeep(record.editValueRefs);
      data['isOrderClass'] = data['isOrderClass'] ? 1 : 0;
      if (record._newRow) {
        await postBandingBandingTaskClass({
          ...data,
          bandingTaskId: props.taskId,
        } as API.AddBandingTaskClassDto);
      } else {
        const _dataSource = getDataSource();
        const editData = _dataSource.filter((row) => row.id === record.id)[0];
        Object.assign(editData, data);
        await putBandingBandingTaskClass(editData as API.UpdateBandingTaskClassDto);
      }
      await record.onEdit?.(false, true);
      currentEditKeyRef.value = '';
      reload();
    } else {
      createMessage.error({ content: '请填写正确的数据', key: 'saving' });
    }
  };

  const createActions = (record: EditRecordRow): ActionItem[] => {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
          onClick: handleEdit.bind(null, record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '是否删除',
            confirm: handleDelete.bind(null, record),
          },
        },
      ];
    }
    return [
      {
        label: '确定',
        onClick: handleSave.bind(null, record),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
      },
    ];
  };

  const handelImport = () => {
    openImportModal(true, { baseData: { taskId: props.taskId } });
  };

  const handleSuccess = () => {
    reload();
  };

  const validateStep = () => {
    return true;
  };
  const reloadStep = () => {
    reload();
  };

  defineExpose({ validateStep, reloadStep });
</script>

<style lang="less" scoped>
  .dsion-step2 {
    margin: 16px 0;
  }
</style>
