<template>
  <div class="leftPage">
    <div class="topPage">
      <Title style="font-size: 22px" title="企业关键指标" />
      <div class="indicators">
        <div class="indicator-card" v-for="indicator in indicators" :key="indicator.id">
          <div style="display: flex; align-items: baseline; gap: 4px; margin-bottom: 5px">
            <div class="indicator-value">{{ indicator.value }}</div>
            <div class="indicator-unit">{{ indicator.unit }}</div>
          </div>
          <div class="indicator-name">{{ indicator.name }}</div>
          <div class="indicator-icon">
            <img :src="indicator.iconPath" :alt="indicator.name" v-if="indicator.iconPath" style="width: 50px; height: 50px" />
          </div>
        </div>
      </div>
    </div>

    <div class="endPage">
      <Title style="font-size: 22px" title="人员情况" />
      <div class="map">
        <div class="project_attendance_chart">
          <Title style="font-size: 22px" title="各项目人员出勤率" />
          <div class="chart_content" ref="attendanceChartRef"></div>
        </div>
        <div class="attendance_tag">
          <div class="tag_item">
            <img src="@/assets/projectLarge/people.svg" alt="" />
            <div class="tag_title">出勤人</div>
            <div class="tag_info">
              {{ attendanceCount }}
              <span style="font-size: 14px">人</span>
            </div>
          </div>
          <div class="tag_item">
            <img src="@/assets/projectLarge/people.svg" alt="" />
            <div class="tag_title">在岗人</div>
            <div class="tag_info">
              {{ peopleCount }}
              <span style="font-size: 14px">人</span>
            </div>
          </div>
          <div class="tag_item">
            <img src="@/assets/projectLarge/people.svg" alt="" />
            <div class="tag_title">出勤率</div>
            <div class="tag_info">
              {{ attendanceRate }}
              <span style="font-size: 14px">%</span>
            </div>
          </div>
        </div>
      </div>

      <div class="attendance_tag"></div>
    </div>

    <!-- 项目出勤率柱状图 -->
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import Title from './title.vue';
import { getScreenNews, getScreenPeople } from '@/api/projectScreen';
import { keyIndex } from '@/api/enterpriseLarge/index';
import { mapOption } from './optionList';
import * as echarts from 'echarts';

const props = defineProps({
  projectId: {
    type: String,
    default: ''
  }
});

let mapChart = null;
const mapChartRef = ref<HTMLDivElement | null>(null);
const indicators = ref([
  {
    id: '1',
    name: '在建项目',
    value: '28',
    unit: '个',
    iconPath: '/src/assets/images/beUnder.png'
  },
  {
    id: '2',
    name: '合同总额',
    value: '288.88',
    unit: '亿元',
    iconPath: '/src/assets/images/contract.png'
  },
  {
    id: '3',
    name: '总容量',
    value: '158.88',
    unit: '个',
    iconPath: '/src/assets/images/totalCapacity.png'
  },
  {
    id: '4',
    name: '今日施工',
    value: '18',
    unit: '个',
    iconPath: '/src/assets/images/todayConstruction.png'
  }
]);

const news = ref([]);
const newDetail = ref({
  title: '',
  content: ''
});
const newId = ref('');
const attendanceCount = ref(0);
const attendanceRate = ref(0);
const peopleCount = ref(0);
const teamAttendanceList = ref([{ id: '', teamName: '', attendanceNumber: 0, allNumber: 0, attendanceRate: 0, attendanceTime: '' }]);

// 项目出勤率数据
const projectAttendanceData = ref([
  { name: 'A项目', value: 62 },
  { name: 'B项目', value: 56 },
  { name: 'C项目', value: 95 },
  { name: 'D项目', value: 64 },
  { name: 'E项目', value: 97.5 }
]);

let attendanceChart = null;
const attendanceChartRef = ref<HTMLDivElement | null>(null);

/**
 * 获取项目人员出勤数据
 */
const getPeopleData = async () => {
  const res = await getScreenPeople(props.projectId);
  const { data, code } = res;
  if (code === 200) {
    attendanceCount.value = data.attendanceCount;
    attendanceRate.value = data.attendanceRate;
    peopleCount.value = data.peopleCount;
    teamAttendanceList.value = data.teamAttendanceList;
  }
};

/**
 * 获取企业关键指标数据
 */
const getKeyIndexData = async () => {
  const res = await keyIndex();
  const { data, code } = res;
  if (code === 200) {
    // 更新指标数据，使用接口返回的指定字段
    indicators.value[0].value = data.ongoingProject || 0;
    indicators.value[1].value = data.totalContractAmount || 0;
    indicators.value[2].value = data.totalCapacity || 0;
    indicators.value[3].value = data.todayProject || 0;
  }
};

/**
 * 初始化项目出勤率柱状图（美化版）
 */
