<template>
  <div class="h-full flex flex-col gap-y-3">
    <n-page-header @back="$router.back">
      <template #title> 校准证书 </template>
    </n-page-header>
    <div class="flex-1 grid grid-cols-2 gap-x-3">
      <n-card>
        <!-- <n-list class="h-full">
          <template #header>
            <n-space justify="space-between">
              <h2>校准证书</h2>
              <n-button type="primary" @click="showAddModal">添加</n-button>
            </n-space>
          </template>
          <n-scrollbar
            :style="{ maxHeight: `${height - 300}px` }"
            trigger="none"
          >
            <template v-for="item of dataList" :key="item">
              <n-list-item>
                <template #suffix>
                  <n-popconfirm @positive-click="handleDelete(item)">
                    <template #trigger>
                      <n-button type="error">删除</n-button>
                    </template>
                    是否确认删除？
                  </n-popconfirm>
                </template>
                <n-card
                  embedded
                  :bordered="false"
                  :content-style="{ padding: '5px', textAlign: 'center' }"
                  style="cursor: pointer"
                  @click="handleView(item)"
                >
                  {{ item.slice(item.lastIndexOf('-') + 1) }}
                </n-card>
              </n-list-item>
            </template>
          </n-scrollbar>
        </n-list> -->
        <div class="flex flex-col gap-y-3">
          <div class="self-end">
            <n-button type="primary" @click="showAddModal">添加</n-button>
          </div>
          <n-table :bordered="false">
            <thead>
              <tr>
                <th>布局编号</th>
                <th>设备编号</th>
                <th>证书有效期</th>
                <th>备注</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item of dataList" :key="item">
                <td>
                  <n-input v-model:value="item.split('&')[1]" type="text" />
                </td>
                <td>{{ item.split('&')[2] }}</td>
                <td>{{ item.split('&')[3] }}</td>
                <td>{{ item.split('&')[4] }}</td>
                <td>
                  <n-space>
                    <n-button type="primary" @click="handleView(item)"
                      >查看</n-button
                    >
                    <n-popconfirm @positive-click="handleDelete(item)">
                      <template #trigger>
                        <n-button type="error">删除</n-button>
                      </template>
                      是否确认删除？
                    </n-popconfirm>
                  </n-space>
                </td>
              </tr>
            </tbody>
          </n-table>
        </div>
      </n-card>
      <n-card>
        <div class="flex flex-col gap-y-3">
          <n-descriptions bordered>
            <n-descriptions-item label="报告名称">
              {{ taskInfo.T_name }}
            </n-descriptions-item>
            <n-descriptions-item label="创建时间">
              {{ taskInfo.CreateTime }}
            </n-descriptions-item>
            <n-descriptions-item label="修改时间">
              {{ taskInfo.UpdateTime }}
            </n-descriptions-item>
          </n-descriptions>
          <div class="flex justify-end">
            <n-button text style="font-size: 24px" @click="onPrint">
              <n-icon>
                <printer-icon />
              </n-icon>
            </n-button>
          </div>
          <n-scrollbar
            :style="{ maxHeight: `${height - 380}px` }"
            trigger="none"
          >
            <vue-pdf-embed ref="pdfRef" :source="source" />
          </n-scrollbar>
        </div>
      </n-card>
    </div>
  </div>
  <n-modal
    :show-icon="false"
    v-model:show="modal.showModal"
    preset="dialog"
    :title="modal.title"
    positive-text="确认"
    negative-text="取消"
    @positive-click="getCertificateInfo"
  >
    <n-form :model="formValue" label-width="auto" show-require-mark>
      <n-form-item label="SN" path="T_sn">
        <n-input v-model:value="formValue.T_sn" />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup>
import VuePdfEmbed from 'vue-pdf-embed';
import { PrinterOutlined as PrinterIcon } from '@vicons/antd';
import { getCertificate, getTask, editTask } from '@/api';
import { useWindowSize } from '@vueuse/core';

const { height } = useWindowSize();

const task = window.sessionStorage.getItem('task')
  ? JSON.parse(window.sessionStorage.getItem('task'))
  : {};

const message = useMessage();

const pdfRef = ref(null);

//
const source = ref('');

// 任务信息
const taskInfo = ref({});

//
const dataList = ref([]);

// 模态框数据源
const modal = reactive({
  title: '',
  showModal: false,
});

// 表单数据
const formValue = reactive({
  T_sn: null,
  T_pdf3: '',
});

// 打印pdf
const onPrint = () => {
  pdfRef.value.print();
};

//
const handleView = (row) => {
  source.value = row.split('&')[0];
};

// 删除
const handleDelete = async (row) => {
  try {
    const arr = dataList.value.filter((item) => item !== row);
    const { data: res } = await editTask({
      T_task_id: task.T_task_id,
      T_pdf3: arr.join('|'),
    });
    message.success(res.Msg);
    getTaskInfo();
  } catch (e) {
    console.log(e);
  }
};

// 显示添加
const showAddModal = () => {
  modal.title = '添加设备';
  modal.showModal = true;
};

// 添加
const getCertificateInfo = async () => {
  try {
    const { data: res } = await getCertificate({
      T_sn: formValue.T_sn,
    });
    formValue.T_pdf3 = `${res.Data.T_pdf}&${res.Data.Id}&${res.Data.T_Certificate_sn}&${res.Data.T_failure_time}&1|`;
    editTaskInfo();
  } catch (e) {
    console.log(e);
  }
};

const editTaskInfo = async () => {
  try {
    const { data: res } = await editTask({
      T_task_id: task.T_task_id,
      T_pdf3: taskInfo.value.T_pdf3 + formValue.T_pdf3,
    });
    message.success(res.Msg);
    getTaskInfo();
  } catch (e) {
    console.log(e);
  }
};

// 任务（获取）
const getTaskInfo = async () => {
  try {
    const { data: res } = await getTask({
      T_task_id: task.T_task_id,
    });
    console.log(res);
    taskInfo.value = res.Data || {};
    dataList.value = res.Data.T_pdf3.split('|').filter((item) => item);
    console.log(dataList.value);
  } catch (e) {
    console.log(e);
  }
};

getTaskInfo();
</script>

<style scoped></style>
