<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import { objectClean } from '@/utils';
import { fetchQueryChannelList, fetchQueryAlipayOrderList, fetchDownloadOrderTemplate, fetchDownloadOrders, fetchUploadOrderExpressInfo } from '@/service/api';
import { Icon } from '@iconify/vue';
import {PAGINATION_PAGE_SIZES} from '@/const/index'

const orderStatusOptions = [
  { label: '待支付', value: '00' },
  { label: '支付中', value: '01' },
  { label: '支付完成', value: '02' },
  { label: '已发货', value: '03' },
  { label: '已关闭', value: '05' },
]

// 应用类型 01:h5 02:公众号 3:微信小程序 04:支付宝-h5 05:支付宝小程序	
const appTypeOptions = [
  { label: 'h5', value: '01' },
  { label: '公众号', value: '02' },
  { label: '微信小程序', value: '03' },
  { label: '支付宝-h5', value: '04' },
  { label: '支付宝小程序', value: '05' },
]
const channelOptions = ref([])
async function getChannelList() {
  const res = await fetchQueryChannelList({
    pageNum: 1,
    pageSize: 100
  })
  console.log(res)
  if(res.data) {
    channelOptions.value = res.data?.data?.records || []
  }
}

const pagination = ref({
  pageSize: 10,
  itemCount: 0,
  pageNum: 1
});
function handlePageUpdate(page: number) {
  pagination.value.pageNum = page;
  getListData();
}
function handlePageSizeUpdate(pageSize: number) {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize;
  getListData();
}

function createQueryParams() {
  return {
    orderId: '',
    mobile: '',
    createTime: null,
    startCreateTime: '',
    endCreateTime: '',
    orderStatus: null,
    appType: null,
    channelCode: null
  };
}

/** 检索 */
function handleQuery() {
  getListData();
}
/** 重置检索 */
function handleResetQuery() {
  queryParams.value = { ...createQueryParams() };
  getListData();
}

const listData = ref([]);

const queryParams = ref(createQueryParams());

const loading = ref(false);

async function getListData() {
  loading.value = true;
  const { pageNum, pageSize } = pagination.value;
  const { orderId, mobile, createTime, orderStatus, appType, channelCode } = queryParams.value;
  const params = {
    orderId,
    mobile,
    orderStatus,
    appType, 
    channelCode,
    startCreateTime: createTime ? `${createTime[0]} 00:00:00` : '',
    endCreateTime: createTime ? `${createTime[1]} 23:59:59` : '',
    pageNum,
    pageSize
  };
  const { data } = await fetchQueryAlipayOrderList(objectClean(params));
  if (data?.ok) {
    listData.value = data.data.records;
    pagination.value.itemCount = data.data.total;
  }
  loading.value = false;
}

const showModal = ref(false)
const currentRow = ref<any>({})
function handleShowModal(row: any, type: string) {
  showModal.value = true
  currentRow.value = row
}

function filterOrderStatus(value: string) {
  const item = orderStatusOptions.find((item) => item.value === value);
  return item ? item.label : '';
}

function filterAppType(value: string) {
  const item = appTypeOptions.find((item) => item.value === value);
  return item ? item.label : '';
}

const downloadOrdersLoading = ref(false)
async function downloadOrders() {
  downloadOrdersLoading.value = true
  const { pageNum, pageSize } = pagination.value;
  const { orderId, mobile, createTime, orderStatus } = queryParams.value;
  const params = {
    orderId,
    mobile,
    orderStatus,
    startCreateTime: createTime ? `${createTime[0]} 00:00:00` : '',
    endCreateTime: createTime ? `${createTime[1]} 23:59:59` : '',
    pageNum,
    pageSize
  };
  const res = await fetchDownloadOrders(objectClean(params))
  downloadFile(res.data, `订单信息_${new Date().getTime()}.xlsx`)
  downloadOrdersLoading.value = false
}
const downloadTemplateLoading = ref(false)
async function downloadTemplate() {
  downloadTemplateLoading.value = true
  const res = await fetchDownloadOrderTemplate()
  
  downloadFile(res.data,`快递模板_${new Date().getTime()}.xlsx`)

  downloadTemplateLoading.value = false
}

const upload = ref()
const importLoading = ref(false)
function handleGetFileData() {
  importLoading.value = true
  nextTick(async () => {
    const formData = new FormData();
    formData.append('file', upload.value.files[0]);
    const res = await fetchUploadOrderExpressInfo(formData)
    console.log(res)
    if(res.data?.ok) {
      window.$message.success('导入成功')
      getListData()
    }
    importLoading.value = false
  });
}
function importExpressInfo() {
  upload.value.value = "";
  upload.value.click();
}

