<template>
  <div class="dashboard">
    <!-- 顶部区域 -->
    <header class="dashboard-header">
      <div class="header-content">
        <h1 class="text-gradient">工作台</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>工作台</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </header>

    <div class="dashboard-content">
      <!-- 左侧个人信息区域 -->
      <div class="left-panel">
        <el-card class="user-card" :body-style="{ padding: '0px' }">
          <div class="user-profile">
            <div class="cover-image"></div>
            <el-avatar :src="avatarUrl" :size="100" class="profile-avatar"></el-avatar>
            <h2 class="profile-name">{{ nickName }}</h2>
            <p class="profile-dept">{{ deptLabel }}</p>
          </div>

          <!-- 常用应用区域 -->
          <div class="apps-section">
            <h3 class="section-title">常用应用</h3>
            <div class="apps-grid">
              <div
                v-for="(fRouter, index) in favoriteRouter"
                :key="fRouter.path"
                class="app-item"
                @mouseenter="hoverIndex = index"
                @mouseleave="hoverIndex = -1"
              >
                <router-link :to="fRouter.path" class="app-link">
                  <svg-icon :icon-class="fRouter.meta.icon" class="app-icon"/>
                  <span class="app-name">{{ subName(fRouter.name) }}</span>
                </router-link>
                <el-button
                  @click="removeRoute(fRouter.id)"
                  class="delete-button"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  size="mini"
                  v-show="hoverIndex === index"
                ></el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧主要内容区域 -->
      <div class="right-panel">
        <!-- 待审批事项和已入库物资区域 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="approval-card" shadow="hover">
              <div class="approval-header">
                <h3>待审批事项</h3>
                <el-button type="primary" size="small" @click="refreshApprovalRequests">刷新</el-button>
                <el-table :data="spDate" style="width: 100%">
                  <el-table-column prop="operation" label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" size="mini" @click="handleTodo(scope.$index, scope.row)">
                        办理
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="taskName" label="任务名称"></el-table-column>
                  <el-table-column prop="starter" label="发起人"></el-table-column>
                  <el-table-column prop="assignee" label="办理人"></el-table-column>
                  <el-table-column prop="createTime" label="任务创建时间"></el-table-column>
                  <el-table-column prop="startTime" label="流程启动时间"></el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="approval-card" shadow="hover">
              <div class="approval-header">
                <h3>已入库物资</h3>
                <el-table :data="rkWareNoticeTabBakList" style="width: 100%">
                  <el-table-column prop="id" label="编号" width="80"></el-table-column>
                  <el-table-column prop="goodsName" label="物资名称"></el-table-column>
                  <el-table-column prop="recoil" label="类型" width="100"></el-table-column>
                  <el-table-column prop="acceNum" label="数量" width="80"></el-table-column>
                  <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                  <el-table-column prop="createTime" label="入库日期" width="120"></el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 数据统计区域 -->
        <div class="stats-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="stats-card" shadow="hover">
                <div class="stats-header">
                  <h3>今日出库单数</h3>
                  <div class="stats-number">{{ todaySize }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stats-card" shadow="hover">
                <div class="stats-header">
                  <h3>今日出库金额</h3>
                  <div class="stats-number">{{ todayMoney }} 元</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stats-card" shadow="hover">
                <div class="stats-header">
                  <h3>本月累计出库金额</h3>
                  <div class="stats-number">{{ monthMoney }} 元</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="chart-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card" shadow="hover">
                <div ref="trendChart1" style="height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card" shadow="hover">
                <div ref="sixMonthAmountChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="monthlyDistributionChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="teamDistributionChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="sixMonthDistributionChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="budgetRadarChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="usageGaugeChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card" shadow="hover">
                <div ref="compareBarChart" style="height: 300px;"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import * as echarts from 'echarts';
import axios from 'axios';
import { getMyTodoList } from "@/views/todo/api/myTodoList";
import { listRkWareNoticeTabBaks } from "@/api/system/rkWareNoticeTabBak";

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters(['favoriteRouter']),
    nickName() {
      return this.$store.state.user.nickName;
    }
  },
  data() {
    return {
      todaySize: null,
      monthMoney: null,
      todayMoney: null,
      hoverIndex: -1,
      deptLabel: '',
      avatarUrl: '',
      responseData: [],
      rkWareNoticeTabBakList: [],
      spDate: [],
      searchParams: {
        taskName: "",
        processName: "",
        pageNum: 1,
        pageSize: 10
      },
      charts: {
        trendChart1: null,
        sixMonthAmountChart: null,
        monthlyDistributionChart: null,
        teamDistributionChart: null,
        sixMonthDistributionChart: null,
        budgetRadarChart: null,
        usageGaugeChart: null,
        compareBarChart: null
      },
    };
  },
  mounted() {
    this.deptLabel = this.$store.state.user.dept.length > 0 ? this.$store.state.user.dept[0].label : '';
    this.avatarUrl = this.$store.getters.avatar;
    this.initCharts();
    this.getAllTodoListByParamsAndRender(this.searchParams);
  },
  methods: {
    ...mapActions(['DELETE_ROUTE']),
    removeRoute(index) {
      const ids = index || [];
      this.DELETE_ROUTE(ids);
    },
    subName(name) {
      return name.length > 4 ? name.substring(0, 4) + '...' : name;
    },
    initCharts() {
      this.$nextTick(() => {
        Object.keys(this.charts).forEach(key => {
          this.charts[key] = echarts.init(this.$refs[key]);
        });
        this.updateCharts();
        this.dayAMonthCk();
        this.sixMonthCk();
        this.ckMoneyVS();
        this.monthOutTo();
        this.sixMonthOutTo();
        this.groupCk();
        this.monthYsOut();
        this.totalUse();
        this.yearCkRk();
      });
    },
    refreshApprovalRequests() {
      this.searchParams.processName = "";
      this.searchParams.taskName = "";
      this.getAllTodoListByParamsAndRender(this.searchParams);
    },
    handleTodo(index, row) {
      console.log("todo", row);
      const {formKey, taskId, businessKey} = row;
      this.$router.push({
        path: `/process/${formKey}/${taskId}?id=${businessKey}&taskName=处理待办`,
        meta: {title: "测试"},
        params: {row}
      })
    },
    getAllTodoListByParamsAndRender(params) {
      const {pageSize = 10, pageNum = 1, processName = "", taskName = ""} = params;
      getMyTodoList({
        pageSize,
        pageNum,
        isAsc: "asc",
        processName,
        taskName
      }).then(res => {
        this.responseData = res;
        console.log(this.responseData.rows)
        this.spDate = this.responseData.rows.slice(0, 3);
      });
      listRkWareNoticeTabBaks(this.queryParams).then(response => {
        this.rkWareNoticeTabBakList = response.rows.map(row => {
          return Object.keys(row).reduce((acc, key) => {
            // 检查每个值，如果为null则替换为''，否则保留原值
            acc[key] = row[key] === 'null' ? '' : row[key];
            return acc;
          }, {});
        });
        this.total = response.total;
        if (this.columns.length === 0) {
          this.columns = response.columns.map(column => {
            // 如果columns中也可能有null值，同样进行处理
            return column === null ? '' : column;
          });
        }
      })
    },
    dayAMonthCk() {
      axios.get('/dev-api/system/LargeScreen/dayAMonthCk')
        .then(response => {
          // 处理响应数据
          this.todaySize = response.data[0];
          this.todayMoney = response.data[1];
          this.monthMoney = response.data[2];
        })
    },
    sixMonthCk() {
      axios.get('/dev-api/system/LargeScreen/sixMonthCk')
        .then(response => {
          // 处理响应数据
          this.updateSixMonthAmountChart(response.data)
        })
    },
    ckMoneyVS() {
      axios.get('/dev-api/system/LargeScreen/ckMoneyVS')
        .then(response => {
          // 处理响应数据
          this.updateCompareBarChart(response.data);
        })
    },
    monthOutTo() {
      axios.get('/dev-api/system/LargeScreen/monthOutTo')
        .then(response => {
          // 处理响应数据
          this.updateMonthlyDistributionChart(response.data);
        })
    },
    sixMonthOutTo() {
      axios.get('/dev-api/system/LargeScreen/sixMonthOutTo')
        .then(response => {
          // 处理响应数据
          this.updateSixMonthDistributionChart(response.data);
        })
    },
    groupCk() {
      axios.get('/dev-api/system/LargeScreen/groupCk')
        .then(response => {
          // 处理响应数据
          this.updateTeamDistributionChart(response.data);
        })
    },
    monthYsOut() {
      axios.get('/dev-api/system/LargeScreen/monthYsOut/'+this.deptLabel)
        .then(response => {
          // 处理响应数据
          this.updateBudgetRadarChart(response.data);
        })
    },
    yearCkRk() {
      axios.get('/dev-api/system/LargeScreen/yearCkRk')
        .then(response => {
          // 处理响应数据
          this.updateTrendChart1(response.data);
        })
    },
    totalUse() {
      axios.get('/dev-api/system/LargeScreen/totalUse')
        .then(response => {
          // 处理响应数据
          this.updateUsageGaugeChart(response.data);
        })
    },
    updateCharts() {
      // 这个方法现在是空的，因为我们在各个单独的方法中更新图表
    },
    updateTrendChart1(data) {
      const centerName1 = '东区维修中心';
      const centerData1 = data[centerName1];
      const centerName2 = '南区维修中心';
      const centerData2 = data[centerName2];
      const centerName3 = '西区维修中心';
      const centerData3 = data[centerName3];
      const centerName4 = '仓储队';
      const centerData4 = data[centerName4];
      const option = {
        title: {
          text: '出入库单数趋势',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['东区维修中心', '西区维修中心', '南区维修中心', '仓储队'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '东区维修中心',
            type: 'line',
            data: centerData1,
            smooth: true,
          },
          {
            name: '西区维修中心',
            type: 'line',
            data: centerData3,
            smooth: true,
          },
          {
            name: '南区维修中心',
            type: 'line',
            data: centerData2,
            smooth: true,
          },
          {
            name: '仓储队',
            type: 'line',
            data: centerData4,
            smooth: true,
          }
        ]
      };
      this.charts.trendChart1.setOption(option);
    },
    updateSixMonthAmountChart(data) {
      const option = {
        title: {
          text: '近6个月出库数量/金额',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['金额', '数量'],
          bottom: 0
        },
        xAxis: {
          type: 'category',
          data: Object.keys(data)
        },
        yAxis: [
          {
            type: 'value',
            name: '金额',
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#FF8C00'
              }
            }
          },
          {
            type: 'value',
            name: '出库件数',
            position: 'right',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#409EFF'
              }
            }
          }
        ],
        series: [
          {
            name: '金额',
            type: 'bar',
            data: Object.values(data).map(item => item[1]),
            itemStyle: {
              color: '#5dc0e8'
            },
            yAxisIndex: 0
          },
          {
            name: '数量',
            type: 'line',
            data: Object.values(data).map(item => item[0]),
            smooth: true,
            itemStyle: {
              color: '#e87533'
            },
            lineStyle: {
              width: 2
            },
            yAxisIndex: 1
          }
        ]
      };
      this.charts.sixMonthAmountChart.setOption(option);
    },
    updateMonthlyDistributionChart(data) {
      const dataArray = Object.entries(data).map(([name, value]) => ({
        name,
        value: value
      }));
      const totalValue = dataArray.reduce((sum, item) => sum + parseFloat(item.value), 0).toFixed(2);
      const option = {
        title: [
          {
            text: '本月物资流向',
            left: 'left'
          },
          {
            text: totalValue + '万元',
            left: 'center',
            top: '45%'
          }
        ],
        legend: {
          bottom: 0
        },
        tooltip: {
          trigger: 'item',
        },
        series: [
          {
            name: '物资流向',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: '{c}万元',
              position: 'outside'
            },
            data: dataArray
          }
        ]
      };
      this.charts.monthlyDistributionChart.setOption(option);
    },
    updateTeamDistributionChart(data) {
      const dataArray = Object.entries(data).map(([name, value]) => ({
        name,
        value: (value / 10000).toFixed(2)
      }));
      const option = {
        title: {
          text: '小组出库金额(万元)',
          left: 'left'
        },
        legend: {
          bottom: 0
        },
        tooltip: {
          trigger: 'item',
        },
        series: [
          {
            name: '出库金额',
            type: 'pie',
            radius: '50%',
            data: dataArray,
            label: {
              show: true,
              formatter: '{c}万元',
              position: 'outside'
            },
          }
        ]
      };
      this.charts.teamDistributionChart.setOption(option);
    },
    updateSixMonthDistributionChart(data) {
      const month = this.getPreviousMonths();
      const reversedMonth = month.reverse();

      const categories = ['东区维修中心', '南区维修中心', '西区维修中心', '仓储队'];
      const seriesData = categories.map(category => ({
        name: category,
        type: 'bar',
        stack: 'total',
        data: new Array(6).fill(0)
      }));

      data.forEach((monthData, index) => {
        Object.entries(monthData).forEach(([key, value]) => {
          const categoryIndex = categories.indexOf(key);
          if (categoryIndex !== -1) {
            seriesData[categoryIndex].data[5 - index] = value;
          }
        });
      });

      const option = {
        title: {
          text: '近6月物资流向',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: categories,
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: reversedMonth
        },
        series: seriesData
      };

      this.charts.sixMonthDistributionChart.setOption(option);
    },
    updateBudgetRadarChart(data) {
      console.log(data)
      const dataArray = Object.entries(data).map(([name, value]) => ({
        name,
        value: value.toFixed(2)
      }));

      const radarIndicator = dataArray.map(item => ({
        name: item.name,
        max: 50
      }));

      const expenseValues = dataArray.map(item => parseFloat(item.value));

      const option = {
        title: {
          text: '近6月预算开支',
          left: 'left'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return `${params.seriesName}：<br>${params.value.join(', ')}`;
          }
        },
        legend: {
          bottom: 0,
          left: 'left'
        },
        radar: {
          indicator: radarIndicator
        },
        series: [
          {
            type: 'radar',
            name: '开支',
            data: [
              {
                value: expenseValues,
                name: '开支'
              }
            ]
          },
          {
            type: 'radar',
            name: '预算',
            data: [
              {
                value: new Array(dataArray.length).fill(30),
                name: '预算'
              }
            ]
          }
        ]
      };

      this.charts.budgetRadarChart.setOption(option);
    },
    updateUsageGaugeChart(data) {
      const value = (data / 100000).toFixed(2);
      console.log(value)
      const option = {
        title: {
          text: '本中心物资累计使用率',
          left: 'left'
        },
        series: [
          {
            type: 'gauge',
            progress: {
              show: true,
              width: 18
            },
            axisLine: {
              lineStyle: {
                width: 18
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              length: 15,
              lineStyle: {
                width: 2,
                color: '#999'
              }
            },
            pointer: {
              show: false
            },
            axisLabel: {
              distance: 25,
              color: '#999',
              fontSize: 14
            },
            detail: {
              valueAnimation: true,
              formatter: '{value}%',
              color: '#409EFF'
            },
            data: [
              {
                value: value,
                name: '使用率',
              }
            ]
          }
        ]
      };
      this.charts.usageGaugeChart.setOption(option);
    },
    updateCompareBarChart(data) {
      const time = this.getPreviousMonths();
      const option = {
        title: {
          text: '出库金额同比',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['今年', '去年', '前年'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: time
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '今年',
            type: 'bar',
            data: Object.values(data).map(item => item[0]),
          },
          {
            name: '去年',
            type: 'bar',
            data: Object.values(data).map(item => item[1]),
          },
          {
            name: '前年',
            type: 'bar',
            data: Object.values(data).map(item => item[2]),
          }
        ]
      };
      this.charts.compareBarChart.setOption(option);
    },
    getPreviousMonths() {
      const months = [];
      const date = new Date();
      date.setMonth(date.getMonth() - 1); // Start with last month

      for (let i = 0; i < 6; i++) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        months.unshift(`${year}-${month}`);
        date.setMonth(date.getMonth() - 1);
      }

      return months;
    }
  }
};
</script>

