<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          value-format="yyyy-MM-dd" :picker-options="pickerOptions" @change="handleDateRangeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属来源" prop="storeId">
        <el-select v-model="queryParams.orgId" placeholder="请选择" clearable>
          <el-option v-for="store in storeOptions" :key="store.id" :label="store.name" :value="store.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品类别" prop="goodsType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择商品类别" clearable>
          <el-option v-for="dict in goodsTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="statisticsList" border>
      <el-table-column label="商品图片" align="center" width="100">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.goodsImg" :preview-src-list="[scope.row.goodsImg]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="实际销售数量" align="center" prop="actualSaleCount" />
      <el-table-column label="实际销售金额" align="center" prop="actualSaleAmount">
        <template slot-scope="scope">
          {{ scope.row.actualSaleAmount ? scope.row.actualSaleAmount.toFixed(2) : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="saleCount" />
      <el-table-column label="销售金额" align="center" prop="saleAmount">
        <template slot-scope="scope">
          {{ scope.row.saleAmount ? scope.row.saleAmount.toFixed(2) : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="退款数量" align="center" prop="refundCount" />
      <el-table-column label="退款金额" align="center" prop="refundAmount">
        <template slot-scope="scope">
          {{ scope.row.refundAmount ? scope.row.refundAmount.toFixed(2) : 0 }}
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script>
import { listStatistics } from '@/api/order/goods'
import { listStore } from "@/api/system/store"

export default {
  name: "GoodsStatistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统计列表
      statisticsList: [],
      // 门店选项
      storeOptions: [],
      // 商品类别选项
      goodsTypeOptions: [
        { value: '1', label: '普通商品' },
        { value: '2', label: '生活服务' },
        { value: '3', label: '汽车美容' }
      ],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: null,
        endTime: null,
        orgId: null,
        goodsType: null,
        goodsName: null
      },
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近半个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    // 设置默认日期范围为最近半个月
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 15)
    this.dateRange = [this.formatDate(start), this.formatDate(end)]
    this.queryParams.startTime = this.dateRange[0]
    this.queryParams.endTime = this.dateRange[1]

    this.getList()
    this.getStoreOptions()
  },
  methods: {
    /** 格式化日期为 yyyy-MM-dd */
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    /** 日期范围变化处理 */
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }
    },
    /** 查询统计列表 */
    getList() {
      this.loading = true
      listStatistics(this.queryParams).then(response => {
        this.statisticsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取门店选项 */
    getStoreOptions() {
      listStore().then(response => {
        this.storeOptions = response.rows
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置日期范围为最近半个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 15)
      this.dateRange = [this.formatDate(start), this.formatDate(end)]
      this.queryParams.startTime = this.dateRange[0]
      this.queryParams.endTime = this.dateRange[1]
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有商品销售统计数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.download('/mapi/order/goods/statistics/export', {
          ...this.queryParams
        }, `商品销售统计_${new Date().getTime()}.xlsx`)
      })
    }
  }
}
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
