<template>
  <div class="flex flex-col h-full">
    <div class="page-action">
      <t-space size="small">
        <t-popup v-if="perm.BUTTON_BatchImport" trigger="hover">
          <template #content>
            <t-button
              variant="outline"
              @click="downloadImportTemplate('TEMPLATE_DELIVERY')"
            >
              <template #icon
                ><svg-icon name="export" color="#262626" /></template
              >下载模板
            </t-button>
          </template>
          <upload-button
            upload-url="/api/admin/device/delivery/import"
            :format="['xls', 'xlsx']"
          >
            <t-button variant="outline">
              <template #icon
                ><svg-icon name="import" color="#262626" /></template
              >批量导入
            </t-button>
          </upload-button>
        </t-popup>
        <t-button
          v-if="perm.BUTTON_BatchExport"
          variant="outline"
          @click="multExport"
        >
          <template #icon><svg-icon name="export" color="#262626" /></template
          >批量导出
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchDeliver"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleOperate('DELIVER')"
        >
          <template #icon><svg-icon name="delete" color="#262626" /></template
          >批量发货
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchReceive"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleOperate('RECEIVE')"
        >
          <template #icon><MarkAsUnreadIcon /></template>批量签收
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchCancel"
          variant="outline"
          :disabled="!selectedRowKeys.length"
          @click="handleOperate('CANCEL')"
        >
          <template #icon><CloseOctagonIcon /></template>批量作废
        </t-button>
        <t-button
          v-if="perm.BUTTON_BatchReturn"
          variant="outline"
          @click="handleReturn(selectedRowKeys)"
        >
          <template #icon><RollfrontIcon /></template>批量返还
        </t-button>
      </t-space>
    </div>

    <SearchForm :fields="fields" :params="params" :search="search">
      <template #service="{ item, params }">
        <select-service-unit
          v-model="params[item.prop]"
          :clearable="true"
        ></select-service-unit>
      </template>
      <template #user="{ item, params }">
        <select-url-user
          v-model="params[item.prop]"
          url="/api/admin/device/delivery/delivery_user_list"
          clearable
        ></select-url-user>
      </template>
      <template #supplier="{ item, params }">
        <select-supplier
          v-model="params[item.prop]"
          type="DEVICE"
        ></select-supplier>
      </template>
    </SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        v-loading="loading"
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
        :key="tableKey"
      >
        <template #serviceName="{ row }">
          {{ row.serviceName || '--' }}
        </template>
        <template #crmNo="{ row }">
          {{ row.crmNo || '--' }}
        </template>
        <template #expressPhotoPath="{ row }">
          <image-view
            v-if="row.expressPhotoPath"
            :width="80"
            :height="80"
            :images="[row.expressPhotoPath]"
          ></image-view>
        </template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop v-if="row.effect">
            <t-link
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
              v-if="row.status == 'UN_DELIVER' && perm.LINK_Update"
            >
              修改
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              v-if="row.status == 'UN_DELIVER' && perm.LINK_Cancel"
              @click="handleOperate('CANCEL', [row.id])"
            >
              作废
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              v-if="row.status == 'UN_DELIVER' && perm.LINK_Deliver"
              @click="handleOperate('DELIVER', [row.id])"
            >
              发货
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              v-if="
                row.status == 'DELIVER' &&
                !(row.crmNo && row.deliveryType === 'OUT') &&
                perm.LINK_Receive
              "
              @click="handleOperate('RECEIVE', [row.id])"
            >
              签收
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              v-if="
                row.status == 'RECEIVE' &&
                row.usageType === 'OTHER' &&
                row.deliveryType === 'OUT' &&
                perm.LINK_Return
              "
              @click="handleReturn([row.id], true)"
            >
              返还
            </t-link>
          </div>
        </template>
      </t-table>
    </div>
    <EditDeviceInfoDialog
      v-model:visible="showEditDeviceDialog"
      :curRow="curRow"
      @success="fetchData"
    ></EditDeviceInfoDialog>

    <DeviceTableDialog
      :data="waitReturnData"
      v-model:visible="showWaiReturnDataDialog"
      @success="returnSuccess"
    ></DeviceTableDialog>
  </div>
</template>

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

import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import {
  ErrorCircleFilledIcon,
  RollfrontIcon,
  CloseOctagonIcon,
  MarkAsUnreadIcon,
} from 'tdesign-icons-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import {
  deviceSendStatusUpdateApi,
  deviceSendListApi,
  deviceSendExportApi,
  deviceSendReturn,
} from '@/api/resource-guard';
import {
  DEVICE_SEND_STATUS,
  DEVICE_USAGE_TYPE,
  INOUT_TYPE,
} from '@/config/constants';
import usePermission from '@/hooks/usePermission';
import EditDeviceInfoDialog from './edit-device-info-dialog.vue';
import { dictToOptionList } from '@/utils/tool';
import { downloadImportTemplate } from '@/api/common';
import DeviceTableDialog from '@/views/sop/sop-manage/device-out-in/add-device-dialog.vue';
const { perm } = usePermission();
const tableKey = ref(Date.now() + '');
const curRow = ref(null);
const showEditDeviceDialog = ref(false);

