<template>
  <div class="wait-check">
    <div class="page-action">
      <t-button
        v-if="perm.BUTTON_BatchPass"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleAudit(selectedRowKeys, true)"
      >
        <template #icon><svg-icon name="right-circle" color="#fff" /></template
        >批量通过
      </t-button>
      <t-button
        v-if="perm.BUTTON_BatchNoPass"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleAudit(selectedRowKeys, false)"
      >
        <template #icon><svg-icon name="wrong-circle" color="#fff" /></template
        >批量拒绝
      </t-button>
    </div>
    <SearchForm :fields="fields" :params="params" showAll :search="search">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :filterParams="{ statusList: ['PUBLISH'] }"
        ></select-service-unit>
      </template>
      <template #supplier="{ item, params }">
        <select-supplier v-model="params[item.prop]"> </select-supplier>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="taskId"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #code="{ col, row }">
          <more-content
            :content="row[col.colKey]"
            @action="handleDetail(row)"
          ></more-content>
        </template>
        <template #backup-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #apply-time="{ col, row }">
          {{ timestampFilter(row[col.colKey]) }}
        </template>
        <template #custom-type="{ col, row }">
          {{ customerTypeFilter(row[col.colKey]) }}
        </template>
        <template #attachmentPaths="{ col, row }">
          <attachment-view
            :imageList="getUrls(row[col.colKey], 'image')"
            :fileList="getUrls(row[col.colKey], 'file')"
            :imgSize="60"
          ></attachment-view>
        </template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop>
            <t-link
              v-if="perm.LINK_Pass"
              theme="primary"
              hover="color"
              @click="handleAudit([row.taskId], true)"
              :disabled="!row.myself"
            >
              通过
            </t-link>
            <t-link
              v-if="perm.LINK_NoPass"
              theme="danger"
              hover="color"
              @click="handleAudit([row.taskId], false)"
              :disabled="!row.myself"
            >
              拒绝
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <!-- AbnormalDetailDialog -->
    <abnormal-detail-dialog
      v-model:visible="showAbnormalDetailDialog"
      :row="curRow"
    ></abnormal-detail-dialog>
  </div>
</template>

<script setup name="WaitCheck">
import { reactive, ref, computed } from 'vue';
import { omit } from 'lodash';

import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import {
  workHoursWaitCheckListApi,
  workHoursWaitCheckAuditApi,
} from '@/api/work-hours';
import { timestampFilter, customerTypeFilter } from '@/utils/filter';
import AbnormalDetailDialog from './abnormal-detail-dialog.vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const selectedRowKeys = ref([]);
const selectChange = (value) => {
  selectedRowKeys.value = value;
};

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'name',
    label: '姓名',
    labelWidth: 55,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'supplierId',
    label: '所属供应商',
    type: 'select',
    labelWidth: 95,
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'customName',
    label: '客户名称',
    labelWidth: 80,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 3,
    children: [
      {
        type: 'button',
        text: '搜索',
        attrs: {
          style: { marginLeft: '0 !important' },
        },
        onClick: () => {
          search();
        },
      },
    ],
  },
  {
    prop: 'exceptionTime',
    label: '异常时间',
    type: 'daterange',
    labelWidth: 70,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'applyTime',
    label: '申请时间',
    type: 'daterange',
    labelWidth: 95,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
]);
const params = reactive({
  serviceId: '',
  name: '',
  supplierId: '',
  customName: '',
  exceptionTime: [],
  applyTime: [],
});
const computedParams = computed(() => {
  let data = omit(params, ['exceptionTime', 'applyTime']);
  data.startTime = params.exceptionTime[0];
  data.endTime = params.exceptionTime[1];
  data.applyStartTime = params.applyTime[0];
  data.applyEndTime = params.applyTime[1];
  return data;
});

const getUrls = (data, type) => {
  const list = data.split(',');
  const imgs = ['jpg', 'png', 'jpeg'];
  if (type === 'image') {
    return list.filter((item) => {
      const evt = item.split('.').slice(-1)[0];
      return imgs.includes(evt);
    });
  } else {
    return list.filter((item) => {
      const evt = item.split('.').slice(-1)[0];
      return !imgs.includes(evt);
    });
  }
};

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
    disabled: ({ rowIndex }) => {
      return !tableData.value[rowIndex].myself;
    },
  },
  { colKey: 'code', title: '异常编号', width: 200 },
  { colKey: 'serviceName', title: '服务单元', width: 140 },
  { colKey: 'sopNo', title: 'SOP流水号', width: 200 },
  { colKey: 'createRealName', title: '姓名', width: 140 },
  { colKey: 'supplierName', title: '供应商', width: 140 },
  { colKey: 'customName', title: '客户名称', width: 140 },
  { colKey: 'customType', title: '客户类型', cell: 'custom-type', width: 120 },
  { colKey: 'dingExceptionTypeStr', title: '异常类型', width: 120 },
  { colKey: 'exceptionTime', title: '异常日期', width: 140 },
  { colKey: 'applyTime', title: '补卡时间', cell: 'backup-time', width: 180 },
  { colKey: 'reason', title: '理由' },
  {
    colKey: 'attachmentPaths',
    title: '附件/截图',
    minWidth: 240,
  },
  { colKey: 'statusStr', title: '审核状态', width: 120 },
  { colKey: 'approveUserName', title: '当前审核人', width: 140 },
  { colKey: 'createTime', title: '申请时间', cell: 'apply-time', width: 180 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 120,
  },
];
const { pagination, tableData, fetchData, search, onChange } = useFetchTable(
  workHoursWaitCheckListApi,
  {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
    },
    params: computedParams,
  }
);

const showAbnormalDetailDialog = ref(false);
const curRow = ref(null);
const handleDetail = async (row) => {
  curRow.value = row;
  showAbnormalDetailDialog.value = true;
};

const handleAudit = async (selectedIds, pass) => {
  if (!selectedIds.length) {
    MessagePlugin.error('请选择要通过的记录');
    return;
  }

  const actionName = pass ? '通过' : '拒绝';
  const warningBody =
    selectedIds.length > 1
      ? `确定要${actionName}当前选择的所有记录吗`
      : `确定要${actionName}当前记录吗`;

  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: warningBody,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      let data = { dingExceptionApprove: pass ? 'PASS' : 'NO_PASS' };
      const isBatch = selectedIds.length > 1;
      if (isBatch) {
        data.taskIds = selectedIds;
      } else {
        data.taskId = selectedIds[0];
      }

      const res = await workHoursWaitCheckAuditApi(data, isBatch).catch(
        () => {}
      );
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
</script>
