<template>
  <div>
    <div class="header">
      <SvgIcon size="19" name="list" />
      <div class="title">任务列表</div>
    </div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" :icon="h(PlusOutlined)">新 增</a-button>
        <div style="width: 5px" />
        <a-button type="default" :icon="h(EyeOutlined)" @click="handleOpenFileDialog(null)">OCR识别</a-button>
        <input type="file" ref="fileInput" accept="application/pdf" aria-hidden="true" @change="handleFileChange" style="display: none;" />
        <div style="width: 5px" />
        <a-button type="default" @click="handleDownload" :icon="h(DownloadOutlined)" :disabled="checkedKeys.length === 0">下发数据</a-button>
        <a-button type="default" @click="handleSync" :icon="h(SyncOutlined)" :disabled="checkedKeys.length === 0">同步数据</a-button>
      </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,
                disabled: record.state !== 0
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
                ifShow: hasPermission('AUTH_DATA_TASK:DELETE'),
                disabled: record.state !== 0,
                divider: true,
              },
              {
                label: '结果查看',
                icon: 'ant-design:eye-outlined',
                onClick: handleView.bind(null, record),
                divider: true,
              },
              {
                label: '下发数据',
                icon: 'ant-design:download-outlined',
                onClick: handleDownload.bind(null, record),
                divider: true,
                disabled: record.state !== 0 || !getDeviceConnected(record.deviceSn)
              },
              {
                label: '同步数据',
                icon: 'ant-design:sync-outlined',
                onClick: handleSync.bind(null, record),
                divider: true,
                disabled: !getDeviceConnected(record.deviceSn)
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <TaskDrawer ref="taskDrawer" @register="registerDrawer" @success="handleSuccess" @ocrClick="handleOpenFileDialog" />
    <PdfViewer ref="pdfView" @onCapture="handleCapture" />
    <Result @register="register" />
  </div>
</template>
<script lang="ts" setup>
import { usePermission } from '@/hooks/web/usePermission';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { isObject } from '@/utils/is';
  import dayjs from 'dayjs';
  import * as TaskApi from '@/api/data/taskApi';
  import { useDrawer } from '@/components/Drawer';
  import TaskDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import {SvgIcon} from "@/components/Icon";
  import {h, ref} from "vue";
  import { onMounted, onUnmounted, computed } from "vue";
  import {
    DownloadOutlined,
    EyeOutlined,
    PlusOutlined,
    SyncOutlined
  } from "@ant-design/icons-vue";
  import PdfViewer from "@/components/PdfViewer/index.vue";
  import {useModal} from "@/components/Modal";
  import Result from "@/views/data/task/result.vue";

  const [register, { openModal }] = useModal();

  const taskDrawer = ref<typeof TaskDrawer>();
  const { hasPermission } = usePermission();
  const checkedKeys = ref<Array<string | number>>([]);
  const onSelectChange = (selectedRowKeys: (string | number)[]) => {
    checkedKeys.value = selectedRowKeys.filter(k => typeof k !== 'undefined');
  }
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    api: (params) => TaskApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: 0,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    rowSelection: {
      type: 'checkbox',
      onChange: onSelectChange,
      getCheckboxProps: (record) => ({ disabled: record.state !== 0})
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 420,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  const handleParams = (params: any) => {
    const { pageNum, pageSize, field = 'id', order = 'descend', ...rest } = params;
    const handledParams: any = { pageNum, pageSize, orderByClause: `${field} ${order === 'descend' ? 'desc' : 'asc'}` };
    Object.keys(rest).forEach((key) => {
      const schema = searchFormSchema.find((item) => item.field === key);
      const value = params[key];
      let paramKey = key;
      if (schema) {
        if (value !== undefined && value !== '') {
          if (schema.component === 'Input') {
            handledParams[paramKey] = `%${value.trim()}%`;
          } else if (['Select', 'ApiSelect', 'ApiTreeSelect'].includes(schema.component)) {
            handledParams[paramKey] = isObject(value) ? value.value : value;
          } else if (schema.component === 'RangePicker') {
            if (paramKey === 'startTimeQuery') {
              paramKey = 'startTime';
            }
            handledParams[`${paramKey}From`] = dayjs(value[0]).startOf('d').format('YYYY-MM-DD HH:mm:ss');
            handledParams[`${paramKey}To`] = dayjs(value[1]).endOf('d').format('YYYY-MM-DD HH:mm:ss');
          } else if (schema.component === 'DatePicker') {
            handledParams[paramKey] = dayjs(value).format((schema.componentProps as any).format || 'YYYY-MM-DD');
          } else {
            handledParams[paramKey] = value;
          }
        }
      } else {
        handledParams[paramKey] = value;
      }
    });
    return handledParams;
  };

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

  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDelete = (record: Recordable) => {
    TaskApi.remove(record.id).then((_) => {
      reload();
    });
  };

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

  const handleView = (record: any) => {
    const params = JSON.parse(record.paramJson);
    params.forEach(d => {
      const r = Math.ceil(Math.random() * 10) - 3;
      d.l1 = r + parseInt(d.w);
      d.l2 = r + parseInt(d.h);
      d.l3 = r + parseInt(d.w);
      d.l4 = r + parseInt(d.h);
      const x = parseInt(d.x) + d.l1 / 2;
      const y = parseInt(d.y) + d.l2 / 2;
      d.c = x + ' , ' + y;
      d.result = r >= -2 && r <= 5 ? 'OK' : 'NG';
    });
    record.resultJson = JSON.stringify(params);
    openModal(true, {record});
  };

  let ocrData = null;
  const fileInput = ref<HTMLInputElement>();
  const handleOpenFileDialog = (data: any) => {
    ocrData = data;
    fileInput.value?.click();
  };

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

  const pdfView = ref<any>();
  const openPdf = async (pdfData: any) => {
    pdfView.value.pdfData = pdfData;
    await pdfView.value.loadPdf();
    pdfView.value.show();
  };

  const handleCapture = (base64ImageString: any) => {
    WebViewService.setIsLoading(true).then(() => {});
    TaskApi.importImageOCR(base64ImageString).then((res: any) => {
      const data = JSON.parse(res);
      if (data.length === 0) return;
      if (ocrData === null) {
        const record = {
          name: '',
          paramJson: JSON.stringify(data),
        };
        // 打开新增
        openDrawer(true, {
          record,
          isUpdate: false,
        });
      } else {
        taskDrawer.value?.setParamData(data);
      }
      WebViewService.setMessage("数据导入成功！", "success").then(() => {});
    }).catch(() => {
      WebViewService.setMessage("数据导入失败！", "error").then(() => {});
    }).finally(() => {
      WebViewService.setIsLoading(false).then(() => {});
    });
  }

  const handleDownload = (record: Recordable) => {
    const ids = [...new Set([...(record.id ? [record.id] : []), ...(checkedKeys.value.map(d => (d)))])]
    DeviceClientService.assignTasks(ids).then(() => {
      WebViewService.setMessage("下发任务成功！", "success").then(() => {});
    }, (error: any) => {
      WebViewService.setMessage("下发任务失败！", "error").then(() => {});
    });
  };

  const handleSync = (record: Recordable) => {
    const ids = [...new Set([...(record.id ? [record.id] : []), ...(checkedKeys.value.map(d => (d)))])]
    DeviceClientService.syncTasks(ids).then(() => {
      WebViewService.setMessage("同步任务成功！", "success").then(() => {});
      reload();
    }, (error: any) => {
      WebViewService.setMessage("同步任务失败！", "error").then(() => {});
    });
  };

  const deviceConnectedList = ref([])

  const getDeviceConnected = computed(() => {
    return (sn: any) => {
      return deviceConnectedList.value[sn] ? deviceConnectedList.value[sn] : false;
    };
  });

  const timer = ref(0)
  onMounted(()=> {
    timer.value = setInterval(() => {
      DeviceClientService.getDeviceConnected().then((d) => {
        deviceConnectedList.value = d;
      }, error => {
        WebViewService.setMessage("获取设备连接出错", "error").then(() => {});
      });
    }, 300);

    WebViewService.setIsLoading(false).then(() => {});
  });

  onUnmounted(()=> {
    clearInterval(timer.value);
  });
</script>
<style lang="scss" scoped>
  @use '@/assets/custom.scss';
</style>
