<template>
  <a-card>
    <a-button style="margin-bottom: 30px" type="primary" @click="back">返回</a-button>
    快送员订单
    <div class="data-box">
      <div style="display: flex;justify-content: space-around">
        <a-descriptions :column=3 style="width: 85%">
          <a-descriptions-item label="快送员姓名">{{ errandData?.errandName }}</a-descriptions-item>
          <a-descriptions-item label="配送单位">{{ errandData?.distributionScope }}</a-descriptions-item>
          <a-descriptions-item label="联系方式">{{ errandData?.errandPhone }}</a-descriptions-item>
          <a-descriptions-item label="银行卡号">{{ errandData?.bankCard }}</a-descriptions-item>
          <a-descriptions-item label="当前接单量">{{ errandData?.totalOrders }}</a-descriptions-item>
          <a-descriptions-item label="最大送单量">{{ errandData?.maxOrders }}</a-descriptions-item>
        </a-descriptions>
        <div style="width: 15%;display: flex;white-space: nowrap">
          图片：
          <div style="width: 45%">
            <a-image :src="errandData.errandAvatarUrl"/>
          </div>
        </div>
      </div>
    </div>
    <div class="search-box" style="margin-top: 2%;display: inline-block;width: 100%">
      <div style="display: flex;justify-content: space-between;margin-bottom: 2%">
        <!-- 查询信息 -->
        <a-form layout="inline">
          <a-space>
            <a-input-search
                style="width: 400px"
                placeholder="请输入订单号"
                enter-button
                allow-clear
                @search="onSearch"
            />
            <a-select
                v-model:value="searchParams.state"
                style="width: 120px"
                @change="getOrdersList(1)"
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="0">未支付</a-select-option>
              <a-select-option value="1">已支付</a-select-option>
              <a-select-option value="2">已退款</a-select-option>
              <a-select-option value="3">已取消</a-select-option>
              <a-select-option value="4">已出餐</a-select-option>
              <a-select-option value="5">已完成</a-select-option>
            </a-select>
          </a-space>
        </a-form>
        <a-space>
          <!-- 导出信息 -->
          <a-button type="primary" @click="download">EXCEL导出</a-button>
          <!--筛选时间-->
          <a-range-picker @change="searchTime" format="YYYY-MM-DD"/>
        </a-space>
      </div>
      <!-- 数据展示部分 -->
      <a-table
          :scroll="{ x: 800, y: 1000 }"
          :data-source="tableData"
          :columns="columns"
          :rowKey="(record: any) => record.id"
          :pagination=false
          :loading="loading"
          bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <div v-if="record.state === 0">
              <a-tag color="purple">未支付</a-tag>
            </div>
            <div v-else-if="record.state === 1">
              <a-tag color="blue">已支付</a-tag>
            </div>
            <div v-else-if="record.state === 2">
              <a-tag color="red">已退款</a-tag>
            </div>
            <div v-else-if="record.state === 3">
              <a-tag color="gray">已取消</a-tag>
            </div>
            <div v-else-if="record.state === 4">
              <a-tag color="blue">已出餐</a-tag>
            </div>
            <div v-else-if="record.state === 5">
              <a-tag color="green">已完成</a-tag>
            </div>
          </template>
          <template v-if="column.key === 'totalPrice'">
            <a-tag color="purple">{{ record.totalPrice }}</a-tag>
          </template>
          <template v-if="column.key === '操作'">
            <a-space>
              <a-button size="small"
                        type="link"
                        style="color: rgba(255, 141, 26, 1);"
                        @click="router.push({path:'/orderDetail',query:{id:record.id}})">查看
              </a-button>
              <a-button v-if="[1, 4, 5].includes(record.state)"
                        size="small"
                        type="link"
                        style="color: rgba(255, 141, 26, 1);"
                        @click="modalOpen = true; recordId=record.orderNo">退款
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <!--订单金额信息 -->
    <div style="margin: 20px 0 20px 0;float: left;">
      <span class="ant-pagination-total-text">总金额：{{ ordersCount }}元</span>
    </div>
    <!-- 分页部分 -->
    <div class="pagination">
      <a-pagination v-model:current="searchParams.current"
                    v-model:pageSize="searchParams.pageSize"
                    show-size-changer
                    show-quick-jumper
                    :total="total"
                    :show-total="() => `共 ${total} 条订单`"
                    @change="onChange"
                    @showSizeChange="onShowSizeChange"
      />
    </div>
    <!--退款弹出框-->
    <a-modal v-model:open="modalOpen" title="退款" destroyOnClose @ok="refund()">
      <span>确定退款吗</span>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {message} from "ant-design-vue";
import {useRoute} from "vue-router";
import {formatTime} from "../../utils/TableConfig";
import router from "../../router";
import myAxios from "../../api/myAxios.ts";

const route = useRoute();
//订单信息
const tableData: any = ref([])
//店铺信息
const errandData: any = ref({})
//订单总金额
const ordersCount: any = ref<Number>()
//加载按钮
const loading = ref(false)
//弹出框开关
const modalOpen = ref<boolean>(false);
//退款id
const recordId = ref<Number>();
// 分页
const total: any = ref(0);
//查询条件
const searchParams: any = ref({
  current: 1,
  pageSize: 10,
  orderId: null,
  searchTime: null,
  state: ''
})

