<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">
          <div class="user-profile">
            <el-avatar :src="avatarUrl" :size="100" class="profile-avatar"></el-avatar>
            <h2 class="profile-name">{{ this.$store.state.user.nickName }}</h2>
            <p class="profile-dept">{{ deptLabel }}</p>
            <el-tag size="small" effect="dark" class="role-tag">{{ userRole }}</el-tag>
          </div>

          <!-- 常用应用区域 -->
          <div class="apps-section">
            <h3 class="section-title">常用应用</h3>
            <div class="apps-grid">
              <router-link
                  v-for="fRouter in favoriteRouter"
                  :key="fRouter.path"
                  :to="fRouter.path"
                  class="app-item"
              >
                <svg-icon :icon-class="fRouter.meta.icon" class="app-icon"/>
                <span>{{ subName(fRouter.name) }}</span>
              </router-link>
            </div>
          </div>

          <!-- 系统公告区域 -->
          <div class="announcement-section">
            <h3 class="section-title">系统公告</h3>
            <el-carousel height="180px" indicator-position="outside" class="announcement-carousel">
              <el-carousel-item v-for="item in announcements" :key="item.id" class="carousel-item">
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
              </el-carousel-item>
            </el-carousel>
          </div>
        </el-card>
      </div>

      <!-- 右侧主要内容区域 -->
      <div class="right-panel">
        <!-- 数据卡片区域 -->
        <div class="stats-cards">
          <el-card class="stat-card entrance" shadow="hover">
            <div class="stat-content">
              <div class="stat-header">
                <h3>出入库任务</h3>
                <el-dropdown @command="handleClick" trigger="click">
                  <span class="el-dropdown-link">
                    详情<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="['chuCount', chuCount]">出库任务 ({{ chuCount }})</el-dropdown-item>
                    <el-dropdown-item :command="['ruCount', ruCount]">入库任务 ({{ ruCount }})</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="stat-numbers">
                <div class="stat-item">
                  <span class="label">未完成</span>
                  <span class="value">{{ chuCount + ruCount }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">未阅读</span>
                  <span class="value">{{ quest }}</span>
                </div>
              </div>
              <el-progress
                  :percentage="calculateProgress(chuCount + ruCount, quest)"
                  :format="progressFormat"
                  class="stat-progress"
              ></el-progress>
            </div>
          </el-card>

          <el-card class="stat-card warehouse" shadow="hover">
            <div class="stat-content">
              <div class="stat-header">
                <h3>出入库通知单</h3>
                <el-dropdown @command="handleClick" trigger="click">
                  <span class="el-dropdown-link">
                    详情<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="['chuTaskList', outNotice]">出库 ({{ outNotice }})</el-dropdown-item>
                    <el-dropdown-item :command="['ruTaskList', inNotice]">入库 ({{ inNotice }})</el-dropdown-item>
                    <el-dropdown-item :command="['audit', audit]">出库待审核 ({{ audit }})</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="stat-numbers">
                <div class="stat-item">
                  <span class="label">已查看</span>
                  <span class="value">{{ outNotice + inNotice }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">未查看</span>
                  <span class="value">{{ inNoticeCount }}</span>
                </div>
              </div>
              <el-progress
                  :percentage="calculateProgress(outNotice + inNotice, inNoticeCount)"
                  :format="progressFormat"
                  class="stat-progress"
              ></el-progress>
            </div>
          </el-card>

          <el-card class="stat-card warning" shadow="hover">
            <div class="stat-content">
              <div class="stat-header">
                <h3>预警通知</h3>
                <el-dropdown @command="handleClick" trigger="click">
                  <span class="el-dropdown-link">
                    详情<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="['overdue', overdue]">超期预警 ({{ overdue }})</el-dropdown-item>
                    <el-dropdown-item :command="['expired', overProtected]">过保预警 ({{ overProtected }})</el-dropdown-item>
                    <el-dropdown-item :command="['safety', security]">安全预警 ({{ security }})</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="stat-numbers">
                <div class="stat-item">
                  <span class="label">未处理</span>
                  <span class="value">{{ overdue + overProtected + security }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">已处理</span>
                  <span class="value">{{ securityData < 0 ? 0 : securityData }}</span>
                </div>
              </div>
              <el-progress
                  :percentage="calculateProgress(securityData, overdue + overProtected + security)"
                  :format="progressFormat"
                  class="stat-progress"
              ></el-progress>
            </div>
          </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="chart-section">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-header">
              <h3>任务完成情况</h3>
              <el-radio-group v-model="chartType" size="small" @change="updateChart">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="pie">饼图</el-radio-button>
              </el-radio-group>
            </div>
            <div ref="taskChart" class="chart-container"></div>
          </el-card>
        </div>

        <!-- 待办事项区域 -->
        <div class="tasks-section">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-card class="tasks-card" shadow="hover">
                <div class="tasks-header">
                  <h3>待审批事项</h3>
                  <el-button type="primary" size="small" @click="refreshApprovalRequests">刷新</el-button>
                </div>
                <table-template
                    :data="tableData"
                    :total="total"
                    @page-change="handlePageChange"
                >
                  <template #columns>
                    <el-table-column prop="operation" label="操作">
                      <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>
                  </template>
                </table-template>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="pie-chart-card" shadow="hover">
                <div ref="approvalPieChart" class="pie-chart-container"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 保持原有的 script 部分不变
import TableTemplate from "@/components/TableTemplate/index.vue";
import {mapGetters} from "vuex";
import {getMyTodoList} from "@/views/todo/api/myTodoList";
import {alarmData, entryAnd, getTaskInfo} from "@/api/common";
import * as echarts from "echarts";

export default {
  name: "Dashboard",
  components: {TableTemplate},
  computed: {
    ...mapGetters(["favoriteRouter"]),
    tableData() {
      return this.responseData.rows || []
    },
    total() {
      return this.responseData.total || 0
    }
  },
  data() {
    return {
      chuCount: 0,
      ruCount: 0,
      deptLabel: "",
      overdue: 0,
      overProtected: 0,
      security: 0,
      securityData: 0,
      outNotice: 0,
      inNotice: 0,
      audit: 0,
      avatarUrl: this.$store.getters.avatar,
      inNoticeCount: 0,
      NoticeCount: 0,
      quest: 0,
      task: 0,
      userRole: "管理员",
      responseData: [],
      quickActions: [
        {name: "创建任务", handler: this.createTask},
        {name: "生成报表", handler: this.generateReport},
        {name: "系统设置", handler: this.openSettings},
        {name: "帮助中心", handler: this.openHelp},
      ],
      searchParams: {
        taskName: "",
        processName: "",
        pageNum: 1,
        pageSize: 10
      },
      chartType: 'bar',
      approvalRequests: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: 10,
      totalApprovals: 0,
      announcements: [
        {id: 1, title: "系统升级通知", content: "系统将于本周六凌晨2点进行升级维护，预计耗时2小时。"},
        {id: 2, title: "新功能上线", content: "库存预警功能已上线，请及时查看并处理库存预警信息。"},
        {id: 3, title: "安全提醒", content: "请注意保护您的账号安全，定期更改密码并不要将密码告知他人。"},
      ],
    };
  },


  mounted() {
    this.deptLabel = this.$store.state.user.dept.length > 0 ? this.$store.state.user.dept[0].label : "";
    this.initData();
    this.initTaskChart();
    this.fetchApprovalRequests();
    this.initApprovalPieChart();
    this.getAllTodoListByParamsAndRender(this.searchParams)
  },

  methods: {


    getAllTodoListByParamsAndRender(params) {
      const {pageSize = 1, pageNum = 10, processName = "", taskName = ""} = params;
      getMyTodoList({
        pageSize,
        pageNum,
        isAsc: "asc",
        processName,
        taskName
      }).then(res => {
        this.responseData = res;
      });
    },

    handlePageChange() {
    },
    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}
      })

    },


    initData() {
      this.inNoticeCount = parseInt(localStorage.getItem('inNoticeCount')) || 0;
      this.quest = parseInt(localStorage.getItem('task')) || 0;
      this.securityData = parseInt(localStorage.getItem('securityData')) || 0;

      getTaskInfo().then((res) => {
        this.chuCount = res.data.out;
        this.ruCount = res.data.in;
        this.audit = res.data.audit;
        this.task = res.data.out + res.data.in;
        if (this.quest === 0) {
          this.quest = this.task;
          localStorage.setItem('task', this.quest);
        }
      });

      alarmData().then((res) => {
        this.overdue = res.overdue;
        this.overProtected = res.overProtected;
        this.security = res.security;
        if (this.securityData === 0) {
          this.securityData = res.overdue + res.overProtected + res.security;
          localStorage.setItem('securityData', this.securityData);
        }
      });

      entryAnd().then((res) => {
        this.outNotice = res.data.out;
        this.inNotice = res.data.in;
        this.NoticeCount = res.data.out + res.data.in;
        if (this.inNoticeCount === 0) {
          this.inNoticeCount = this.NoticeCount;
          localStorage.setItem('inNoticeCount', this.inNoticeCount);
        }
      });
    },
    initTaskChart() {
      this.updateChart();

    },
    updateChart() {
      const chartDom = this.$refs.taskChart;
      const myChart = echarts.init(chartDom);
      let option;

      const data = [
        {name: '出库任务', value: this.chuCount},
        {name: '入库任务', value: this.ruCount},
        {name: '预警处理', value: this.securityData},
      ];

      switch (this.chartType) {
        case 'bar':
          option = this.getBarChartOption(data);
          break;
        case 'line':
          option = this.getLineChartOption(data);
          break;
        case 'pie':
          option = this.getPieChartOption(data);
          break;
      }

      myChart.setOption(option);
    },
    getBarChartOption(data) {
      return {
        title: {text: '任务完成情况'},
        tooltip: {trigger: 'axis'},
        xAxis: {type: 'category', data: data.map(item => item.name)},
        yAxis: {type: 'value'},
        series: [{type: 'bar', data: data.map(item => item.value)}]
      };
    },
    getLineChartOption(data) {
      return {
        title: {text: '任务完成趋势'},
        tooltip: {trigger: 'axis'},
        xAxis: {type: 'category', data: data.map(item => item.name)},
        yAxis: {type: 'value'},
        series: [{type: 'line', data: data.map(item => item.value)}]
      };
    },
    getPieChartOption(data) {
      return {
        title: {text: '任务分布'},
        tooltip: {trigger: 'item'},
        series: [{
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
    },
    subName(name) {
      const len = this.byteLength(name);
      if (len / 2 == name.length) {
        return name.substring(0, 4);
      } else if (len / 2 < name.length) {
        return name.substring(0, 5);
      }
    },
    byteLength(str) {
      let len = 0;
      for (let i = 0; i < str.length; i++) {
        const code = str.charCodeAt(i);
        if (code >= 0x0000 && code <= 0x00FF) {
          len += 1;
        } else {
          len += 2;
        }
      }
      return len;
    },
    handleClick([type, value]) {
      switch (type) {
        case 'overdue':
        case 'expired':
        case 'safety':
          this.securityData -= value;
          localStorage.setItem('securityData', this.securityData);
          this.$router.push(type === 'safety' ? "/chart/safetyStock" : "/chart/overInsured");
          break;
        case 'chuTaskList':
        case 'ruTaskList':
          this.NoticeCount -= value;
          localStorage.setItem('inNoticeCount', this.NoticeCount);
          this.$router.push(type === 'chuTaskList' ? "/link/ckOrders" : "/rk/trkNotice");
          break;
        case 'audit':
          this.$router.push("/link/ckOrders");
          break;
        case 'chuCount':
        case 'ruCount':
          this.task -= value;
          localStorage.setItem('task', this.task);
          this.$router.push(type === 'chuCount' ? "/server/pickingwavegoods" : "/server/ongoodsshelf");
          break;
      }
      this.updateChart();
    },
    handleApprove(row) {
      row.status = 'Approved';
      this.$message.success('审批已通过');
      this.updateApprovalPieChart();
    },
    handleReject(row) {
      row.status = 'Rejected';
      this.$message.error('审批已拒绝');
      this.updateApprovalPieChart();
    },
    calculateProgress(completed, total) {
      return total > 0 ? (completed / total) * 100 : 0;
    },
    progressFormat(percentage) {
      return percentage.toFixed(0) + '%';
    },
    createTask() {
      this.$message.info('创建任务功能待实现');
    },
    generateReport() {
      this.$message.info('生成报表功能待实现');
    },
    openSettings() {
      this.$router.push('/settings');
    },
    openHelp() {
      window.open('https://help.example.com', '_blank');
    },
    fetchApprovalRequests() {
      this.tableLoading = true;
      // 模拟API调用
      setTimeout(() => {
        this.approvalRequests = [
          {id: 4, type: "出库申请", requester: "赵六", date: "2023-05-18", status: "Pending"},
        ];
        this.totalApprovals = 20; // 假设总共有20条数据
        this.tableLoading = false;
        this.updateApprovalPieChart();
      }, 1000);
    },
    refreshApprovalRequests() {
      this.searchParams.processName = "";
      this.searchParams.taskName = "";
      this.getAllTodoListByParamsAndRender(this.searchParams);
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchApprovalRequests();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchApprovalRequests();
    },
    initApprovalPieChart() {
      const chartDom = this.$refs.approvalPieChart;
      const myChart = echarts.init(chartDom);
      myChart.setOption(this.getApprovalPieChartOption());
    },
    updateApprovalPieChart() {
      const chartDom = this.$refs.approvalPieChart;
      const myChart = echarts.init(chartDom);
      myChart.setOption(this.getApprovalPieChartOption());
    },
    getApprovalPieChartOption() {
      const typeCount = {};
      this.approvalRequests.forEach(request => {
        typeCount[request.type] = (typeCount[request.type] || 0) + 1;
      });
      const data = Object.keys(typeCount).map(key => ({name: key, value: typeCount[key]}));
      return {
        title: {text: '审批类型统计'},
        tooltip: {trigger: 'item'},
        series: [{
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
    },
  }
};
</script>

<style lang="scss" scoped>
.dashboard {
  min-height: 100vh;
  background: #f5f7fa;
  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%;

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

      .profile-avatar {
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        border: 4px solid #fff;
      }

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

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

      .role-tag {
        background: linear-gradient(45deg, #409EFF, #36D1DC);
        border: none;
        padding: 4px 12px;
      }
    }
  }
}

.apps-section {
  margin: 24px 0;

  .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 {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 12px;
      border-radius: 8px;
      transition: all 0.3s;
      text-decoration: none;
      color: #606266;

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

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

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-bottom: 24px;

  .stat-card {
    position: relative;
    overflow: hidden;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .stat-content {
      padding: 20px;

      .stat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h3 {
          font-size: 18px;
          font-weight: 600;
        }
      }

      .stat-numbers {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .stat-item {
          text-align: center;

          .label {
            display: block;
            color: #909399;
            margin-bottom: 4px;
          }

          .value {
            font-size: 24px;
            font-weight: 600;
          }
        }
      }
    }
  }
}

.chart-section {
  margin-bottom: 24px;

  .chart-card {
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        font-size: 18px;
        font-weight: 600;
      }
    }

    .chart-container {
      height: 400px;
    }
  }
}

.tasks-section {
  .tasks-card {
    .tasks-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .pie-chart-card {
    .pie-chart-container {
      height: 300px;
    }
  }
}

.announcement-section {
  .announcement-carousel {
    .carousel-item {
      padding: 20px;
      background: #f5f7fa;
      border-radius: 8px;

      h4 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 12px;
      }

      p {
        color: #606266;
        line-height: 1.6;
      }
    }
  }
}

@media screen and (max-width: 1200px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style>
