<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 筛选条件 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="会员">
              <el-select
                v-model="query.MemberId"
                placeholder="请选择会员"
                filterable
                remote
                :remote-method="remoteMemberMethod"
                :loading="memberLoading"
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in memberOptions"
                  :key="item.id"
                  :label="`${item.khmc}(${item.sjh || ''} ${item.gsmdName || ''})`"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属门店">
              <el-select
                v-model="query.BelongStoreId"
                placeholder="请选择所属门店"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.dm"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开单门店">
              <el-select
                v-model="query.BillingStoreId"
                placeholder="请选择开单门店"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.dm"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开单人">
              <userSelect v-model="query.BillingUserId" placeholder="请选择开单人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="购买品项">
              <el-select
                v-model="query.PurchaseItemId"
                placeholder="请选择购买品项"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.xmmc"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="赠送品项">
              <el-select
                v-model="query.GiftItemId"
                placeholder="请选择赠送品项"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.xmmc"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="体验品项">
              <el-select
                v-model="query.ExperienceItemId"
                placeholder="请选择体验品项"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.xmmc"
                  :value="item.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="NCC-common-layout-main NCC-flex-main">
        <el-table 
          v-loading="listLoading" 
          :data="treeList" 
          border
          stripe
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          row-key="id"
          :default-expand-all="false">
          <el-table-column prop="name" label="名称/信息" min-width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'member'">
                <i class="el-icon-user" style="margin-right: 4px; color: #409EFF;"></i>
                <strong>{{ scope.row.MemberName || '无' }}</strong>
                <span style="color: #909399; margin-left: 8px;">({{ scope.row.MemberCode || '无' }})</span>
              </span>
              <span v-else-if="scope.row.level === 'billing'">
                <i class="el-icon-document" style="margin-right: 4px; color: #67C23A;"></i>
                <span>{{ formatDateTime(scope.row.BillingTime) || '无' }}</span>
                <span style="color: #909399; margin-left: 8px;">{{ scope.row.BillingStoreName || '无' }} - {{ scope.row.BillingUserName || '无' }}</span>
              </span>
              <span v-else-if="scope.row.level === 'item'">
                <i class="el-icon-goods" style="margin-right: 4px; color: #409EFF;"></i>
                <el-tag 
                  :type="getItemTypeTagType(scope.row.ItemType)" 
                  size="small"
                  style="margin-right: 4px;">
                  {{ scope.row.ItemType }}
                </el-tag>
                <span>{{ scope.row.ItemName || '无' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="memberPhone" label="会员电话" min-width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'member'">
                <i class="el-icon-phone" style="margin-right: 4px; color: #67C23A;"></i>
                <span>{{ scope.row.MemberPhone || '无' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="belongStoreName" label="所属门店" min-width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'member'">
                <i class="el-icon-shop" style="margin-right: 4px; color: #409EFF;"></i>
                <span>{{ scope.row.BelongStoreName || '无' }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="itemPrice" label="单价" min-width="100" >
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'item'">
                <span class="amount-text">¥{{ formatMoney(scope.row.ItemPrice) }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="projectNumber" label="项目数" min-width="100" >
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'item'">
                <i class="el-icon-menu" style="margin-right: 4px; color: #67C23A;"></i>
                <span>{{ scope.row.ProjectNumber || 0 }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" min-width="120" >
            <template slot-scope="scope">
              <span v-if="scope.row.level === 'item'">
                <span :class="getAmountClass(scope.row.ItemType)">
                  ¥{{ formatMoney(scope.row.TotalAmount) }}
                </span>
              </span>
              <span v-else-if="scope.row.level === 'billing'">
                <span class="amount-paid">
                  ¥{{ formatMoney(scope.row.BillingTotalAmount) }}
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <pagination 
          :total="total" 
          :page.sync="listQuery.currentPage" 
          :limit.sync="listQuery.pageSize" 
          @pagination="search" 
        />
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'MemberItemStatistics',
  data() {
    return {
      query: {
        MemberId: undefined,
        BelongStoreId: undefined,
        BillingStoreId: undefined,
        BillingUserId: undefined,
        PurchaseItemId: undefined,
        GiftItemId: undefined,
        ExperienceItemId: undefined
      },
      memberOptions: [],
      memberLoading: false,
      storeOptions: [],
      itemOptions: [],
      list: [],
      treeList: [],
      listLoading: false,
      total: 0,
      idCounter: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20
      }
    }
  },
  created() {
    this.initStoreOptions()
    this.initItemOptions()
    this.initMemberOptions()
    this.search()
  },
  methods: {
    // 初始化门店选项
    initStoreOptions() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.storeOptions = res.data.list
        }
      }).catch(() => {
        this.storeOptions = []
      })
    },

    // 初始化品项选项
    initItemOptions() {
      request({
        url: '/api/Extend/LqXmzl',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.itemOptions = res.data.list
        }
      }).catch(() => {
        this.itemOptions = []
      })
    },

    // 初始化会员选项
    initMemberOptions() {
      request({
        url: '/api/Extend/LqKhxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 10
        }
      }).then(res => {
        if (res.code == 200 && res.data.list && res.data.list.length > 0) {
          this.memberOptions = res.data.list
        }
      }).catch(() => {
        this.memberOptions = []
      })
    },

    // 会员远程搜索
    remoteMemberMethod(query) {
      if (query !== '') {
        this.memberLoading = true
        request({
          url: '/api/Extend/LqKhxx',
          method: 'GET',
          data: {
            currentPage: 1,
            pageSize: 20,
            keyword: query
          }
        }).then(res => {
          this.memberLoading = false
          if (res.code == 200 && res.data.list && res.data.list.length > 0) {
            this.memberOptions = res.data.list
          } else {
            this.memberOptions = []
          }
        }).catch(() => {
          this.memberLoading = false
          this.memberOptions = []
        })
      } else {
        this.memberOptions = []
      }
    },

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

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

      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === null || params[key] === '') {
          delete params[key]
        }
      })

      request({
        url: '/api/Extend/lqkhxx/get-member-item-info',
        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
          this.buildTreeData()
        } else {
          this.list = []
          this.treeList = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
        this.list = []
        this.treeList = []
        this.total = 0
      })
    },

    // 构建树状数据
    buildTreeData() {
      this.idCounter = 0
      const treeList = []
      
      this.list.forEach(member => {
        // 第一层：会员节点
        const memberNode = {
          id: `member_${this.idCounter++}`,
          level: 'member',
          ...member,
          children: []
        }

        // 处理开单数据
        if (member.BillingItems && member.BillingItems.length > 0) {
          member.BillingItems.forEach(billing => {
            // 第二层：开单节点
            const billingNode = {
              id: `billing_${this.idCounter++}`,
              level: 'billing',
              ...billing,
              BillingTotalAmount: (billing.PurchaseItemsTotalAmount || 0) + 
                                 (billing.ConsumedItemsTotalAmount || 0) - 
                                 (billing.RefundedItemsTotalAmount || 0) - 
                                 (billing.DeductedItemsTotalAmount || 0),
              children: []
            }

            // 处理购买品项
            if (billing.PurchaseItems && billing.PurchaseItems.length > 0) {
              billing.PurchaseItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '购买',
                  ...item
                })
              })
            }

            // 处理赠送品项
            if (billing.GiftItems && billing.GiftItems.length > 0) {
              billing.GiftItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '赠送',
                  ...item
                })
              })
            }

            // 处理体验品项
            if (billing.ExperienceItems && billing.ExperienceItems.length > 0) {
              billing.ExperienceItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '体验',
                  ...item
                })
              })
            }

            // 处理消费品项
            if (billing.ConsumedItems && billing.ConsumedItems.length > 0) {
              billing.ConsumedItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '消费',
                  ...item
                })
              })
            }

            // 处理退款项
            if (billing.RefundedItems && billing.RefundedItems.length > 0) {
              billing.RefundedItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '退款',
                  ...item
                })
              })
            }

            // 处理扣减项
            if (billing.DeductedItems && billing.DeductedItems.length > 0) {
              billing.DeductedItems.forEach(item => {
                billingNode.children.push({
                  id: `item_${this.idCounter++}`,
                  level: 'item',
                  ItemType: '扣减',
                  ...item
                })
              })
            }

            // 即使没有品项，也添加开单节点
            memberNode.children.push(billingNode)
          })
        }

        // 无论是否有开单或品项，都添加会员节点
        treeList.push(memberNode)
      })

      this.treeList = treeList
    },

    // 获取品项类型的标签类型
    getItemTypeTagType(itemType) {
      const typeMap = {
        '购买': 'success',
        '赠送': 'info',
        '体验': 'warning',
        '消费': 'primary',
        '退款': 'danger',
        '扣减': 'danger'
      }
      return typeMap[itemType] || ''
    },

    // 获取金额样式类
    getAmountClass(itemType) {
      if (itemType === '退款' || itemType === '扣减') {
        return 'amount-debt'
      }
      return 'amount-paid'
    },

    // 重置查询条件
    reset() {
      this.query = {
        MemberId: undefined,
        BelongStoreId: undefined,
        BillingStoreId: undefined,
        BillingUserId: undefined,
        PurchaseItemId: undefined,
        GiftItemId: undefined,
        ExperienceItemId: undefined
      }
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.list = []
      this.treeList = []
      this.total = 0
    },

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

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      try {
        const date = new Date(dateTime)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (e) {
        return dateTime
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.amount-paid {
  color: #67C23A;
  font-weight: 500;
}

.amount-debt {
  color: #F56C6C;
  font-weight: 500;
}

.amount-text {
  color: #409EFF;
  font-weight: 500;
}
</style>