const initAttendanceChart = () => {
  if (!attendanceChartRef.value) {
    return;
  }
  attendanceChart = echarts.init(attendanceChartRef.value);

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(29, 214, 255, 0.1)'
        }
      },
      backgroundColor: 'rgba(10, 24, 45, 0.8)',
      borderColor: 'rgba(29, 214, 255, 0.3)',
      borderWidth: 1,
      textStyle: {
        color: '#e6f7ff'
      },
      formatter: (params) => {
        const data = params[0];
        return `${data.name}<br/>出勤率: ${data.value}%`;
      }
    },
    grid: {
      top: 40,
      right: 30,
      bottom: 40,
      left: 30,
      containLabel: true,
      backgroundColor: 'rgba(10, 24, 45, 0.1)',
      borderColor: 'rgba(29, 214, 255, 0.1)',
      borderWidth: 1
    },
    xAxis: {
      type: 'category',
      data: projectAttendanceData.value.map((item) => item.name),
      axisLine: {
        lineStyle: {
          color: 'rgba(29, 214, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#e6f7ff',
        fontSize: 14,
        interval: 0,
        fontWeight: 'bold',
        padding: [10, 0, 0, 0]
      },
      axisTick: {
        show: true,
        length: 5,
        lineStyle: {
          color: 'rgba(29, 214, 255, 0.5)'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      interval: 20,
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(29, 214, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#e6f7ff',
        fontSize: 12,
        formatter: '{value}%',
        padding: [0, 10, 0, 0]
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(29, 214, 255, 0.15)',
          type: 'dashed'
        }
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        data: projectAttendanceData.value.map((item) => item.value),
        type: 'bar',
        itemStyle: {
          color: function (params) {
            // 根据数值动态调整渐变效果
            const value = params.value;
            const baseColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(29, 214, 255, 1)' },
              { offset: 1, color: 'rgba(10, 120, 200, 0.8)' }
            ]);
            return baseColor;
          },
          borderRadius: [5, 5, 0, 0],
          borderColor: 'rgba(255, 255, 255, 0.3)',
          borderWidth: 1
        },
        barWidth: '45%',
        label: {
          show: true,
          position: 'top',
          color: '#e6f7ff',
          fontSize: 14,
          fontWeight: 'bold',
          formatter: '{c}%',
          offset: [0, -10]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(29, 214, 255, 1)' },
              { offset: 1, color: 'rgba(10, 120, 200, 1)' }
            ]),
            shadowBlur: 10,
            shadowColor: 'rgba(29, 214, 255, 0.5)',
            borderColor: 'rgba(255, 255, 255, 0.5)'
          },
          label: {
            color: '#ffffff',
            textShadowBlur: 2,
            textShadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        animationDelay: function (idx) {
          // 动画延迟，使柱子依次出现
          return idx * 100;
        }
      }
    ],
    // 添加动画效果
    animationEasing: 'elasticOut',
    animationDelayUpdate: function (idx) {
      return idx * 5;
    },
    // 添加单位标签
    graphic: [
      {
        type: 'text',
        left: 10,
        top: 10,
        style: {
          text: '单位: %',
          fill: '#8ab2ff',
          fontSize: 12
        }
      }
    ]
  };

  attendanceChart.setOption(option);

  // 添加窗口大小变化时的图表更新
  const handleResize = () => {
    if (attendanceChart) {
      attendanceChart.resize();
    }
  };

  window.addEventListener('resize', handleResize);

  // 清理函数
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
};

/**
 * 初始化地图
 */
const initMapChart = () => {
  if (!mapChartRef.value) {
    return;
  }
  mapChart = echarts.init(mapChartRef.value);
  mapChart.setOption(mapOption);
};

onMounted(() => {
  // nextTick(() => {
  //   initMapChart();
  // });
  getPeopleData();
  getKeyIndexData();

  // 初始化项目出勤率柱状图
  setTimeout(() => {
    initAttendanceChart();
  }, 100);
});

onUnmounted(() => {
  // if (mapChart) {
  //   mapChart.dispose();
  //   mapChart = null;
  // }

  if (attendanceChart) {
    attendanceChart.dispose();
    attendanceChart = null;
  }
});
</script>

<style scoped lang="scss">
.leftPage {
  display: flex;
  flex-direction: column;
  height: 100%;

  .topPage,
  .endPage {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    padding: 15px 0;
    border: 1px solid rgba(29, 214, 255, 0.1);
    box-sizing: border-box;
  }

  .endPage {
    flex: 1;
    margin-top: 23px;
  }

  .project_attendance_chart {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    padding: 15px 0;
    border: 1px solid rgba(29, 214, 255, 0.1);
    box-sizing: border-box;

    .chart_title {
      font-size: 16px;
      color: #e6f7ff;
      margin-bottom: 15px;
      text-align: left;
    }
    .chart_content {
      width: 100%;
      height: 200px;
      position: relative;
    }
  }
}

.indicators {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 15px;
  padding: 0 15px;
  box-sizing: border-box;
}

.indicator-card {
  position: relative;
  width: 100%;
  height: 100px;
  background: rgba(10, 24, 45, 0.7);
  border: 1px solid rgba(29, 214, 255, 0.2);
  border-radius: 4px;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}

.indicator-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, rgba(29, 214, 255, 0.2) 0%, rgba(29, 214, 255, 0.6) 50%, rgba(29, 214, 255, 0.2) 100%);
}

.indicator-value {
  font-size: 24px;
  font-weight: bold;
  color: #e6f7ff;
  margin-bottom: 5px;
}

.indicator-unit {
  font-size: 14px;
  color: #8ab2ff;
  margin-bottom: 8px;
}

.indicator-name {
  font-size: 14px;
  color: #e6f7ff;
}

.indicator-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.indicator-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.map {
  margin-top: 15px;
}

.attendance_tag {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 30px;
  margin-top: 15px;

  .tag_item {
    width: 28%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    border: 1px dashed rgba(29, 214, 255, 0.3);
    padding: 10px;

    .tag_info {
      font-size: 20px;
      font-weight: 700;
      color: rgba(230, 247, 255, 1);
      text-shadow: 0px 1.24px 6.21px rgba(0, 190, 247, 1);
    }

    .tag_title {
      font-size: 14px;
      font-weight: 400;
      color: rgba(230, 247, 255, 1);
    }
  }
}

.attendance_list {
  padding: 0px 30px;
  font-size: 14px;

  .attendance_item {
    display: grid;
    grid-template-columns: 3fr 2fr 2fr 3fr;
    margin-top: 20px;
  }
}

.subfont {
  color: rgba(138, 149, 165, 1);
}
</style>
