<template>
  <el-container class="order-view panel-block">
    <el-container class="order-index-main">
      <el-container>
        <el-header class="sa-header">
          <!-- 简化搜索组件 -->
          <div class="search-container">
            <sa-search-simple
              :searchFields="searchFields"
              :defaultValues="defaultSearchValues"
              @search="(val) => getData(1, val)"
              @reset="getData(1)"
            >
              <template #custom="{ data }">
                <el-form-item label="下单时间">
                  <el-date-picker
                    v-model="data.create_time"
                    type="datetimerange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :editable="false"
                    style="width: 350px"
                  />
                </el-form-item>
              </template>
            </sa-search-simple>
          </div>
          <el-tabs class="sa-tabs" v-model="currentStatus" @tab-change="handleTabChange">
            <el-tab-pane label="全部(100)" name="all"></el-tab-pane>
            <el-tab-pane label="待付款(25)" name="unpaid"></el-tab-pane>
            <el-tab-pane label="已付款(15)" name="paid"></el-tab-pane>
            <el-tab-pane label="待发货(30)" name="nosend"></el-tab-pane>
            <el-tab-pane label="待收货(20)" name="noget"></el-tab-pane>
            <el-tab-pane label="已完成(20)" name="completed"></el-tab-pane>
            <el-tab-pane label="已关闭(5)" name="closed"></el-tab-pane>
            <el-tab-pane label="已退款(8)" name="refunded"></el-tab-pane>
            <el-tab-pane label="已取消(12)" name="cancelled"></el-tab-pane>
          </el-tabs>
          <div class="sa-title sa-flex sa-row-between">
            <div class="label sa-flex">
              <span class="left">订单列表</span>
            </div>
            <div>
              <el-button
                class="sa-button-refresh"
                icon="RefreshRight"
                @click="getData()"
              ></el-button>
              <el-button
                :loading="exportLoading"
                :disabled="exportLoading"
                @click="onExport('export')"
                >订单导出</el-button
              >
              <el-button
                v-if="currentStatus == 'nosend'"
                :loading="exportLoading"
                :disabled="exportLoading"
                @click="onExport('exportDelivery')"
                >导出发货单</el-button
              >
            </div>
          </div>
        </el-header>
        <el-main class="sa-p-0">
          <div class="sa-table-wrap" v-loading="loading">
            <el-table
              height="100%"
              class="sa-table"
              :data="table.data"
              @selection-change="changeSelection"
              @sort-change="fieldFilter"
              @row-dblclick="detailRow"
              row-key="id"
              stripe
            >
              <template #empty>
                <sa-empty></sa-empty>
              </template>
              <el-table-column type="selection" width="48" align="center"></el-table-column>
              <el-table-column sortable="custom" prop="order_sn" label="订单编号" min-width="150">
                <template #default="scope">
                  <div class="order-info">
                    <div class="order-sn">{{ scope.row.order_sn }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="商品信息" min-width="280">
                <template #default="scope">
                  <div
                    class="sa-flex sa-row-center"
                    v-if="scope.row.items && scope.row.items.length > 0"
                  >
                    <el-image
                      :src="scope.row.items[0].goods_image"
                      style="width: 60px; height: 60px; margin-right: 12px"
                      fit="cover"
                    />
                    <div>
                      <div class="goods-title">{{ scope.row.items[0].goods_title }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="规格" min-width="120" align="center">
                <template #default="scope">
                  <div v-if="scope.row.items && scope.row.items.length > 0">
                    {{ scope.row.items[0].goods_sku_text || '-' }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>
              <el-table-column prop="goods_num" label="数量" min-width="80" align="center">
                <template #default="scope">
                  {{
                    scope.row.items && scope.row.items.length > 0 ? scope.row.items[0].goods_num : 0
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="user.nickname" label="用户名" min-width="120" align="center">
                <template #default="scope">
                  <div>{{ scope.row.user ? scope.row.user.nickname : '-' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="pay_fee" label="付款金额" min-width="120" align="center">
                <template #default="scope">
                  <div>৳{{ scope.row.pay_fee }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="status_text" label="订单状态" min-width="100" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ scope.row.status_text }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="物流信息" min-width="150" align="center">
                <template #default="scope">
                  <div v-if="scope.row.express_no">
                    <div>{{ scope.row.express_company || '快递公司' }}</div>
                    <div>{{ scope.row.express_no }}</div>
                  </div>
                  <div v-else>{{ scope.row.express_status || '未发货' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="下单时间" min-width="150" align="center">
                <template #default="scope">
                  <div>{{ scope.row.create_time }}</div>
                </template>
              </el-table-column>
              <el-table-column label="付款时间" min-width="150" align="center">
                <template #default="scope">
                  <div>{{ scope.row.pay_time || '-' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="150" fixed="right">
                <template #default="scope">
                  <div class="sa-flex">
                    <el-button
                      v-if="scope.row.btns?.includes('send')"
                      class="is-link"
                      type="primary"
                      @click="onSend(scope.row)"
                      >发货</el-button
                    >
                    <el-button class="is-link" type="primary" @click="detailRow(scope.row.id)"
                      >详情</el-button
                    >
                    <el-button
                      v-if="scope.row.status === 'unpaid'"
                      class="is-link sa-m-l-12"
                      type="danger"
                      @click="cancelOrder(scope.row.id)"
                    >
                      取消
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <el-footer class="order-index-footer">
      <sa-view-bar>
        <template #left>
          <sa-batch-handle
            :batchHandleTools="batchHandleTools"
            :selectedLeng="table.selected.length"
            @batchHandle="batchHandle"
          ></sa-batch-handle>
        </template>
        <template #right>
          <sa-pagination :pageData="pageData" @updateFn="getData" />
        </template>
      </sa-view-bar>
    </el-footer>
  </el-container>
</template>
<script>
  export default {
    name: 'shop.admin.order.order',
  };
</script>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { api } from '../order.service';
  import { useModal, usePagination } from '@/sheep/hooks';
  import OrderDispatch from './dispatch.vue';
  import OrderBatchDispatch from './batchDispatch.vue';
  import OrderDetail from './detail.vue';

  // 搜索字段配置
  const searchFields = reactive({
    order_sn: {
      type: 'input',
      label: '订单编号',
      placeholder: '请输入订单编号',
      width: 200,
    },
    goods_info: {
      type: 'input',
      label: '商品（名称/编号）',
      placeholder: '请输入商品名称或编号',
      width: 200,
    },
    'user.nickname': {
      type: 'input',
      label: '用户名',
      placeholder: '请输入用户名',
      width: 200,
    },
    'user.mobile': {
      type: 'input',
      label: '手机号',
      placeholder: '请输入手机号',
      width: 200,
    },
    express_no: {
      type: 'input',
      label: '物流单号',
      placeholder: '请输入物流单号',
      width: 200,
    },
  });

  // 默认搜索值
  const defaultSearchValues = reactive({
    order_sn: '',
    goods_info: '',
    'user.nickname': '',
    'user.mobile': '',
    express_no: '',
    create_time: [],
  });

  // 当前状态标签
  const currentStatus = ref('all');

  // 标签切换处理
  const handleTabChange = (status) => {
    currentStatus.value = status;
    getData(1, { status: status === 'all' ? '' : status });
  };

  // 获取状态类型
  const getStatusType = (status) => {
    const statusMap = {
      unpaid: 'warning',
      paid: 'info',
      nosend: '',
      noget: '',
      completed: 'success',
      closed: 'danger',
      refunded: 'warning',
      cancelled: 'danger',
    };
    return statusMap[status] || '';
  };

  const loading = ref(true);

  // 表格
  const table = reactive({
    data: [],
    order: 'desc',
    sort: 'id',
    selected: [],
  });

  const { pageData } = usePagination();

  // 获取数据
  async function getData(page, searchParams = {}) {
    loading.value = true;
    try {
      if (page) pageData.page = page;

      // 处理搜索参数
      let search = {};
      if (Object.keys(searchParams).length > 0) {
        // 处理时间范围
        if (searchParams.create_time && searchParams.create_time.length === 2) {
          search.create_time = searchParams.create_time;
        }

        // 处理其他搜索参数
        Object.keys(searchParams).forEach((key) => {
          if (key !== 'create_time' && searchParams[key]) {
            search[key] = searchParams[key];
          }
        });
      }

      const response = await api.order.list({
        page: pageData.page,
        list_rows: pageData.list_rows,
        ...search,
        order: table.order,
        sort: table.sort,
      });

      console.log('API 响应:', response);

      if (response && response.error === 0 && response.data) {
        table.data = response.data.orders.data || [];
        pageData.page = response.data.orders.current_page || 1;
        pageData.list_rows = response.data.orders.per_page || 10;
        pageData.total = response.data.orders.total || 0;
      } else {
        table.data = [];
        console.error('获取订单数据失败:', response);
      }
    } catch (error) {
      console.error('API 调用异常:', error);
      table.data = [];
    }
    loading.value = false;
  }

  // table 字段排序
  function fieldFilter({ prop, order }) {
    table.order = order == 'ascending' ? 'asc' : 'desc';
    table.sort = prop;
    getData();
  }

  // table 批量选择
  function changeSelection(row) {
    table.selected = row;
  }

  // 导出订单/导出发货单
  const exportLoading = ref(false);
  async function onExport(type) {
    exportLoading.value = true;
    try {
      await api.order.export(type, {});
    } catch (error) {
      console.error('导出失败:', error);
    }
    exportLoading.value = false;
  }

  const batchHandleTools = [
    {
      type: 'all',
      label: '批量发货',
      buttonType: 'default',
    },
  ];

  function batchHandle() {
    let order_ids = [];
    table.selected.forEach((s) => {
      order_ids.push(s.id);
    });
    useModal(
      OrderBatchDispatch,
      {
        title: '批量发货',
        order_ids,
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }

  function detailRow(id) {
    useModal(
      OrderDetail,
      {
        title: '订单详情',
        type: 'detail',
        id,
      },
      {
        confirm: () => {
          getData();
        },
        close: () => {
          getData();
        },
      },
    );
  }

  function cancelOrder(id) {
    console.log('取消订单:', id);
    // 这里可以添加取消订单的逻辑
  }

  function onSend(row) {
    useModal(
      OrderDispatch,
      {
        title: '订单发货',
        params: {
          data: row,
        },
      },
      {
        success: () => {
          getData();
        },
      },
    );
  }

  onMounted(() => {
    getData();
  });
</script>
<style lang="scss" scoped>
  .order-view {
    .el-main {
      .sa-table-wrap {
        overflow: hidden;
        height: 100%;
        :deep() {
          .el-table__empty-text {
            margin-left: 0;
          }
        }
        .order-info {
          .order-sn {
            font-size: 14px;
            font-weight: 500;
            color: var(--sa-font);
            margin-bottom: 4px;
            line-height: 1.4;
          }
          .order-time {
            font-size: 12px;
            color: var(--sa-subfont);
            line-height: 1.2;
          }
        }
        .goods-title {
          font-size: 14px;
          font-weight: 500;
          color: var(--sa-font);
          margin-bottom: 4px;
          line-height: 1.4;
        }
        .goods-sku {
          font-size: 12px;
          color: var(--sa-subfont);
          line-height: 1.2;
        }
      }
    }

    .order-index-main {
      overflow: hidden;
    }

    .order-index-footer {
      --el-footer-height: fit-content;
    }

    .search-container {
      .range-input-group {
        display: flex;
        align-items: center;
        gap: 8px;
        width: 100%;

        .el-input {
          flex: 1;
        }

        .range-separator {
          color: var(--el-text-color-regular);
          font-size: 14px;
          white-space: nowrap;
        }
      }
    }
  }
</style>