function downloadFile(data: any, fileName: string) {
  // 创建一个链接元素用于下载
  const url = window.URL.createObjectURL(new Blob([data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName); // 文件名和扩展名
  document.body.appendChild(link);
  link.click();

  // 清理和释放URL对象
  link.parentNode?.removeChild(link);
  window.URL.revokeObjectURL(url);
  window.$message.success('下载成功')
}

onMounted(() => {
  getListData();
  getChannelList()
});
</script>
<template>
  <div>
    <input
      ref="upload"
      accept=".xlsx"
      type="file"
      name="upload"
      style="display: none"
      @change="handleGetFileData"
    />
    <n-card class="h-full shadow-sm rounded-8px">
      <n-grid cols="1 s:2 m:3 l:4 xl:5 2xl:6" responsive="screen" x-gap="12" y-gap="12">
          <n-grid-item>
            <p class="mb-6px">订单编号：</p>
            <n-input clearable v-model:value="queryParams.orderId" placeholder="订单编号"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">订单状态：</p>
            <n-select v-model:value="queryParams.orderStatus" clearable placeholder="订单状态" :options="orderStatusOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">下单平台：</p>
            <n-select v-model:value="queryParams.appType" clearable placeholder="下单平台" :options="appTypeOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">渠道来源：</p>
            <n-select 
              label-field="channelName"
              value-field="channelCode"
              v-model:value="queryParams.channelCode" clearable placeholder="渠道来源" :options="channelOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">手机号：</p>
            <n-input clearable v-model:value="queryParams.mobile" placeholder="手机号"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">创建时间：</p>
            <n-date-picker
              v-model:formatted-value="queryParams.createTime"
              :actions="[]"
              close-on-select
              value-format="yyyy-MM-dd"
              placeholder="创建时间"
              type="daterange"
              start-placeholder="开始"
              end-placeholder="结束"
              clearable
            />
          </n-grid-item>
          <n-grid-item class="flex items-end">
            <n-space>
              <n-button secondary strong type="primary" @click="handleQuery"> 查 询 </n-button>
              <n-button secondary strong @click="handleResetQuery">重 置</n-button>
            </n-space>
          </n-grid-item>
        </n-grid>
    </n-card>
    <n-card class="shadow-sm rounded-8px mt-12px">
      <n-alert closable class="mb-12px" type="warning">
      下载订单后完善快递名称和物流单号、发货时间后导入即可
    </n-alert>
      <n-space class="mb-12px">
        <n-button :loading="downloadOrdersLoading" secondary strong type="primary" @click="downloadOrders"> 下载订单 </n-button>
        <!-- <n-button :loading="downloadTemplateLoading" secondary strong @click="downloadTemplate">下载快递模板</n-button> -->
        <n-button :loading="importLoading" secondary strong @click="importExpressInfo">导入快递信息</n-button>
      </n-space>
      <n-spin :show="loading">
        <vxe-table
          :column-config="{ resizable: true }"
          :seq-config="{ startIndex: (pagination.pageNum - 1) * pagination.pageSize }"
          auto-resize
          :row-config="{ isHover: true }"
          stripe
          border
          :data="listData"
        >
        <vxe-column fixed="left" type="seq" title="序号" width="60"></vxe-column>
        <vxe-column fixed="left" min-width="200" field="orderId" title="订单编号"></vxe-column>
        <vxe-column fixed="left" min-width="240" field="productName" title="商品名称"></vxe-column>
        <vxe-column fixed="left" min-width="120" field="productPrice" title="商品单价">
          <template #default="{ row }">
            <span>￥ {{ row.productPrice }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="120" field="productNum" title="商品数量"></vxe-column>
        <vxe-column min-width="120" field="originalPrice" title="订单金额">
          <template #default="{ row }">
            <span>￥ {{ row.originalPrice }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="160" field="discountAmount" title="优惠券抵扣金额">
          <template #default="{ row }">
            <span>￥ {{ row.discountAmount }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="120" field="realPrice" title="实付款">
          <template #default="{ row }">
            <span>￥ {{ row.realPrice }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="120" field="orderStatus" title="订单状态">
          <template #default="{row}">
            <n-tag round :bordered="false" type="warning" v-if="row.orderStatus === '00'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <n-tag round :bordered="false" type="primary" v-else-if="row.orderStatus === '02'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <n-tag round :bordered="false" :color="{ color: 'rgba(32, 128, 240, 0.12)', textColor: '#2080f0' }"  v-else-if="row.orderStatus === '03'">
              {{ filterOrderStatus(row.orderStatus) }}
              </n-tag>
            <n-tag round :bordered="false" v-else-if="row.orderStatus === '04'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <span v-else>{{ filterOrderStatus(row.orderStatus) }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="120" field="recipients" title="收货人信息"></vxe-column>
        <vxe-column min-width="120" field="mobile" title="收货人联系电话"></vxe-column>
        <vxe-column min-width="200" field="provinceName" title="收货人收货地址">
          <template #default="{ row }">
            <span>{{ row.provinceName }} {{ row.cityName }} {{ row.countyName }} {{ row.address }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="200" field="serviceProviders" title="快递"></vxe-column>
        <vxe-column min-width="200" field="expressOrderId" title="物流单号"></vxe-column>
        <vxe-column min-width="200" field="createTime" title="创建时间"></vxe-column>
        <vxe-column min-width="200" field="payEndTime" title="付款时间"></vxe-column>
        <vxe-column min-width="200" field="deliveryTime" title="发货时间"></vxe-column>
        <vxe-column min-width="200" field="channelName" title="渠道来源"></vxe-column>
        <vxe-column min-width="200" field="appType" title="下单平台">
          <template #default="{row}">
            <span>{{ filterAppType(row.appType || '') }}</span>
          </template>
        </vxe-column>
        <!-- <vxe-column field="title" title="操作" fixed="right" min-width="80">
          <template #default="{ row }">
            <n-space>
              <n-button
                  strong
                  text
                  type="info"
                  @click="handleShowModal(row, 'view')"
                  >详情</n-button
                >
            </n-space>
          </template>
        </vxe-column> -->
        <template #empty>
          <icon-custom-empty-data class="text-320px text-primary" />
        </template>
      </vxe-table>
      </n-spin>
      <div v-if="pagination.itemCount !== 0" class="w-full flex justify-end mt-4">
        <n-pagination
          v-model:page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount"
          :page-sizes="PAGINATION_PAGE_SIZES"
          :on-update:page="handlePageUpdate"
          :on-update:page-size="handlePageSizeUpdate"
          show-size-picker
        >
        <template #prefix="{ itemCount, startIndex }">
          <div class="text-[#333]">共 <span class="text-primary">{{ pagination.itemCount }}</span> 条</div>
        </template>
      </n-pagination>
      </div>
    </n-card>
  </div>
</template>
