<template>
  <el-dialog
    title="仓库领用成本统计表"
    :visible.sync="visible"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose">
    <div class="statistics-dialog-content">
      <!-- 筛选条件 -->
      <el-row class="search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="right">
          <el-col :span="6">
            <el-form-item label="统计月份">
              <el-date-picker
                v-model="query.StatisticsMonth"
                type="month"
                value-format="yyyyMM"
                format="yyyy年MM月"
                placeholder="请选择月份"
                :style='{"width":"100%"}' />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="门店">
              <el-select
                v-model="query.StoreIds"
                placeholder="请选择门店（不选则统计所有门店）"
                multiple
                filterable
                clearable
                collapse-tags
                :style='{"width":"100%"}'>
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="listLoading"
          :data="list"
          border
          stripe
          :max-height="600">
          <el-table-column prop="StatisticsMonth" label="统计月份" min-width="120" sortable="custom">
            <template slot-scope="scope">
              <i class="el-icon-date" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ formatMonth(scope.row.StatisticsMonth) || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StoreName" label="门店名称" min-width="150" sortable="custom">
            <template slot-scope="scope">
              <i class="el-icon-shop" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ scope.row.StoreName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ReceiveCount" label="领取数量" min-width="120" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-s-data" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.ReceiveCount !== null && scope.row.ReceiveCount !== undefined ? scope.row.ReceiveCount : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ProductVarietyCount" label="领取品种数量" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-goods" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.ProductVarietyCount !== null && scope.row.ProductVarietyCount !== undefined ? scope.row.ProductVarietyCount : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalCostAmount" label="总价" min-width="130" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-money" style="margin-right: 4px; color: #67C23A;"></i>
              <span class="amount-paid">¥{{ formatMoney(scope.row.TotalCostAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AvgUnitPrice" label="平均单价" min-width="120" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-coin" style="margin-right: 4px; color: #909399;"></i>
              <span>¥{{ formatMoney(scope.row.AvgUnitPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="WarehouseCount" label="涉及仓库数量" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-office-building" style="margin-right: 4px; color: #909399;"></i>
              <span>{{ scope.row.WarehouseCount !== null && scope.row.WarehouseCount !== undefined ? scope.row.WarehouseCount : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="UsageRecordCount" label="领用记录数" min-width="130" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-document" style="margin-right: 4px; color: #909399;"></i>
              <span>{{ scope.row.UsageRecordCount !== null && scope.row.UsageRecordCount !== undefined ? scope.row.UsageRecordCount : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AvgReceiveAmount" label="平均领用金额" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-coin" style="margin-right: 4px; color: #67C23A;"></i>
              <span>¥{{ formatMoney(scope.row.AvgReceiveAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AvgRecordAmount" label="平均单笔金额" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-coin" style="margin-right: 4px; color: #67C23A;"></i>
              <span>¥{{ formatMoney(scope.row.AvgRecordAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalUsageQuantity" label="领用总数量" min-width="130" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-s-data" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.TotalUsageQuantity !== null && scope.row.TotalUsageQuantity !== undefined ? scope.row.TotalUsageQuantity : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MaxRecordAmount" label="最大单笔金额" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-top" style="margin-right: 4px; color: #F56C6C;"></i>
              <span>¥{{ formatMoney(scope.row.MaxRecordAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MinRecordAmount" label="最小单笔金额" min-width="140" sortable="custom" align="right">
            <template slot-scope="scope">
              <i class="el-icon-bottom" style="margin-right: 4px; color: #409EFF;"></i>
              <span>¥{{ formatMoney(scope.row.MinRecordAmount) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="search"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'StoreReceiveCostStatisticsDialog',
  components: {
    Pagination
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    storeOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      query: {
        StatisticsMonth: undefined,
        StoreIds: []
      },
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.setDefaultMonth()
        this.search()
      }
    }
  },
  methods: {
    // 设置默认月份（当前月份）
    setDefaultMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      this.query.StatisticsMonth = `${year}${month}`
    },

    // 查询数据
    search() {
      this.listLoading = true

      const params = {
        currentPage: this.listQuery.currentPage,
        pageSize: this.listQuery.pageSize
      }

      if (this.query.StatisticsMonth) {
        params.StatisticsMonth = this.query.StatisticsMonth
      }

      if (this.query.StoreIds && this.query.StoreIds.length > 0) {
        params.StoreIds = this.query.StoreIds
      }

      request({
        url: '/api/Extend/LqInventoryUsage/get-store-receive-cost-statistics',
        method: 'POST',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          this.list = res.data.list
          this.total = (res.data.pagination && res.data.pagination.total) || res.data.list.length || 0
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
        this.list = []
        this.total = 0
      })
    },

    // 重置查询条件
    reset() {
      this.query = {
        StatisticsMonth: undefined,
        StoreIds: []
      }
      this.setDefaultMonth()
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.list = []
      this.total = 0
      this.search()
    },

    // 格式化月份（YYYYMM -> YYYY年MM月）
    formatMonth(month) {
      if (!month || month.length !== 6) return month
      const year = month.substring(0, 4)
      const monthNum = month.substring(4, 6)
      return `${year}年${monthNum}月`
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 处理关闭
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-dialog-content {
  .search-box {
    margin-bottom: 20px;
  }

  .table-container {
    min-height: 400px;
  }
}

.amount-paid {
  color: #67C23A;
  font-weight: 500;
}
</style>
