<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="900px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #paramJson="{ model }">
        <CodeEditor
          style="height: 500px"
          :auto-height="false"
          v-model:value="model.paramJson"
          @change="model.paramJson = $event;"
        />
      </template>
    </BasicForm>
    <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>
        <input type="file" ref="fileInput" aria-hidden="true" accept="image/bmp,image/jpeg,image/jpg,image/png" @change="handleFileChange" style="display: none;" />
        <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 { CodeEditor } from "@/components/CodeEditor";
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: 'code',
    key: 'code',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: 'X(mm)',
    dataIndex: 'x',
    key: 'x',
    width: '80px',
  },
  {
    title: 'Y(mm)',
    dataIndex: 'y',
    key: 'y',
    width: '80px',
  },
  {
    title: 'w(mm)',
    dataIndex: 'w',
    key: 'w',
    width: '80px',
  },
  {
    title: 'h(mm)',
    dataIndex: 'h',
    key: 'h',
    width: '80px',
  },
];

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

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

const [registerForm, { resetFields, setFieldsValue, validate }] = 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) => {
    paramData.value.push({ index, ...d });
  });
  await setFieldsValue({
    ...data.record,
  });
});

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: 180,
    title: '操作',
    dataIndex: 'action',
    fixed: undefined,
  },
});

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

async function handleSubmit() {
  try {
    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');
  } catch {} finally {
    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 => d.code !== record.code);
};

const fileInput = ref<HTMLInputElement>();
const handleOpenFileDialog = () => {
  fileInput.value?.click();
};

const handleFileChange = (event: any) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      handleImport(e.target!.result);
      fileInput.value!.value = '';
    };
    reader.readAsDataURL(file);
  }
};

const handleImport = (base64ImageString: any) => {
  TaskApi.importImageOCR(base64ImageString).then((res: any) => {
    WebViewService.setMessage("数据导入成功！", "success").then(() => {});
    paramData.value = JSON.parse(res);
  }).catch(() => {
    WebViewService.setMessage("数据导入失败！", "error").then(() => {});
  });
};

const updateParamData = (data: any) => {
  paramData.value[data.index] =  { ...data };
}
</script>
<style lang="scss" scoped>
@use '@/assets/custom.scss';
</style>