const columns: any = [
  {title: '订单号', dataIndex: 'id', key: 'id', width: 100, fixed: 'left', align: 'center'},
  {
    title: '下单时间', dataIndex: 'createTime', key: 'createTime', width: 100, align: 'center',
    customRender: (row: any) => {
      return formatTime(row)
    }
  },
  {title: '卖家昵称', dataIndex: 'userName', key: 'userName', width: 150, align: 'center'},
  {title: '支付状态', dataIndex: 'state', key: 'state', width: 150, align: 'center'},
  {title: '订单金额', dataIndex: 'totalPrice', key: 'totalPrice', width: 150, align: 'center'},
  {title: '操作', key: '操作', fixed: 'right', width: 80, align: 'center'},
];

onMounted(() => {
  getOrdersList(1)
  getBusinessVO()
  getOrdersCount()
})

/**
 * 获取订单信息列表
 */
console.log(route.query.id)
const getOrdersList = async (current: any) => {
  let errandId = route.query.id; //商家id
  loading.value = true;
  const res: any = await myAxios.post('/orders/list/page', {
    errandId: errandId,
    businessId: "",
    current: current,
    pageSize: searchParams.value.pageSize,
    id: searchParams.value.orderId,
    sortField: "createTime",
    sortOrder: "descend",
    state: searchParams.value.state,
    startTime: searchParams.value.searchTime == null ? '' : searchParams.value.searchTime[0],
    endTime: searchParams.value.searchTime == null ? '' : searchParams.value.searchTime[1]
  })
  if (res.code === 0 && res.data) {
    searchParams.value.current = current
    tableData.value = res.data.records;
    total.value = parseInt(res.data.total);
    loading.value = false;
  } else {
    console.log("没有获取订单")
    console.log(res.data)
    message.error(`获取数据失败：${res.description}`);
    back()
  }
}

/**
 * 获取店铺信息
 */
const getBusinessVO = async () => {
  let errandId:any = route.query.id;
  if (!errandId) {
    console.error("商家ID未定义或为空");
    return;
  }

  const formData = new URLSearchParams();
  formData.append('errandId1', errandId);

  try {
    const res:any = await myAxios.post('/errand/get/id', formData.toString(), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (res.code === 0 && res.data) {
      console.log(res)
      errandData.value = res.data;
    } else {
      console.log(res)
      message.error(`获取数据失败：${res.description}`);
      back();
    }
  } catch (error) {
    console.error('请求异常：', error);
    message.error('接口请求异常，请检查控制台');
  }
}
/**
 * 获取该店铺收入
 */
const getOrdersCount = async () => {
  let errandId = route.query.id; //商家id
  const res: any = await myAxios.post('/orders/count', {
    "errandId": errandId,
    "type": "money",
    "state": 5
  })
  if (res.code === 0 && res.data) {
    console.log(res)
    ordersCount.value = res.data;
  } else {
    message.error(`获取数据失败：${res.description}`);
    back()
  }
}

/**
 * 导出Excel表
 */
const download = async () => {
  let errandId = route.query.id //商家id
  const res: any = await myAxios.post('/orders/download/errand', {
        errandId: errandId,
        // 添加时间参数（与列表查询保持一致）
        startTime: searchParams.value.searchTime?.[0] || '',
        endTime: searchParams.value.searchTime?.[1] || '',
        // 保留其他必要参数
        current: searchParams.value.current,
        pageSize: searchParams.value.pageSize,
        sortField: "createTime",
        sortOrder: "descend"
      },
      {
        responseType: "blob"
      }
  )
  downloadCallback(res, '快送员订单信息表.xlsx')
}

/**
 * 退款
 */
// const refund = async () => {
//   const res: any = await myAxios.get('/Alipay/test/refund', {orderNo: recordId.value})
//   if (res.code === 0 && res.data) {
//     message.success('退款成功');
//     modalOpen.value = false
//     await getOrdersList(1)
//     await getOrdersCount()
//   } else {
//     message.error(`退款失败：${res.description}`);
//   }
// }
const refund = async () => {
  const res: any = await myAxios.get(`/Alipay/test/refund?orderNo=${recordId.value}`);
  if (res.code === 0 && res.data) {
    message.success('退款成功');
    modalOpen.value = false;
    await getOrdersList(1);
    await getOrdersCount();
  } else {
    message.error(`退款失败：${res.description}`);
  }
}
/**
 * 查询
 */
const onSearch = async (ordersId: number) => {
  searchParams.value.orderId = ordersId
  await getOrdersList(1)
}

/**
 * 查询时间
 */
const searchTime = async (dateTime: any) => {
  searchParams.value.searchTime = dateTime
  await getOrdersList(1)
}

/**
 * 分页
 */
const onShowSizeChange = (current: number, pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  getOrdersList(current);
}
const onChange = (pageNumber: number) => {
  searchParams.value.current = pageNumber;
  getOrdersList(pageNumber);
}

/**
 * 返回
 */
const back = () => {
  router.back()
}

//生成下载文件
const downloadCallback = (res: any, fileName: any) => {
  const blob = new Blob([res]);
  if ("download" in document.createElement("a")) {
    // 非IE下载
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
  }
}

</script>

<style scoped>

</style>
