<template>
  <HomeContainer :customStyle="{ background: 'none' }">
    <!-- 页面标题 -->
    <view class="page-header">

      <view class="report-type">{{ reportTypeText }}</view>
      <!-- 班组和个人切换按钮 -->
      <SelectTag v-if="isTeamLeader" :tags="roleTags" :selected-value="currentQueryParams.scopedType"
        @change="handleRoleChange" class="role-selector" />
    </view>

    <!-- 四个分析组件 -->
    <view class="analysis-sections">
      <!-- 勤务组织组件 -->
      <DutyOrganization :query-form="currentQueryParams" />

      <!-- 质控活动组件 -->
      <QualityControl :query-form="currentQueryParams" />

      <!-- 风险隐患组件 -->
      <RiskHazard :query-form="currentQueryParams" />

      <!-- 抽问抽答组件 -->
      <QaAnalysis :query-form="currentQueryParams" />
    </view>
  </HomeContainer>
</template>

<script>
import HomeContainer from '@/components/HomeContainer.vue'
import DutyOrganization from './components/dutyOrganization.vue'
import QualityControl from './components/qualityControl.vue'
import RiskHazard from './components/riskHazard.vue'
import QaAnalysis from './components/qaAnalysis.vue'
import SelectTag from '@/components/select-tag/select-tag.vue'
// import { getUsageReport } from '@/api/qualityControlAnalysisReport/qualityControlAnalysisReport'

export default {
  name: 'QualityControlAnalysisReport',
  components: {
    HomeContainer,
    DutyOrganization,
    QualityControl,
    RiskHazard,
    QaAnalysis,
    SelectTag
  },
  data() {
    return {
      // 查询参数
      currentQueryParams: {
        dateRangeQueryType: 'MONTH', // 默认月度
        year: new Date().getFullYear(),
        quarter: '',
        month: new Date().getMonth() + 1,
        scopedType: ''
      },
      // 页面加载状态
      loading: false,
      // 报告数据
      reportData: {},
      // 角色切换相关数据
      roleTags: [
        { label: '班组', value: 'TEAMS' },
        { label: '个人', value: 'USER' }
      ]
    }
  },

  computed: {
    // 报告类型文本
    reportTypeText() {
      const now = new Date()
      const { dateRangeQueryType } = this.currentQueryParams

      switch (dateRangeQueryType) {
        case 'MONTH': {
          const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1)
          const year = lastMonth.getFullYear()
          const month = lastMonth.getMonth() + 1
          return `${year}年${month}月-月度报告`
        }
        case 'QUARTER': {
          const currentQuarter = Math.floor((now.getMonth()) / 3) + 1
          const lastQuarter = currentQuarter === 1 ? 4 : currentQuarter - 1
          const year = currentQuarter === 1 ? now.getFullYear() - 1 : now.getFullYear()
          return `${year}年第${lastQuarter}季度-季度报告`
        }
        case 'YEAR': {
          const lastYear = now.getFullYear() - 1
          return `${lastYear}年-年度报告`
        }
        default:
          return '报告'
      }
    },

    // 时间范围文本
    timeRangeText() {
      const { dateRangeQueryType, year, quarter, month } = this.currentQueryParams

      switch (dateRangeQueryType) {
        case 'YEAR':
          return `${year}年`
        case 'QUARTER':
          return `${year}年第${quarter}季度`
        case 'MONTH':
          return `${year}年${month}月`
        default:
          return '未知时间范围'
      }
    },

    // 计算属性：检查是否为班组长
    isTeamLeader() {
      const roles = this.$store.state?.user?.roles || []
      return roles.includes('banzuzhang')
    }
  },

  onLoad(options) {
    // 设置查询参数
    this.setQueryParams(options)


  },

  onShow() {

  },

  methods: {
    // 设置查询参数
    setQueryParams(options) {
      const now = new Date()
      const currentYear = now.getFullYear()
      const currentMonth = now.getMonth() + 1
      const currentQuarter = Math.ceil(currentMonth / 3)

      // 从路由参数获取查询类型
      const dateRangeQueryType = options.dateRangeQueryType || 'MONTH'

      // 根据查询类型设置时间参数
      let year, quarter, month

      // 优先使用路由参数中的时间值，如果没有则使用默认值（取前一期）
      switch (dateRangeQueryType) {
        case 'YEAR':
          if (options.year) {
            year = parseInt(options.year)
          } else {
            year = currentYear - 1
          }
          quarter = ''
          month = ''
          break
        case 'QUARTER':
          if (options.year) {
            year = parseInt(options.year)
          } else {
            year = currentYear
          }
          if (options.quarter) {
            quarter = parseInt(options.quarter)
          } else {
            quarter = currentQuarter > 1 ? currentQuarter - 1 : 4
            if (currentQuarter === 1) {
              year = currentYear - 1
            }
          }
          month = ''
          break
        case 'MONTH':
        default:
          if (options.year) {
            year = parseInt(options.year)
          } else {
            year = currentYear
          }
          if (options.month) {
            month = parseInt(options.month)
          } else {
            month = currentMonth > 1 ? currentMonth - 1 : 12
            if (currentMonth === 1) {
              year = currentYear - 1
            }
          }
          quarter = ''
          break
      }

      // 根据查询类型设置yearOnYear和chainRatio参数
      let yearOnYear, chainRatio
      if (dateRangeQueryType === 'YEAR') {
        yearOnYear = true
        chainRatio = undefined
      } else {
        yearOnYear = true
        chainRatio = true
      }

      // 从store获取当前登录用户的deptId
      const { roles, id } = this.$store.state?.user || {};
      const { deptId, deptType } = this.$store.state?.user?.userInfo || {};

      let stationType = roles.includes('test') || roles.includes('zhijianke')
      let finalScopedId, finalScopedType
      if (roles.includes('jingli') || roles.includes('xingzheng')) {
        finalScopedId = deptId || ''
        finalScopedType = 'BRIGADE'
      }
      // 如果是班组长，默认选择 TEAMS
      if (roles.includes('banzuzhang')) {
        finalScopedId = deptId || ''
        finalScopedType = 'TEAMS'
      } else {
        // 其他情况按登录角色赋值
        finalScopedId = stationType ? '' : roles.includes('SecurityCheck') ? id : (deptId || '')
        finalScopedType = stationType ? '' : roles.includes('SecurityCheck') ? 'USER' : (deptType || '')
      }

      // 一次性赋值给currentQueryParams
      this.currentQueryParams = {
        dateRangeQueryType,
        year,
        quarter,
        month,
        scopedId: finalScopedId,
        scopedType: finalScopedType,
        yearOnYear,
        chainRatio
      }
    },



    // 处理角色切换
    handleRoleChange(role) {

      const { userId, deptId } = this.$store.state?.user?.userInfo || {};

      if (role === 'TEAMS') {
        this.currentQueryParams.scopedId = deptId;
        this.currentQueryParams.scopedType = 'TEAMS'
      } else {
        this.currentQueryParams.scopedId = userId
        this.currentQueryParams.scopedType = 'USER'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-header {
  border-radius: 20rpx;
  padding: 32rpx;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}



.report-type {
  font-size: 28rpx;
  opacity: 0.9;
}

.query-section {
  padding: 24rpx 32rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #e9ecef;
}

.query-item {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.query-label {
  font-size: 28rpx;
  color: #666;
  min-width: 120rpx;
}

.query-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
</style>