<template>
  <div class="dashboard-page">
    <el-row :gutter="20" class="mb-20 card-row">
      <el-col v-if="curOrg != '企业单位'" :span="13">
        <el-card shadow="hover">
          <div class="card-header">
            <div class="left-icon">
              <img src="@/assets/index_images/index-icon1@2x.png" alt="" />
              <h3>成本监审办理情况</h3>
            </div>
            <div class="header-actions">
              <el-cascader
                v-model="areaCode"
                :options="districtTree"
                :show-all-levels="false"
                :props="districtTreeCascaderProps"
                style="width: 120px; margin-right: 10px"
                placeholder="请选择"
              />
              <el-date-picker
                v-model="year"
                type="year"
                placeholder="选择年"
                format="yyyy"
                value-format="yyyy"
                style="width: 120px"
              ></el-date-picker>
            </div>
          </div>
          <div
            ref="chartRef"
            style="width: 100%; height: 320px; margin-top: 20px"
          ></div>
          <!-- 轮播显示器 -->
          <ul
            class="carousel"
            @mouseenter="pauseCarousel"
            @mouseleave="resumeCarousel"
          >
            <li
              v-for="(item, idx) in totalPages"
              :key="idx"
              @click="goToPage(idx)"
            >
              <i :class="{ active: idx === chartCurrentPage }"></i>
            </li>
          </ul>
        </el-card>
      </el-col>
      <el-col :span="curOrg != '企业单位' ? 11 : 24">
        <el-card shadow="hover">
          <div class="card-header">
            <div class="left-icon">
              <img src="@/assets/index_images/index-icon2@2x.png" alt="" />
              <h3>最新消息</h3>
            </div>
            <el-button type="text" size="small" @click="loadMoreNews">
              更多 &gt;
            </el-button>
          </div>
          <ul class="news-list card-content">
            <li
              v-for="(item, idx) in newsList"
              :key="idx"
              class="news-item-new"
            >
              <span class="news-dot"></span>
              <span class="news-title-text">{{ item.noticeTitle }}</span>
              <span class="news-author">{{ item.remark || '管理员' }}</span>
              <span class="news-time">{{ item.createTime }}</span>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：本人待办事项 -->
    <el-row class="mb-20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="card-header">
            <div class="left-icon">
              <img src="@/assets/index_images/index-icon5@2x.png" alt="" />
              <h3>本人待办事项</h3>
            </div>
            <div class="search-actions">
              <el-input
                v-model="todoSearchQuery"
                placeholder="监审项目名称"
                style="width: 300px; margin-right: 10px"
                clearable
              />
              <el-button type="primary" @click="handleTodoSearch">
                查询
              </el-button>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="todoList"
            style="width: 100%"
            :stripe="false"
            class="no-zebra"
            border
            default-expand-all
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              header-align="center"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="curOrg == '企业单位'">
                  {{ scope.$index + 1 }}
                </span>
                <!-- 只显示父节点的序号 -->
                <div v-else>
                  <span v-if="scope.row.children">
                    {{ getParentNodeIndex(scope.row) }}
                  </span>
                  <span v-else></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="projectName"
              label="成本监审项目名称"
              show-overflow-tooltip
              header-align="center"
              align="left"
            />
            <el-table-column
              :prop="curOrg == '企业单位' ? 'auditedUnitName' : 'auditObject'"
              label="监审对象"
              header-align="center"
              align="left"
              show-overflow-tooltip
            />
            <el-table-column
              prop="auditPeriod"
              label="监审期间"
              header-align="center"
              align="center"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              v-if="curOrg != '企业单位'"
              prop="source"
              label="立项来源"
              header-align="center"
              align="center"
              width="100"
            />
            <el-table-column
              v-if="curOrg != '企业单位'"
              prop="form"
              label="监审形式"
              header-align="center"
              align="center"
              width="100"
            />
            <el-table-column
              prop="currentNodeName"
              label="状态"
              align="center"
              width="150"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isSubTask">
                  <span>
                    {{ scope.row.currentNodeName }}-{{ scope.row.statusName }}
                  </span>
                </span>
                <span v-else>{{ scope.row.statusName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="260">
              <template slot-scope="scope">
                <div v-if="curOrg == '企业单位'">
                  <el-button
                    v-if="
                      (scope.row.currentNode === 'clcs' ||
                        scope.row.currentNode === 'tjcl') &&
                      (scope.row.status === '100' ||
                        scope.row.status === '500' ||
                        scope.row.status === '600')
                    "
                    size="mini"
                    type="text"
                    @click="handleEdit(scope.row)"
                  >
                    填报任务
                  </el-button>
                  <el-button
                    v-if="
                      scope.row.currentNode === 'yjfk' &&
                      scope.row.status === '250'
                    "
                    size="mini"
                    type="text"
                    @click="handleEdit(scope.row)"
                  >
                    意见反馈
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleMessage(scope.row)"
                  >
                    查看
                  </el-button>
                </div>
                <div v-else>
                  <span v-if="!scope.row.isSubTask" class="action-buttons">
                    <el-button
                      type="text"
                      size="small"
                      @click="handleViewTaskDetail(scope.row)"
                    >
                      任务详情
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="handleOpenMainDetails(scope.row)"
                    >
                      任务办理
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="handleCheckRecord(scope.row)"
                    >
                      备忘录
                    </el-button>
                  </span>
                  <span v-if="scope.row.isSubTask" class="action-buttons">
                    <el-button
                      v-if="
                        scope.row.currentNode === 'clcs' &&
                        (scope.row.status === '200' ||
                          scope.row.status === '600')
                      "
                      type="text"
                      size="small"
                      @click="handleOpenDetails(scope.row)"
                    >
                      资料初审
                    </el-button>
                    <el-button
                      v-if="
                        (scope.row.currentNode === 'sdsh' ||
                          scope.row.currentNode === 'yjfk') &&
                        scope.row.status === '200'
                      "
                      type="text"
                      size="small"
                      @click="handleOpenDetails(scope.row)"
                    >
                      成本审核
                    </el-button>
                    <el-button
                      v-if="
                        scope.row.currentNode === 'yjgz' &&
                        scope.row.status === '200'
                      "
                      type="text"
                      size="small"
                      @click="handleOpenDetails(scope.row)"
                    >
                      意见告知
                    </el-button>
                    <el-button
                      v-if="
                        scope.row.currentNode === 'yjfk' &&
                        scope.row.status === '260'
                      "
                      type="text"
                      size="small"
                      @click="handleOpenDetails(scope.row)"
                    >
                      审核
                    </el-button>
                    <el-button
                      v-if="scope.row.status === '300'"
                      type="text"
                      size="small"
                      @click="handleHf(scope.row)"
                    >
                      恢复
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="handleMessage(scope.row, 'chengben')"
                    >
                      查看
                    </el-button>
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：本人备忘录 -->
    <el-row v-if="curOrg != '企业单位'" class="card-row">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="card-header">
            <h3>本人备忘录</h3>
            <div class="search-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入关键词"
                style="width: 180px"
                clearable
              ></el-input>
              <el-button
                type="primary"
                style="margin-left: 10px"
                size="small"
                icon="el-icon-search"
                @click="handleSearch"
              >
                查询
              </el-button>
            </div>
          </div>
          <el-row class="mt20">
            <el-col :span="13">
              <div class="calendar-container">
                <div class="calendar-header">
                  <el-button
                    type="text"
                    class="calendar-btn"
                    @click="handlePrevMonth"
                  >
                    <i class="el-icon-arrow-left"></i>
                  </el-button>
                  <span class="month-text">{{ setCalendarTitle() }}年</span>
                  <el-button
                    type="text"
                    class="calendar-btn"
                    @click="handleNextMonth"
                  >
                    <i class="el-icon-arrow-right"></i>
                  </el-button>
                </div>
                <el-calendar
                  ref="calendar"
                  v-model="selectedDate"
                  :first-day-of-week="0"
                >
                  <!-- 自定义日期单元格 -->
                  <template slot="dateCell" slot-scope="{ date, data }">
                    <el-tooltip placement="top">
                      <div
                        class="calendar-cell"
                        @click="handleDateClick(date, data)"
                      >
                        <!-- 公历日期 -->
                        <div class="calendar-date-number">
                          {{ data.day.split('-').slice(-1)[0] }}
                        </div>
                        <!-- 农历日期和节日 -->
                        <div class="calendar-lunar-info">
                          <!-- 公历节日 -->
                          {{ getLunarInfo(date).IDayCn }}
                          <span class="calendar-festival">
                            {{
                              getLunarInfo(date).festival
                                ? getLunarInfo(date).festival + ' '
                                : ''
                            }}
                            {{
                              getLunarInfo(date).lunarFestival
                                ? getLunarInfo(date).lunarFestival + ' '
                                : ''
                            }}
                            {{
                              getLunarInfo(date).Term
                                ? getLunarInfo(date).Term
                                : ''
                            }}
                          </span>
                        </div>
                        <div
                          v-if="getTasksByDate(date).length > 0"
                          class="task-indicator"
                        ></div>
                      </div>
                      <div slot="content">
                        <template v-if="getTasksByDate(date).length > 0">
                          <div
                            v-for="(task, index) in getTasksByDate(date)"
                            :key="index"
                            class="task-item"
                          >
                            <div class="task-title">
                              {{ index + 1 }}.{{ task.projectName }}[{{
                                task.timePeriod
                              }}]
                            </div>
                          </div>
                        </template>
                        <template v-else>
                          <div class="no-tasks">暂无任务安排</div>
                        </template>
                      </div>
                    </el-tooltip>
                  </template>
                </el-calendar>
              </div>
            </el-col>
            <el-col :span="10">
              <ul class="news-list card-content">
                <li
                  v-for="(item, idx) in memoList"
                  :key="idx"
                  class="news-item mb10"
                >
                  <div class="news-content">
                    <div class="news-title mb10">
                      <img
                        v-if="item.type === 'warning'"
                        src="@/assets/index_images/index-icon6-light@2x.png"
                        alt=""
                        style="width: 15px; height: 15px"
                      />
                      <img
                        v-else
                        src="@/assets/index_images/index-icon6@2x.png"
                        alt=""
                        style="width: 15px; height: 15px"
                      />
                      <span class="ml10">{{ item.task }}</span>
                    </div>
                    <div class="news-meta mb10">
                      <div class="left-icon w40">
                        <img
                          style="
                            width: 14px;
                            height: 14px;
                            vertical-align: middle;
                          "
                          src="@/assets/index_images/index-icon8@2x.png"
                        />
                        <span>{{ item.title }}</span>
                      </div>
                      <div class="left-icon">
                        <img
                          style="
                            width: 14px;
                            height: 14px;
                            vertical-align: middle;
                          "
                          src="@/assets/index_images/index-icon4@2x.png"
                        />
                        <span>{{ item.memoDate }}</span>
                      </div>
                    </div>
                    <div class="news-meta">
                      <div class="left-icon content-text">
                        <img
                          style="
                            width: 14px;
                            height: 14px;
                            vertical-align: middle;
                          "
                          src="@/assets/index_images/index-icon9@2x.png"
                        />
                        <span class="content-text">{{ item.content }}</span>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
              <!-- 分页 -->
              <el-pagination
                v-if="listTotal > 0"
                :current-page="searchParams.page"
                :page-size="searchParams.pageSize"
                :page-sizes="[50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="listTotal"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详情弹窗组件 -->
    <details-dialog
      :id="selectedProject && selectedProject.id"
      ref="detailsRef"
      :selected-project="selectedProject"
      :visible.sync="detailsVisible"
      :current-node="selectedProject && selectedProject.currentNode"
      :current-status="selectedProject && selectedProject.status"
      :task-info="selectedProject"
      @close="handleDetailsClose"
      @refresh="handleRefresh"
    />
    <!-- 主详情弹窗组件 -->
    <mainDetailsDialog
      :id="selectedProject && selectedProject.id"
      ref="mainDetailsRef"
      :visible.sync="mainDetailsVisible"
      :current-node="selectedProject && selectedProject.currentNode"
      :current-status="selectedProject && selectedProject.status"
      @close="handleMainDetailsClose"
      @refresh="handleMainRefresh"
    />
    <taskInfo ref="taskInfo" />
    <!-- 成本监审信息弹窗 -->
    <cbjs-info
      :id="cbjsInfoData && cbjsInfoData.id"
      :selected-project="cbjsInfoData"
      :visible.sync="cbjsInfoVisible"
      :current-node="cbjsInfoData && cbjsInfoData.currentNode"
      :current-status="cbjsInfoData && cbjsInfoData.status"
    />
    <taskDetail ref="taskDetail" />
    <!-- 填报任务侧边弹窗 -->
    <task-fill-in
      ref="taskFillIn"
      :visible.sync="taskFillInVisible"
      :task-info="currentTaskInfo"
      :view-mode="taskViewMode"
      @close="handleTaskFillInClose"
      @refresh="handleTaskFillInRefresh"
    />
  </div>
</template>

<script>
  // 引入地区选择混入
  import { regionMixin } from '@/mixins/useDict'
  import * as echarts from 'echarts'
  import { memoManageMixin } from '@/views/costAudit/projectInfo/auditProjectManage/memoManage/memoManageMixin'
  import { doProcessBtn } from '@/api/dataPreliminaryReview'
  import { getReviewTaskList } from '@/api/audit/auditIndex'
  import { getChartList, getMsgList, getEnterpriseList } from '@/api/home'
  import detailsDialog from '@/views/costAudit/auditInfo/auditManage/details.vue'
  import mainDetailsDialog from '@/views/costAudit/auditInfo/auditManage/mainDetails.vue'
  import taskInfo from '@/components/task/taskInfo.vue'
  import cbjsInfo from '@/components/task/cbjsInfo.vue'
  import taskDetail from '@/components/task/taskDetail.vue'
  import TaskFillIn from '@/views/EntDeclaration/auditTaskManagement/taskFillIn.vue'
  export default {
    name: 'Dashboard',
    components: {
      detailsDialog,
      taskInfo,
      cbjsInfo,
      mainDetailsDialog,
      taskDetail,
      TaskFillIn,
    },
    mixins: [regionMixin, memoManageMixin],
    data() {
      return {
        areaCode: '140000',
        year: '2025',
        auditType: '山西省公立幼儿园教育成本监审',
        searchKeyword: '',
        todoSearchQuery: '',
        // 轮播相关变量
        chart: null,
        chartTimer: null,
        chartCurrentPage: 0,
        chartPageSize: 9,
        totalPages: 0,
        allCategories: [],
        allCompletedData: [],
        allInProgressData: [],
        newsList: [],
        todoList: [],
        memoList: [],
        currentDate: new Date(),
        selectedDate: '',
        showTooltip: false,
        // 成本审核列表相关
        currentPage: 1,
        pageSize: 100,
        total: 0,
        loading: false,
        detailsVisible: false,
        selectedProject: null,
        cbjsInfoVisible: false,
        cbjsInfoData: null,
        mainDetailsVisible: false,
        curOrg: '',
        // 填报任务弹窗相关
        taskFillInVisible: false,
        currentTaskInfo: {},
        taskViewMode: false,
      }
    },
    watch: {
      // 监听年份变化
      year(newVal) {
        if (newVal) {
          this.loadChartData()
        }
      },
      // 监听地区变化
      areaCode(newVal) {
        if (newVal) {
          this.loadChartData()
        }
      },
    },
    mounted() {
      this.$el.querySelector('div.el-calendar__header').remove()
      let user = this.$permission.getUserInfo()
      this.curOrg = this.$store.state.user.userInfo.curOrg
      if (user.dataScope === 0) {
        this.areaCode = user.provinceCode
      } else if (user.dataScope === 1) {
        this.areaCode = user.cityCode
      } else if (user.dataScope === 2) {
        this.areaCode = user.countyCode
      }
      if (this.curOrg != '企业单位') {
        this.initChart()
        this.initCalendarData('index')
      }
      this.getTodoList()
      this.loadNewsList()
    },
    methods: {
      getTodoList() {
        if (this.curOrg === '企业单位') {
          this.getEnterpriseTodoList()
        } else {
          this.loadAuditProjectList()
        }
      },
      // 加载最新消息
      async loadNewsList() {
        try {
          const response = await getMsgList()
          if (response.state && response.value) {
            this.newsList = response.value || []
          }
        } catch (error) {
          console.error('加载最新消息失败:', error)
        }
      },
      // 待办事项搜索
      handleTodoSearch() {
        this.currentPage = 1
        if (this.curOrg === '企业单位') {
          this.getEnterpriseTodoList()
        } else {
          this.loadAuditProjectList()
        }
      },
      // 获取企业待办列表
      async getEnterpriseTodoList() {
        try {
          this.loading = true
          const params = {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            projectName: this.todoSearchQuery,
          }
          const response = await getEnterpriseList(params)

          if (response.state && response.value) {
            const records = response.value.records || []
            this.todoList = records
          }
        } catch (error) {
          console.error('获取企业待办列表失败:', error)
        } finally {
          this.loading = false
        }
      },
      // 填报任务
      handleEdit(row) {
        console.log('填报任务', row)
        this.currentTaskInfo = row || {}
        this.taskViewMode = false
        // 使用ref调用组件的open方法
        this.$nextTick(() => {
          if (this.$refs.taskFillIn) {
            this.$refs.taskFillIn.open(row, false)
          }
        })
      },
      // 填报任务提交成功后刷新列表
      handleTaskFillInRefresh() {
        // 刷新列表数据
        this.getEnterpriseTodoList()
      },
      // 填报任务弹窗关闭
      handleTaskFillInClose() {
        this.taskFillInVisible = false
        this.currentTaskInfo = {}
      },
      // 加载审核项目列表
      async loadAuditProjectList() {
        try {
          this.loading = true
          const params = {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            projectName: this.todoSearchQuery,
          }
          const response = await getReviewTaskList(params)

          if (response.state && response.value) {
            const records = response.value.records || []
            // 转换数据格式，将childTasks转换为children以适应表格组件
            this.todoList = records.map((record) => {
              return {
                id: record.id,
                projectName: record.projectName,
                auditObject: record.auditedUnitName,
                auditPeriod: record.auditPeriod,
                source: this.getSourceTypeText(record.sourceType),
                form: this.getAuditTypeText(record.auditType),
                status: this.getStatusText(record.status),
                statusName: record.statusName,
                isSubTask: record.pid !== '0',
                currentNodeName: record.currentNodeName,
                currentNode: record.currentNode,
                projectId: record.projectId,
                auditedUnitId: record.auditedUnitId,
                children: record.childTasks
                  ? record.childTasks.map((child) => ({
                      id: child.id,
                      projectName: child.projectName,
                      auditObject: child.auditedUnitName,
                      auditPeriod: record.auditPeriod,
                      source: '',
                      form: '',
                      currentNode: child.currentNode,
                      status: child.status,
                      statusName: child.statusName,
                      isSubTask: true,
                      projectId: child.projectId,
                      auditedUnitId: child.auditedUnitId,
                      taskId: child.id,
                      catalogId: child.catalogId,
                    }))
                  : [],
              }
            })
            this.total = response.value.total || 0
          } else {
            this.todoList = []
            this.total = 0
          }
        } catch (error) {
          console.error('加载审核项目列表失败:', error)
        } finally {
          this.loading = false
        }
      },
      // 获取父节点的连续序号
      getParentNodeIndex(row) {
        // 过滤出所有父节点
        const parentNodes = this.todoList.filter(
          (item) => item.children && item.children.length > 0
        )
        // 找到当前行在父节点数组中的索引
        const index = parentNodes.findIndex((item) => item.id === row.id)
        // 返回序号（索引+1）
        return index + 1
      },
      // 获取来源类型文本
      getSourceTypeText(type) {
        const typeMap = {
          1: '年度计划内',
          2: '年度计划外',
        }
        return typeMap[type] || type
      },
      // 获取审核类型文本
      getAuditTypeText(type) {
        const typeMap = {
          1: '定期监审',
          2: '定调价监审',
        }
        return typeMap[type] || type
      },
      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          ccls: '资料初审',
          200: '审核通过',
          clcs: '审核中',
        }
        return statusMap[status] || status
      },
      // 查记录
      handleCheckRecord(project) {
        this.$router.push({
          name: 'memoManage',
        })
      },
      // 判断是否为周末
      isWeekend(date) {
        const day = date.getDay() // 0-6，0表示周日，6表示周六
        return day === 0 || day === 6 // 周日或周六为周末
      },
      initChart() {
        // 保存图表实例到组件实例中
        this.chart = echarts.init(this.$refs.chartRef)

        // 加载图表数据
        this.loadChartData()

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
          this.chart.resize()
        })

        // 组件销毁时清除定时器
        this.$once('hook:beforeDestroy', () => {
          if (this.chartTimer) {
            clearInterval(this.chartTimer)
          }
        })
      },
      // 加载图表数据
      async loadChartData() {
        try {
          const params = {
            year: this.year,
            region: this.areaCode[this.areaCode.length - 1],
          }
          const response = await getChartList(params)

          if (response.state && response.value) {
            const data = response.value || []
            // 解析接口返回的数据
            this.allCategories = data.map((item) => ({ name: item.name }))
            this.allCompletedData = data.map((item) => item.finish)
            this.allInProgressData = data.map((item) => item.nFinish)

            // 每页显示9个数据
            this.chartPageSize = 9
            this.chartCurrentPage = 0
            this.totalPages = Math.ceil(
              this.allCategories.length / this.chartPageSize
            )

            // 初始加载第一页数据
            this.updateChartData()

            // 设置定时器，每5秒切换一页数据
            if (this.chartTimer) {
              clearInterval(this.chartTimer)
            }
            this.chartTimer = setInterval(() => {
              this.chartCurrentPage =
                this.totalPages > 1
                  ? (this.chartCurrentPage + 1) % this.totalPages
                  : 0
              this.updateChartData()
            }, 5000)
          } else {
            // 如果接口没有数据，使用初始化默认数据
            this.initChartData()
            this.updateChartData()
          }
        } catch (error) {
          console.error('加载图表数据失败:', error)
          // 出错时使用默认数据
          this.initChartData()
          this.updateChartData()
        }
      },

      // 初始化图表数据
      initChartData() {
        // 扩展数据，确保有足够的数据用于轮播
        this.allCategories = []
        // 每页显示9个数据
        this.chartPageSize = 9
        this.chartCurrentPage = 0
        this.totalPages = Math.ceil(
          this.allCategories.length / this.chartPageSize
        )
      },

      // 跳转到指定页面
      goToPage(index) {
        if (index >= 0 && index < this.totalPages) {
          // 清除现有定时器
          if (this.chartTimer) {
            clearInterval(this.chartTimer)
          }
          // 更新当前页
          this.chartCurrentPage = index
          this.updateChartData()
          // 重新设置定时器
          this.resumeCarousel()
        }
      },

      // 暂停轮播
      pauseCarousel() {
        if (this.chartTimer) {
          clearInterval(this.chartTimer)
          this.chartTimer = null
        }
      },

      // 恢复轮播
      resumeCarousel() {
        if (!this.chartTimer && this.totalPages > 1) {
          this.chartTimer = setInterval(() => {
            this.chartCurrentPage =
              (this.chartCurrentPage + 1) % this.totalPages
            this.updateChartData()
          }, 5000)
        }
      },

      // 更新图表数据的方法
      updateChartData(
        categories = null,
        completedData = null,
        inProgressData = null
      ) {
        if (!this.chart) {
          return
        }

        let currentCategories, currentCompletedData, currentInProgressData

        // 如果提供了新数据，则使用新数据
        if (categories && completedData && inProgressData) {
          currentCategories = categories
          currentCompletedData = completedData
          currentInProgressData = inProgressData
        } else {
          // 否则使用当前页的数据
          const startIndex = this.chartCurrentPage * this.chartPageSize
          const endIndex = Math.min(
            startIndex + this.chartPageSize,
            this.allCategories.length
          )

          currentCategories = this.allCategories.slice(startIndex, endIndex)
          currentCompletedData = this.allCompletedData.slice(
            startIndex,
            endIndex
          )
          currentInProgressData = this.allInProgressData.slice(
            startIndex,
            endIndex
          )
        }

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            show: true,
            itemWidth: 20,
            itemHeight: 8,
            itemGap: 10,
            data: ['已办', '在办'],
          },
          grid: {
            top: '20%',
            left: '3%',
            right: '4%',
            bottom: '2%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: currentCategories.map((item) => item.name),
            axisLabel: {
              interval: 0,
              rotate: 0,
            },
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: true,
            scrollBar: {
              show: true,
              height: 10,
            },
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '已办',
              type: 'bar',
              barWidth: '10%',
              data: currentCompletedData,
              itemStyle: {
                color: '#1890ff',
              },
            },
            {
              name: '在办',
              type: 'bar',
              barWidth: '10%',
              data: currentInProgressData,
              itemStyle: {
                color: '#ff9c6e',
              },
            },
          ],
        }

        this.chart.setOption(option, true)
      },
      loadMoreNews() {
        //  跳转通知公告页面
        this.$router.push('/personal/notice')
      },
      handleOp(type, row) {
        if (type === '详情') {
          this.$refs.taskDetail.open(row, 'chengben')
        } else if (type === '办理') {
          this.selectedProject = row
          this.mainDetailsVisible = true
        } else if (type === '查看') {
          this.cbjsInfoData = row
          this.cbjsInfoVisible = true
        } else if (type === '审核') {
          this.selectedProject = row
          this.detailsVisible = true
        }
      },
      // 打开详情弹窗
      handleOpenDetails(project) {
        this.selectedProject = project
        this.detailsVisible = true
      },
      handleOpenMainDetails(project) {
        this.selectedProject = project
        this.mainDetailsVisible = true
      },
      // 详情弹窗关闭处理
      handleDetailsClose() {
        this.selectedProject = null
        this.detailsVisible = false
      },
      // 主详情弹窗关闭处理
      handleMainDetailsClose() {
        this.selectedProject = null
        this.mainDetailsVisible = false
      },
      // 刷新表格数据
      handleRefresh() {
        this.loadAuditProjectList()
      },
      // 主详情刷新处理
      handleMainRefresh() {
        this.loadAuditProjectList()
      },
      // 恢复任务
      async handleHf(row) {
        if (!row || !row.id) {
          this.$message.error('缺少任务ID')
          return
        }

        this.$confirm('确定要恢复此任务吗？', '恢复任务', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            try {
              const params = {
                taskId: row.id,
                key: 2,
                status: 200,
                processNodeKey: row.currentNode,
              }

              const response = await doProcessBtn(params)

              if (response && response.code === 200) {
                this.$message.success('恢复任务成功')
                this.loadAuditProjectList()
              } else {
                this.$message.error(response?.message || '恢复任务失败')
              }
            } catch (error) {
              console.error('恢复任务失败:', error)
            }
          })
          .catch(() => {
            this.$message.info('已取消恢复任务')
          })
      },
      // 查看
      handleMessage(row, type) {
        if (type === 'chengben') {
          this.cbjsInfoData = row
          this.cbjsInfoVisible = true
        } else {
          this.$refs.taskInfo.open(row, type)
        }
      },
      // 查看任务详情
      handleViewTaskDetail(row) {
        this.$refs.taskDetail.open(row, 'chengben')
      },
      searchMemo() {
        this.$message.info(`搜索备忘录，关键词：${this.searchKeyword}`)
      },
      hasEventOnDate(date) {
        // 检查指定日期是否有备忘录事件
        return this.memoList.some((item) => item.time === date.substring(5))
      },
      addMemo() {
        this.$message.info('添加新备忘录')
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/views/costAudit/projectInfo/auditProjectManage/memoManage/memoManage.scss';
  .mb-20 {
    /* border: 1px solid red; */
    margin-bottom: 20px;
  }
  .icon-dot {
    width: 8px;
    height: 8px;
    background-color: #999999;
    border-radius: 50%;
    display: inline-block;
  }
  /* 确保同一行的卡片高度一致 */
  .card-row {
    display: flex;
    flex-wrap: wrap;
  }
  .card-row .el-card {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  ::v-deep .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
  }
  .card-header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(0deg, #e8edfc, #ffffff);
    padding: 10px 20px;
    box-sizing: border-box;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }
  .calendar-actions {
    display: flex;
    align-items: center;
  }
  .search-actions {
    display: flex;
    align-items: center;
  }
  .news-list {
    width: 100%;
  }
  .card-content {
    width: 90%;
    padding: 20px;
  }
  .news-item {
    width: 100%;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: flex-start;
  }
  .news-item:last-child {
    border-bottom: none;
  }
  /* 新的消息列表样式 */
  .news-item-new {
    width: 100%;
    padding: 10px 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    font-size: 14px;
    line-height: 1.5;
  }
  .news-item-new:last-child {
    border-bottom: none;
  }
  .news-dot {
    width: 6px;
    height: 6px;
    background-color: #409eff;
    border-radius: 50%;
    margin-right: 12px;
    flex-shrink: 0;
  }
  .news-title-text {
    flex: 1;
    color: #333333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 20px;
  }
  .news-author {
    color: #999999;
    margin-right: 20px;
    flex-shrink: 0;
    min-width: 60px;
  }
  .news-time {
    color: #cccccc;
    flex-shrink: 0;
    min-width: 140px;
    text-align: right;
  }
  .news-content {
    width: 100%;
    line-height: 1.6;
    font-size: 14px;
    flex: 1;
  }
  .news-title {
    display: flex;
    align-items: flex-center;
    margin-bottom: 8px;
    width: 95%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .news-title i {
    color: #f56c6c;
    margin-right: 8px;
    font-size: 14px;
    margin-top: 2px;
    flex-shrink: 0;
  }
  .news-meta {
    width: 100%;
    display: flex;
    align-items: center;
    margin-left: 22px;
  }
  .news-meta .left-icon {
    margin-right: 15px;
  }
  .news-meta .left-icon span {
    margin-left: 4px;
    color: #61657e;
    font-size: 14px;
  }
  .calendar-day {
    position: relative;
    text-align: center;
    padding: 10px 0;
    cursor: pointer;
  }
  .has-event {
    background-color: #f0f9eb;
  }
  .event-dot {
    position: absolute;
    bottom: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 6px;
    height: 6px;
    background-color: #67c23a;
    border-radius: 50%;
  }
  .left-icon {
    display: flex;
    align-items: center;
    img {
      width: 20px;
    }
  }
  .title {
    font-size: 18px;
  }
  /* 彻底移除表格斑马纹效果 */
  .no-zebra ::v-deep .el-table__row:nth-child(even) {
    background-color: transparent;
  }
  .no-zebra ::v-deep .el-table__body tr:hover > td {
    background-color: #f5f7fa !important;
  }
  .w40 {
    width: 40%;
  }
  .content-text {
    display: flex;
    align-items: center;
    width: 95%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #61657e;
    font-size: 14px;
  }
  h3 {
    margin: 0;
    // font-size: 16px;
    font-weight: bolder;
    color: #333333;
    margin-left: 10px;
  }

  .event-dot {
    position: absolute;
    bottom: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 6px;
    height: 6px;
    background-color: #67c23a;
    border-radius: 50%;
  }

  .tooltip {
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    background-color: #333;
    color: white;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 1000;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .tooltip.show {
    opacity: 1;
  }

  .tooltip-content {
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .calendar-header {
    width: 95%;
    margin: 15px auto 0;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    background: #f0f4fd;
    padding: 5px 0;
  }
  .calendar-btn {
    margin: 0 20px;
    cursor: pointer;
    font-size: 20px;
    color: #606266;
    transition: color 0.3s ease;
    &:hover {
      color: #409eff;
    }
  }
  /* 使星期几头部居中显示 */
  ::v-deep .el-calendar-table thead th {
    text-align: center !important;
    font-weight: 500;
    color: #606266;
  }
  .carousel {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    li {
      list-style: none;
      margin: 0 8px;
      cursor: pointer;
      transition: transform 0.2s ease;
      &:hover {
        transform: scale(1.1);
      }
    }
    i {
      display: inline-block;
      width: 12px;
      height: 8px;
      background-color: #e0e0e0;
      border-radius: 50%;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    i.active {
      background-color: #409eff;
      width: 24px;
      border-radius: 6px;
    }
  }
</style>