const fields = ref([
  {
    prop: 'serviceId',
    label: '服务单元',
    type: 'select',
    labelWidth: 84,
    colSpan: 6,
    cell: 'service',
  },
  {
    prop: 'usageType',
    label: '用途类型',
    type: 'select',
    labelWidth: 84,
    colSpan: 6,
    options: dictToOptionList(DEVICE_USAGE_TYPE),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'crmNo',
    label: '项目单号',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'status',
    label: '发货状态',
    type: 'select',
    labelWidth: 84,
    colSpan: 6,
    options: dictToOptionList(DEVICE_SEND_STATUS),
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'deliverUserId',
    label: '发货人',
    type: 'select',
    labelWidth: 84,
    colSpan: 6,
    cell: 'user',
  },
  {
    prop: 'deliverTime',
    label: '发货时间',
    labelWidth: 84,
    type: 'daterange',
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'deviceNo',
    label: '设备编号',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'supplierId',
    label: '供应商',
    labelWidth: 84,
    type: 'select',
    colSpan: 6,
    cell: 'supplier',
  },
  {
    prop: 'receiveTime',
    label: '验收时间',
    labelWidth: 84,
    type: 'daterange',
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'serialNo',
    label: '设备序列号',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'consignee',
    label: '收件人',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'mailingAddress',
    label: '收件地址',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'deliveryType',
    label: '出入库状态',
    type: 'select',
    options: dictToOptionList(INOUT_TYPE),
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'brand',
    label: '品牌',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'model',
    label: '型号',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    prop: 'expressNo',
    label: '快递单号',
    labelWidth: 84,
    colSpan: 6,
    attrs: {
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    labelWidth: 0,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
]);

const params = reactive({
  serviceId: '',
  usageType: '',
  crmNo: '',
  status: '',
  deliverUserId: '',
  deliverTime: [],
  deviceNo: '',
  receiveTime: [],
  supplierId: '',
  serialNo: '',
  consignee: '',
  mailingAddress: '',
  deliveryType: '',
  brand: '',
  model: '',
  expressNo: '',
});
const computedParams = computed(() => {
  let data = omit(params, ['deliverTime', 'receiveTime']);
  data.deliverStartTime = params.deliverTime[0];
  data.deliverEndTime = params.deliverTime[1];

  data.receiveStartTime = params.receiveTime[0];
  data.receiveEndTime = params.receiveTime[1];
  return data;
});

const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    fixed: 'left',
  },
  {
    title: '服务单元',
    colKey: 'serviceName',
    width: 140,
    cell: 'serviceName',
  },
  {
    title: '项目单号',
    colKey: 'crmNo',
    width: 140,
    cell: 'crmNo',
  },
  {
    title: '用途',
    colKey: 'usageTypeStr',
    width: 70,
  },
  {
    title: '出库/入库',
    colKey: 'deliveryTypeStr',
    width: 110,
  },
  {
    title: '供应商',
    colKey: 'supplierName',
    width: 140,
  },
  {
    title: '设备编号',
    colKey: 'deviceNo',
    width: 150,
  },
  {
    title: '序列号',
    colKey: 'serialNo',
    width: 150,
  },
  {
    title: '品牌',
    colKey: 'brand',
    width: 100,
  },
  {
    title: '型号',
    colKey: 'model',
    width: 100,
  },
  {
    title: '邮寄地址',
    colKey: 'mailingAddress',
    minWidth: 180,
  },
  {
    title: '收件人',
    colKey: 'consignee',
    width: 90,
  },
  {
    title: '收件人电话',
    colKey: 'consigneePhone',
    width: 130,
  },
  {
    title: '快递单号',
    colKey: 'expressNo',
    width: 150,
  },
  {
    title: '快递单截图',
    colKey: 'expressPhotoPath',
    width: 110,
  },
  {
    title: '发货状态',
    colKey: 'statusStr',
    width: 90,
  },
  {
    title: '发货时间',
    colKey: 'deliverTimeStr',
    width: 180,
  },
  {
    title: '发货人',
    colKey: 'deliverUserName',
    width: 90,
  },
  {
    title: '签收时间',
    colKey: 'receiveTimeStr',
    width: 180,
  },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 160,
  },
];
const { pagination, tableData, fetchData, search, onChange, loading } =
  useFetchTable(deviceSendListApi, {
    fetchDataHandle: () => {
      selectedRowKeys.value = [];
      tableKey.value = Date.now() + '';
    },
    params: computedParams,
  });

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

const handleEdit = (row) => {
  curRow.value = row;
  showEditDeviceDialog.value = true;
};
const waitReturnData = ref([]);
const showWaiReturnDataDialog = ref(false);
const handleReturn = (ids = [], single) => {
  let confirmBody = !ids.length
    ? `确定要返还当所有记录吗？`
    : `确定要返还当前${single ? '' : '选中的'}记录吗？`;
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: confirmBody,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await deviceSendReturn({
        idList: ids,
      }).catch(() => {});
      if (!res) return;
      Array.isArray(res) && (waitReturnData.value = res);
      showWaiReturnDataDialog.value = true;
    },
  });
};
const handleOperate = (status, ids) => {
  let str =
    status === 'DELIVER'
      ? '发货'
      : status === 'RECEIVE'
      ? '签收'
      : status === 'CANCEL'
      ? '作废'
      : '';
  let confirmBody = !ids
    ? `确定要${str}当前选择的所有记录吗？`
    : `确定要${str}当前记录吗？`;
  if (!selectedRowKeys.value.length && !ids) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }

  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: confirmBody,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await deviceSendStatusUpdateApi({
        idList: ids || selectedRowKeys.value,
        status,
      }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const multExport = () => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要导出所有记录吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      deviceSendExportApi(computedParams.value).catch(() => {
        MessagePlugin.error('导出失败');
      });
    },
  });
};
const returnSuccess = () => {
  showWaiReturnDataDialog.value = false;
  fetchData();
};
</script>
