<template>
  <el-dialog title="会员权益" :visible.sync="visible" :close-on-click-modal="false" width="1200px">
    <div v-loading="loading">
      <div class="dialog-header-actions">
        <el-button-group>
          <el-button size="small" icon="el-icon-setting" @click="showColumnDialog = true">字段设置</el-button>
          <el-button size="small" icon="el-icon-camera" @click="handleScreenshot" :loading="screenshotLoading">截图</el-button>
        </el-button-group>
      </div>
      
      <div class="dialog-content" ref="dialogContent">
        <div class="member-info" v-if="memberData.MemberId">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="会员ID">
              <i class="el-icon-postcard"></i>
              {{ memberData.MemberId }}
            </el-descriptions-item>
            <el-descriptions-item label="会员姓名">
              <i class="el-icon-user"></i>
              {{ memberData.MemberName }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="rights-table" ref="rightsTable">
        <el-table 
          :data="memberData.RemainingItems" 
          border 
          style="margin-top: 20px;"
          v-loading="loading"
          empty-text="暂无权益信息"
          show-summary
          :summary-method="getSummaries">
          <el-table-column prop="ItemName" label="项目名称" align="center" min-width="120" v-if="visibleColumns.ItemName">
            <template slot-scope="scope">
              <i class="el-icon-goods"></i>
              {{ scope.row.ItemName || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="ItemPrice" label="单价" align="center" min-width="100" v-if="visibleColumns.ItemPrice">
            <template slot-scope="scope">
              <span style="color: #409EFF;">{{ formatMoney(scope.row.ItemPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="SourceType" label="来源类型" align="center" min-width="100" v-if="visibleColumns.SourceType">
            <template slot-scope="scope">
              <el-tag :type="scope.row.SourceType === '购买' ? 'success' : 'info'" size="small">
                {{ scope.row.SourceType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="TotalPurchased" label="总购买" align="center" min-width="100" v-if="visibleColumns.TotalPurchased">
            <template slot-scope="scope">
              <span>{{ formatNumber(scope.row.TotalPurchased) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ConsumedCount" label="已消费" align="center" min-width="100" v-if="visibleColumns.ConsumedCount">
            <template slot-scope="scope">
              <span style="color: #67C23A;">{{ formatNumber(scope.row.ConsumedCount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RefundedCount" label="已退款" align="center" min-width="100" v-if="visibleColumns.RefundedCount">
            <template slot-scope="scope">
              <span style="color: #E6A23C;">{{ formatNumber(scope.row.RefundedCount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="DeductCount" label="已扣除" align="center" min-width="100" v-if="visibleColumns.DeductCount">
            <template slot-scope="scope">
              <span style="color: #909399;">{{ formatNumber(scope.row.DeductCount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RemainingCount" label="剩余" align="center" min-width="100" v-if="visibleColumns.RemainingCount">
            <template slot-scope="scope">
              <el-tag type="primary" size="small">{{ formatNumber(scope.row.RemainingCount) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column  label="剩余合计" align="center" min-width="100" v-if="visibleColumns.RemainingTotal">
            <template slot-scope="scope">
             <span style="color: #409EFF;">{{ formatMoney(Number(scope.row.RemainingCount) * Number(scope.row.ItemPrice)) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Remark" label="备注" align="center" min-width="150" show-overflow-tooltip v-if="visibleColumns.Remark">
            <template slot-scope="scope">
              <i class="el-icon-edit"></i>
              {{ scope.row.Remark || '无' }}
            </template>
          </el-table-column>
        </el-table>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="visible = false">关闭</el-button>
    </div>
    
    <!-- 字段设置对话框 -->
    <el-dialog title="字段设置" :visible.sync="showColumnDialog" width="400px" append-to-body>
      <div class="column-settings">
        <el-checkbox-group v-model="selectedColumns">
          <el-checkbox v-for="col in columnOptions" :key="col.key" :label="col.key">
            {{ col.label }}
          </el-checkbox>
        </el-checkbox-group>
        <div class="column-actions">
          <el-button size="small" @click="selectAllColumns">全选</el-button>
          <el-button size="small" @click="clearAllColumns">清空</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showColumnDialog = false">取消</el-button>
        <el-button type="primary" @click="saveColumnSettings">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

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

export default {
  name: 'MemberRightsDialog',
  data() {
    return {
      visible: false,
      loading: false,
      screenshotLoading: false,
      showColumnDialog: false,
      memberData: {
        MemberId: '',
        MemberName: '',
        RemainingItems: []
      },
      // 字段配置选项
      columnOptions: [
        { key: 'ItemName', label: '项目名称' },
        { key: 'ItemPrice', label: '单价' },
        { key: 'SourceType', label: '来源类型' },
        { key: 'TotalPurchased', label: '总购买' },
        { key: 'ConsumedCount', label: '已消费' },
        { key: 'RefundedCount', label: '已退款' },
        { key: 'DeductCount', label: '已扣除' },
        { key: 'RemainingCount', label: '剩余' },
        { key: 'RemainingTotal', label: '剩余合计' },
        { key: 'Remark', label: '备注' }
      ],
      // 选中的字段
      selectedColumns: [],
      // 可见字段映射
      visibleColumns: {
        ItemName: true,
        ItemPrice: true,
        SourceType: true,
        TotalPurchased: true,
        ConsumedCount: true,
        RefundedCount: true,
        DeductCount: true,
        RemainingCount: true,
        RemainingTotal: true,
        Remark: true
      }
    }
  },
  mounted() {
    this.loadColumnSettings()
  },
  methods: {
    init(memberId) {
      this.visible = true
      this.loading = true
      this.memberData = {
        MemberId: '',
        MemberName: '',
        RemainingItems: []
      }
      
      request({
        url: `/api/Extend/lqkhxx/GetMemberRemainingItems`,
        method: 'GET',
        data: { memberId }
      }).then(res => {
        if (res.code === 200 && res.data) {
          this.memberData = res.data
        } else {
          this.$message.error(res.msg || '获取会员权益失败')
          this.memberData = { MemberId: '', MemberName: '', RemainingItems: [] }
        }
        this.loading = false
      }).catch(err => {
        console.error('获取会员权益失败:', err)
        this.$message.error('获取会员权益失败')
        this.loading = false
      })
    },
    // 加载字段设置
    loadColumnSettings() {
      const saved = localStorage.getItem('memberRightsColumnSettings')
      if (saved) {
        try {
          const settings = JSON.parse(saved)
          this.selectedColumns = settings.selectedColumns || this.columnOptions.map(col => col.key)
          this.updateVisibleColumns()
        } catch (e) {
          console.error('加载字段设置失败:', e)
          this.selectedColumns = this.columnOptions.map(col => col.key)
          this.updateVisibleColumns()
        }
      } else {
        this.selectedColumns = this.columnOptions.map(col => col.key)
        this.updateVisibleColumns()
      }
    },
    // 更新可见字段
    updateVisibleColumns() {
      const visible = {}
      this.columnOptions.forEach(col => {
        visible[col.key] = this.selectedColumns.includes(col.key)
      })
      this.visibleColumns = visible
    },
    // 全选字段
    selectAllColumns() {
      this.selectedColumns = this.columnOptions.map(col => col.key)
    },
    // 清空字段
    clearAllColumns() {
      this.selectedColumns = []
    },
    // 保存字段设置
    saveColumnSettings() {
      if (this.selectedColumns.length === 0) {
        this.$message.warning('至少需要选择一个字段')
        return
      }
      this.updateVisibleColumns()
      localStorage.setItem('memberRightsColumnSettings', JSON.stringify({
        selectedColumns: this.selectedColumns
      }))
      this.showColumnDialog = false
      this.$message.success('字段设置已保存')
    },
    // 截图功能
    async handleScreenshot() {
      this.screenshotLoading = true
      try {
        // 动态导入html2canvas
        const html2canvas = await import('html2canvas')
        
        // 等待DOM更新
        await this.$nextTick()
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 获取要截图的元素（使用ref定位，包含会员信息和表格）
        let element = this.$refs.dialogContent
        if (!element) {
          // 如果ref不存在，尝试通过对话框查找
          const dialog = this.$el.querySelector('.el-dialog')
          if (dialog) {
            element = dialog.querySelector('.el-dialog__body')
          }
        }
        
        if (!element) {
          this.$message.error('未找到要截图的内容')
          return
        }
        
        // 配置截图选项
        const options = {
          allowTaint: true,
          useCORS: true,
          scale: 2,
          backgroundColor: '#ffffff',
          logging: false,
          imageTimeout: 30000,
          scrollX: 0,
          scrollY: 0,
          width: element.scrollWidth,
          height: element.scrollHeight
        }
        
        // 生成截图
        const canvas = await html2canvas.default(element, options)
        
        // 转换为DataURL
        const dataUrl = canvas.toDataURL('image/png', 1.0)
        
        // 生成文件名
        const memberName = this.memberData.MemberName || '会员'
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
        const filename = `会员权益_${memberName}_${timestamp}.png`
        
        // 下载图片
        this.downloadImage(dataUrl, filename)
        
        this.$message.success('截图成功')
      } catch (error) {
        console.error('截图生成失败:', error)
        this.$message.error('截图生成失败: ' + (error.message || '未知错误'))
      } finally {
        this.screenshotLoading = false
      }
    },
    // 下载图片
    downloadImage(dataUrl, filename) {
      const link = document.createElement('a')
      link.download = filename
      link.href = dataUrl
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    formatMoney(amount) {
      if (!amount && amount !== 0) return '¥0.00'
      const num = parseFloat(amount)
      if (isNaN(num)) return '¥0.00'
      return '¥' + num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    formatNumber(num) {
      if (!num && num !== 0) return '0'
      const number = parseFloat(num)
      if (isNaN(number)) return '0'
      return number.toString()
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        
        const prop = column.property
        const label = column.label
        
        // 判断是否是剩余合计列（通过label判断，因为该列没有property）
        if (label === '剩余合计') {
          // 剩余合计列需要特殊处理：计算所有行的剩余数量 * 单价的总和
          if (this.visibleColumns.RemainingTotal) {
            const total = data.reduce((prev, curr) => {
              const count = Number(curr.RemainingCount) || 0
              const price = Number(curr.ItemPrice) || 0
              return prev + (count * price)
            }, 0)
            sums[index] = this.formatMoney(total)
          } else {
            sums[index] = ''
          }
          return
        }
        
        // 如果列被隐藏，不计算合计
        if (prop && !this.visibleColumns[prop]) {
          sums[index] = ''
          return
        }
        
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          if (prop === 'TotalPurchased' || prop === 'ConsumedCount' || 
              prop === 'RefundedCount' || prop === 'DeductCount' || 
              prop === 'RemainingCount') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = this.formatNumber(sums[index])
          } else {
            sums[index] = ''
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.member-info {
  margin-bottom: 20px;
  
  i {
    margin-right: 6px;
    color: #409EFF;
    font-size: 16px;
  }
}

::v-deep .el-descriptions {
  .el-descriptions__label {
    font-weight: 600;
    color: #606266;
  }
  
  .el-descriptions__content {
    color: #303133;
  }
}

.dialog-footer {
  text-align: right;
}

.rights-table {
  ::v-deep .el-table {
    font-size: 14px;
    
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
    
    td {
      i {
        margin-right: 4px;
        color: #409EFF;
      }
    }
    
    .el-table__footer-wrapper {
      .el-table__footer {
        th {
          background-color: #f0f9ff;
          color: #303133;
          font-weight: 700;
        }
      }
    }
  }
  
  ::v-deep .el-tag {
    font-weight: 600;
  }
}

::v-deep .el-dialog__body {
  padding: 20px;
}

.dialog-header-actions {
  margin-bottom: 15px;
  text-align: right;
  
  .el-button-group {
    .el-button {
      border-radius: 4px;
    }
  }
}


.column-settings {
  .el-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-bottom: 20px;
    
    .el-checkbox {
      margin-right: 0;
    }
  }
  
  .column-actions {
    text-align: center;
    padding-top: 15px;
    border-top: 1px solid #EBEEF5;
    
    .el-button {
      margin: 0 5px;
    }
  }
}
</style>

