<template>
  <!-- 搜索工作栏 -->
  <!-- <div class="search-one">
    <div style="text-align: right;" class="search-input">
      <el-select v-model="queryParams.shopId" placeholder="店铺名称" filterable clearable v-if="!merchantId">
        <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button :icon="Operation" @click="showSearchMore" style="margin-left: 0;" />
    </div>
  </div>

  <div class="searchMore" v-show="searchMoreShow" style="width: calc(100% - 60px);">
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>

      <el-row>
        <el-col>
          <el-form-item>

            <el-button @click="hideSearchMore">
              收起
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button @click="handleQuery" plain type="primary">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>

          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div> -->
  <!-- 列表 -->
  <ContentWrap class="mt-15px">
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @row-click="openForm($event)"
      row-class-name="row"
    >
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="销售额" align="center" prop="platformCollectionAmount">
        <template #default="scope">
          ￥{{ fenToYuan(scope.row.platformCollectionAmount) }}
        </template>
      </el-table-column>

      <el-table-column label="抵扣佣金" align="center" prop="shopHighAmount">
        <template #default="scope">
          {{ pointsToYuan(scope.row.shopAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="抵扣消费分" align="center" prop="shopHighAmount">
        <template #default="scope">
          {{ pointsToYuan(scope.row.consumptionPoints || 0) }}
        </template>
      </el-table-column>
      <el-table-column label="应结(成本)" align="center" prop="shopTotalHighAmount">
        <template #default="scope"> ￥{{ fenToYuan(scope.row.shopTotalHighAmount) }} </template>
      </el-table-column>

      <!-- <el-table-column label="店铺确认转帐完成时间" align="center" prop="shopTransferConfirmTime" :formatter="dateFormatter"
        width="180px" /> -->
      <el-table-column label="转账凭证附件" align="center" prop="attachment">
        <template #default="scope">
          
          <template v-if="scope.row.attachment">
            <!-- 如果有值，显示图片 -->
            <el-image :src="scope.row.attachment"   @click="handleImageClick($event,scope.row.attachment)"/>
          </template>
          <template v-else>
            <!-- 如果没有值，显示导入失败 , 如果是在商户-财务打开的结算单，并且没有图片的话应该显示未结账-->
            <span>{{status === 0 ? '未导入' : merchantId ? '未结账':'导入失败'}}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
        v-if="merchantId"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="success"
            plain
            size="small"
            @click="handleExport($event, scope.row)"
            :loading="exportLoading"
            v-hasPermi="['trade:order:export']"
          >
            导出
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ShopSettlementForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ShopSettlementApi, ShopSettlementVO } from '@/api/system/distri/shopsettlement'
import ShopSettlementForm from './ShopSettlementForm.vue'
import { Setting, Search, Operation } from '@element-plus/icons-vue'
import { fenToYuan, fenToYuan6, pointsToYuan } from '@/utils'
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
let shopList = ref([])
// 获得所有店铺
const getAllShop = async () => {
  loading.value = true
  const res = await AfterSaleApi.getAllShop()
  shopList.value = res
}
const searchMoreShow = ref(false)
// 打开更多搜索条件
const showSearchMore = () => {
  searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
  searchMoreShow.value = false
}
/** 订单结算信息表，记录店铺的结算信息 列表 */
defineOptions({ name: 'ShopSettlement' })

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

const loading = ref(true) // 列表的加载中
const list = ref<ShopSettlementVO[]>([]) // 列表的数据
// 列表的总页数
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  platformCollectionAmount: undefined,
  shopAmount: undefined,
  platformTransferConfirmTime: [],
  shopTransferConfirmTime: [],
  attachment: undefined,
  createTime: [],
  shopId: undefined,
  shopHighAmount: undefined,
  shopTotalHighAmount: undefined,
  ptSettlementId: 0,
  merchantId: undefined
})
const props = defineProps({
  id: {
    type: Number,
    default: undefined
  },
  status:{
    type: Number,
    default: undefined
  },
  merchantId: {
    type: Number,
    default: undefined
  }
})

/** 搜索按钮操作 */
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ShopSettlementApi.getShopSettlementPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (event) => {
  formRef.value.open(event)
}

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await ShopSettlementApi.deleteShopSettlement(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch { }
// }
async function handleImageClick(event,url) {
    // 阻止事件冒泡，避免触发表格行点击事件
    event.stopPropagation(); // 阻止事件冒泡
      try {
        const response = await fetch(url);
        const blob = await response.blob();
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = url.split('/').pop();
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error('Error downloading the image:', error);
      }
  }
/** 导出按钮操作 */
const handleExport = async (event, row) => {
  event.stopPropagation()
  console.log(row)
  // return
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ShopSettlementApi.exportShopOrder({ shopSettlementId: row.id })
    const fileName = row.shopName + formatDate(row.createTime, 'YYYY-MM-DD') + '-结算单.xls'
    download.excel(data, fileName)
  } catch {
  } finally {
    exportLoading.value = false
  }
}
watch(
  () => queryParams.shopId,
  () => {
    getList()
  }
)
/** 初始化 **/
onMounted(() => {
  queryParams.ptSettlementId = props.id
  queryParams.merchantId = props.merchantId
  // console.log(props.merchantId)
  getList()
  getAllShop()
})
</script>
<style src="@/styles/SearchIndex.css" lang="scss" scoped></style>
<style>
.row {
  cursor: pointer;
}
.shopsettlement-dialog > .el-dialog__body {
  padding: 10px;
}
</style>
<style scoped>
::v-deep .el-card__body {
  padding: 10px;
}
</style>
