<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="960px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" :icon="h(PlusOutlined)">新 增</a-button>
        <div style="width: 5px" />
        <a-button type="primary" :icon="h(EyeOutlined)" @click="handleOpenFileDialog">OCR识别</a-button>
        <div style="width: 5px" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                divider: true,
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
                divider: true,
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <Modal @register="register" @success="updateParamData" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {defineEmits, ref, computed, unref, h} from 'vue';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './schema';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import * as TaskApi from '@/api/data/taskApi';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { EyeOutlined, PlusOutlined } from "@ant-design/icons-vue";
import Modal from "@/views/data/task/modal.vue";
import { useModal } from '/@/components/Modal';
const [register, { openModal }] = useModal();

const columns = [
  {
    title: '序号',
    dataIndex: 'sn',
    key: 'sn',
    width: '50px',
    // customRender: ({ index }) => `${index + 1}`,
  },
  {
    title: '预埋件编号',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: 'X(mm)',
    dataIndex: 'x',
    key: 'x',
    width: '72px',
  },
  {
    title: 'Y(mm)',
    dataIndex: 'y',
    key: 'y',
    width: '72px',
  },
  {
    title: 'w(mm)',
    dataIndex: 'w',
    key: 'w',
    width: '72px',
  },
  {
    title: 'h(mm)',
    dataIndex: 'h',
    key: 'h',
    width: '72px',
  },
  {
    title: '中心点(m)',
    dataIndex: 'center',
    key: 'center',
    width: '80px',
  },
];

const paramData = ref<any>([]);

const emit = defineEmits(['success', 'register', 'ocrClick']);
const isUpdate = ref(true);
const entity = ref();

const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  entity.value = data?.record;
  paramData.value = [];
  const items = entity.value && entity.value.paramJson ? JSON.parse(entity.value.paramJson) : [];
  items.forEach((d: any, index: number) => {
    if (Object.keys(d).includes('sn')) {
      paramData.value.push({...d});
    } else {
      paramData.value.push({ sn: (index + 1) + '', ...d});
    }
  });
  await setFieldsValue({
    ...data.record,
  });
});

const setParamData = (items: any) => {
  if (!paramData.value)
    paramData.value = [];
  items.forEach((d: any) => {
    const items = paramData.value.filter((p: any) => p.code === d.code);
    if (items.length === 0) {
      paramData.value.push({...d});
    }
    else {
      items[0] = {...d};
    }
  });
};

const [registerTable] = useTable({
  title: '预埋件列表',
  columns,
  dataSource: paramData,
  useSearchForm: false,
  showTableSetting: false,
  bordered: true,
  showIndexColumn: false,
  canResize: false,
  pagination: false,
  rowKey: (record: any) => record.code,
  actionColumn: {
    width: 140,
    title: '操作',
    dataIndex: 'action',
    fixed: undefined,
  },
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function handleSubmit() {
  const values = await validate();
  setDrawerProps({confirmLoading: true});
  const {
    ...rest
  } = values;
  const action = !unref(isUpdate) ? TaskApi.add : TaskApi.update;
  const data = !unref(isUpdate)
    ? {
      ...rest,
    }
    : Object.assign({},
      {
        ...unref(entity),
        ...rest,
      },
    );
  let p: any = [];
  paramData.value.forEach((d: any) => {
    delete d.index;
    p.push(d);
  });
  data.paramJson = JSON.stringify(p);
  await action(data);
  closeDrawer();
  emit('success');
  setDrawerProps({confirmLoading: false});
}

const handleCreate = () => {
  openModal(true, { isUpdate: false });
};

const handleEdit = (record: Recordable, index: number) => {
  openModal(true, { record, isUpdate: true });
};

const handleDelete = (record: Recordable) => {
  paramData.value = paramData.value.filter((d: any) => d.code !== record.code);
};

const handleOpenFileDialog = () => {
  const rest = getFieldsValue();
  const data = !unref(isUpdate)
    ? {
      ...rest,
    }
    : Object.assign({},
      {
        ...unref(entity),
        ...rest,
      },
    );
  emit("ocrClick", data);
};

const updateParamData = async (data: any) => {
  paramData.value.forEach((d: any, index: number) => {
    if (d["code"] === data["code"]) {
      paramData.value[index] = { ...data };
    }
  });
}

defineExpose({
  setParamData
});

</script>
<style lang="scss" scoped>
@use '@/assets/custom.scss';
</style>
