<template>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="visible"
      width="80%"
      top="5vh"
      :before-close="handleClose"
    >
      <div class="statistics-dialog">
        <div class="time-selector">
          <common-time-select v-model="currentRange" @change="handleTimeChange" />
        </div>
        
        <!-- 加载状态 -->
        <div class="loading-state" v-if="loading">
          <i class="el-icon-loading"></i>
          <span>数据加载中...</span>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-else-if="datas.length === 0">
          <div class="empty-text">暂无数据</div>
        </div>

        <!-- 根据不同ID显示不同内容 -->
        <div class="content-area" v-else>
          <!-- 客户来源统计 -->
          <div v-if="(id == 1 || id == 5)" class="customer-source">
            <el-table :data="datas" style="width: 100%">
              <el-table-column prop="name" label="客户来源" />
              <el-table-column prop="theNum" label="数量" />
              <el-table-column prop="theAmount" label="公示金额" />
            </el-table>
          </div>

          <!-- 检测车型统计 -->
          <div v-if="id == 2" class="car-model-stats">
            <el-table :data="datas" style="width: 100%">
              <el-table-column prop="goodsTitle" label="车型" />
              <el-table-column prop="theNum" label="数量" />
            </el-table>
          </div>

          <!-- 待收款统计 -->
          <div v-if="id == 3 || id == 7" class="pending-payment">
            <el-table 
              :data="datas" 
              style="width: 100%" 
              @row-click="handlePendingPaymentRowClick"
            >
              <el-table-column prop="sourceName" label="渠道" />
              <el-table-column prop="pendingCount" label="台次" />
              <el-table-column prop="pendingAmountYuan" label="金额" />
            </el-table>
          </div>

          <!-- 检测类型统计 -->
          <div v-if="id == 4" class="inspection-type">
            <el-table :data="datas" style="width: 100%">
              <el-table-column prop="skuName" label="检测类型" />
              <el-table-column prop="orderCount" label="订单数量" />
            </el-table>
          </div>

          <!-- 资料统计 -->
          <div v-if="id == 6" class="document-stats">
            <el-table :data="datas" style="width: 100%">
              <el-table-column prop="fileName" label="文件名称" />
              <el-table-column prop="createTime" label="上传时间" />
            </el-table>
          </div>
        </div>
      </div>
      
      <!-- WorkOrderList 弹窗 -->
      <el-dialog
        title="工单详情"
        :visible.sync="workOrderListVisible"
        width="80%"
        top="5vh"
        append-to-body
        v-if="workOrderListVisible"
      >
        <WorkOrderList 
          :show-search="true"
          :show-summary="true"
          :external-query-params="workOrderListQueryParams"
          ref="workOrderList"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="workOrderListVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </template>
  
  <script>
  import * as statisticsApi from './api/statistics'
  import CommonTimeSelect from '@/components/CommonTimeSelect'
  import WorkOrderList from '@/views/partner/components/WorkOrderList.vue'

  export default {
    name: 'StatisticsDialog',
    components: {
      CommonTimeSelect,
      WorkOrderList
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      id: {
        type: [String, Number],
        required: true
      },
      dataId: {
        type: [String, Number],
        default: null
      },
      type: {
        type: String,
        default: ''
      },
      range: {
        type: Array,
        default: () => []
      },
      extraParams: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        currentRange: [],
        datas: [],
        loading: false,
        // WorkOrderList 弹窗相关
        workOrderListVisible: false,
        workOrderListQueryParams: {}
      }
    },
    computed: {
      dialogTitle() {
        const titles = {
          1: '客户来源统计',
          2: '检测车型统计',
          3: '代收款',
          4: '检测类型统计',
          5: '客户来源统计',
          6: '资料统计',
          7: '来源-待收款'
        }
        return titles[this.id] || '统计详情'
      }
    },
    watch: {
      visible(val) {
        if (val) {
          this.currentRange = [...this.range]
          this.loadData()
        }
      }
    },
    mounted() {
      // 确保组件挂载时如果可见就加载数据
      if (this.visible) {
        this.currentRange = [...this.range]
        this.loadData()
      }
    },
    methods: {
      handleClose() {
        this.$emit('update:visible', false)
      },

      handleTimeChange(range) {
        this.currentRange = range
        this.loadData()
      },

      async loadData() {
        this.loading = true
        try {
          const params = {
            startTime: this.currentRange[0],
            endTime: this.currentRange[1],
            ...this.extraParams
          }

          let response
          switch (this.id) {
            case 1:
              response = await statisticsApi.getStaticsTable3Detail({ ...params, remark: this.type })
              break
            case 2:
              response = await statisticsApi.getStaticsTable4(params)
              break
            case 3:
              response = await statisticsApi.getStaticsTable5(params)
              break
            case 4:
              response = await statisticsApi.queryInspectionSkuList(params)
              break
            case 5:
              response = await statisticsApi.customerSourceCount({ ...params, businessId: this.dataId })
              break
            case 6:
              response = await statisticsApi.getFileByType({ ...params, servicePackageId: 'jiance' })
              this.processFileData(response.data)
              break
            case 7:
              response = await statisticsApi.channelMoneyStaticsByBusi({ ...params, busi: this.type })
              break
            default:
              console.warn('Unknown statistics type:', this.id)
          }

          if (response && response.data) {
            // 特殊处理某些返回数据格式不同的接口
            if (this.id === 4) {
              // 检测类型统计接口返回的是数组
              this.datas = Array.isArray(response.data) ? response.data : []
            } else if (this.id === 6) {
              // 资料统计已经在 processFileData 中处理
            } else {
              // 其他接口通常返回对象，其中包含 list 或 data 属性
              this.datas = response.data.list || response.data.data || response.data || []
            }
          } else {
            this.datas = []
          }
        } catch (error) {
          this.$message.error('数据加载失败: ' + (error.message || ''))
          console.error(error)
          this.datas = []
        } finally {
          this.loading = false
        }
      },

      processFileData(data) {
        if (this.type === 'add') {
          this.datas = data.insertFile || []
        } else if (this.type === 'update') {
          this.datas = data.updateFile || []
        } else {
          this.datas = []
        }
      },
      
      // 处理待收款统计行点击事件
      handlePendingPaymentRowClick(row) {
        // 设置 WorkOrderList 查询参数
        this.workOrderListQueryParams = {
          datetimeRange: this.currentRange,
          customerSource: row.sourceName,
          ...this.extraParams
        };
        
        // 显示 WorkOrderList 弹窗
        this.workOrderListVisible = true;
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .statistics-dialog {
    .time-selector {
      margin-bottom: 20px;
    }
    
    .loading-state {
      text-align: center;
      padding: 60px 0;
      
      i {
        font-size: 24px;
        color: #409EFF;
        margin-right: 10px;
      }
      
      span {
        font-size: 14px;
        color: #666;
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 0;

      .empty-text {
        font-size: 14px;
        color: #999;
      }
    }
    
    .content-area {
      max-height: 60vh;
      overflow-y: auto;
    }
    
    // 添加行hover样式提示
    ::v-deep .el-table__row {
      cursor: pointer;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
  </style>