<style lang="scss" scoped>
.dashboard {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 24px;
}

.dashboard-header {
  margin-bottom: 24px;

  .header-content {
    h1 {
      font-size: 28px;
      margin-bottom: 8px;
      background: linear-gradient(45deg, #409EFF, #36D1DC);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
}

.dashboard-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
}

.left-panel {
  .user-card {
    height: 100%;
    overflow: hidden;

    .user-profile {
      text-align: center;
      padding: 20px 0;
      position: relative;

      .cover-image {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 80px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      .profile-avatar {
        position: relative;
        z-index: 1;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        border: 4px solid #fff;
        margin-top: 40px;
      }

      .profile-name {
        margin: 16px 0 8px;
        font-size: 20px;
        font-weight: 600;
      }

      .profile-dept {
        color: #606266;
        margin-bottom: 12px;
      }
    }
  }
}

.apps-section {
  margin: 24px 0;
  padding: 0 20px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  .apps-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;

    .app-item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 12px;
      border-radius: 8px;
      transition: all 0.3s;
      background-color: #f0f2f5;

      &:hover {
        background-color: #e6e8eb;
        transform: translateY(-2px);
      }

      .app-link {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-decoration: none;
        color: #606266;
      }

      .app-icon {
        font-size: 24px;
        margin-bottom: 8px;
      }

      .app-name {
        font-size: 12px;
        text-align: center;
        word-break: break-word;
      }

      .delete-button {
        position: absolute;
        top: -8px;
        right: -8px;
        opacity: 0;
        transition: opacity 0.3s;
      }

      &:hover .delete-button {
        opacity: 1;
      }
    }
  }
}

.right-panel {
  .approval-card,
  .inventory-card,
  .stats-card,
  .chart-card {
    margin-bottom: 20px;

    .el-card__body {
      padding: 20px;
    }
  }

  .stats-section {
    .stats-card {
      .stats-header {
        text-align: center;

        h3 {
          font-size: 16px;
          color: #606266;
          margin-bottom: 10px;
        }

        .stats-number {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
        }
      }
    }
  }

  .chart-section {
    .chart-card {
      height: 100%;
    }
  }
}
</style>
