<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="业务类型" prop="bizType">
        <el-select
          v-model="queryParams.bizType"
          placeholder="请选择业务类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BROKERAGE_RECORD_BIZ_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="代理商等级" prop="agentLevel">
        <el-select
          v-model="queryParams.agentLevel"
          placeholder="请选择代理商等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in agentLevelList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="支付金额" prop="price">-->
<!--        <el-input-->
<!--          v-model="queryParams.price"-->
<!--          placeholder="请输入订单支付金额，单位：分"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="分红金额" prop="bonus">-->
<!--        <el-input-->
<!--          v-model="queryParams.bonus"-->
<!--          placeholder="请输入分红金额，单位: 分"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="代理商id" prop="agentId">-->
<!--        <el-input-->
<!--          v-model="queryParams.agentId"-->
<!--          placeholder="请输入代理商id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--          class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.tradeOrderStatus" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['agent:order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column   width="180px" label="订单编号" align="center" prop="no" />
      <el-table-column width="180px" label="商品图片" align="center">
        <template v-slot="scope">
          <el-popover
            placement="top-start"
          trigger="click"
          :width="500"
          >
          <!-- 大图预览内容 -->
          <el-image
            :src="scope.row.picUrl"
            style="max-width: 500px; max-height: 500px"
          />

          <!-- 表格中的缩略图 -->
          <template #reference>
            <el-image
              :src="scope.row.picUrl"
              fit="cover"
              style="
            width: 80px;
            height: 80px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          "
              lazy
            >
              <template v-slot:error>
                <div class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
          </template>
          </el-popover>
        </template>
      </el-table-column>

            <el-table-column label="商品信息" width="180px" align="center" prop="spuName">
                <template #default="scope">
                  <div class="wrap-content">{{ scope.row.spuName }}</div>
                  <div class="wrap-content"> x {{scope.row.productCount }}</div>
                </template>
            </el-table-column>
<!--            <el-table-column label="商品价格" align="center" prop="productPrice" :formatter="fenToYuanFormat"/>-->
<!--      <el-table-column label="购买数量" align="center" prop="productCount" />-->
            <el-table-column label="业务类型" align="center" prop="bizType">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.BROKERAGE_RECORD_BIZ_TYPE" :value="scope.row.bizType" />
              </template>
            </el-table-column>
            <el-table-column label="付款金额" align="center" prop="payPrice" :formatter="fenToYuanFormat"/>
<!--            <el-table-column label="标题" align="center" prop="title" />-->
            <el-table-column label="分红金额" align="center" prop="price" :formatter="fenToYuanFormat"/>
<!--            <el-table-column label="描述" align="center" prop="description" />-->
<!--            <el-table-column label="代理商id" align="center" prop="agentId" />
            <el-table-column label="地址" align="center">
              <template #default="{ row }">
                {{ getAreaName(row.areaId) }}
              </template>
            </el-table-column>-->
<!--            <el-table-column label="归属" align="center" prop="agentName" />-->
            <el-table-column label="归属" align="center" width="180px">
              <template #default="{ row }">
                <div>分销用户id: {{ row.userId }} </div>
                <div>代理商名称: {{ row.agentName }}</div>
                <div>代理商等级: {{ getAgentLevelName(row.agentLevel) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="发货状态" align="center" prop="tradeOrderStatus" >
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.tradeOrderStatus" />
              </template>
            </el-table-column>
            <el-table-column
              label="下单时间"
              align="center"
              prop="orderTime"
              :formatter="dateFormatter"
              width="180px"
            />

<!--      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['agent:bonus:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['agent:bonus:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AgentOrderApi, AgentOrderVO } from '@/api/agent/order'
import {InfoApi} from "@/api/agent/info";
import { fenToYuanFormat } from '@/utils/formatter'
import {useRouter,useRoute} from "vue-router";
import * as BrokerageWithdrawApi from "@/api/mall/trade/brokerage/withdraw";
const router = useRouter() // 路由
const route = useRoute();//获取路由名字

/** 代理商分红明细 列表 */
defineOptions({ name: 'AgentBonus' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AgentOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bizId: null, // 业务id
  bizType: null, //业务类型
  title: null,//标题
  description: null, //描述
  price: undefined,
  bonus: undefined,
  agentId: undefined,
  agentLevel: undefined,
  status: undefined,
  payStatus: undefined,
  tradeOrderStatus: undefined,
  createTime: [],
})
const agentLevelList = ref([]);
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const agentId = Number(route.query.agentId)
    console.log("agentId:",agentId)
    if(typeof agentId === 'number' && !Number.isNaN(agentId)){
      queryParams.agentId = agentId
    }
    const data = await AgentOrderApi.getAgenPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getAgentLevelList = async () => {
  const res = await InfoApi.getAgentLevelList()
  agentLevelList.value = res
}

const areaList = ref([]);

const getAreaList = async () => {
  areaList.value = await InfoApi.getAreaList();
  console.log('areaList', areaList);
}

const getAgentLevelName = (id) => {
  const level = agentLevelList.value.find(item => item.id === Number(id));
  return level ? level.name : "未知等级";
};

const getAreaName = (id) => {
  const area = areaList.value.find(item => item.id === Number(id));
  return area ? area.name : "未知地区";

}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.levelId = undefined
  queryParams.agentId = undefined
  route.query.agentId = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AgentOrderApi.exportAgentOrder(queryParams)
    download.excel(data, '分销订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


/** 初始化 **/
onMounted(() => {
  getList()
  getAgentLevelList()
})
</script>
<style scoped>
.wrap-content {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}
</style>
