<template>
  <div >
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :span="6">
        <el-card shadow="hover" class="panel-item">
          <div class="card-panel">
            <div class="card-panel-icon">
              <i class="el-icon-warning-outline" style="color: #409EFF"></i>
            </div>
            <div class="card-panel-description">
              <div class="card-panel-text">流转中</div>
              <count-to
                class="card-panel-num"
                :start-val="0"
                :end-val="pendingCount"
                :duration="2600"
              ></count-to>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="panel-item">
          <div class="card-panel">
            <div class="card-panel-icon">
              <i class="el-icon-check" style="color: #67C23A"></i>
            </div>
            <div class="card-panel-description">
              <div class="card-panel-text">已完成工单</div>
              <count-to
                class="card-panel-num"
                :start-val="0"
                :end-val="completedCount"
                :duration="2600"
              ></count-to>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="panel-item">
          <div class="card-panel">
            <div class="card-panel-icon">
              <i class="el-icon-date" style="color: #E6A23C"></i>
            </div>
            <div class="card-panel-description">
              <div class="card-panel-text">年度工单量</div>
              <count-to
                class="card-panel-num"
                :start-val="0"
                :end-val="yearlyCount"
                :duration="2600"
              ></count-to>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="panel-item">
          <div class="card-panel">
            <div class="card-panel-icon">
              <i class="el-icon-s-data" style="color: #F56C6C"></i>
            </div>
            <div class="card-panel-description">
              <div class="card-panel-text">历史工单总量</div>
              <count-to
                class="card-panel-num"
                :start-val="0"
                :end-val="totalCount"
                :duration="2600"
              ></count-to>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 下方图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8" class="chart-col">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="clearfix card-header">
            <span class="card-title">{{ queryParams.type === 'user' ? '工单类型统计' : '部门工单统计' }}</span>
          </div>
          <div ref="departmentChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16" class="chart-col">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="clearfix card-header">
            <span class="card-title">流转中</span>
            <span class="total-count">(共 {{ total }} 条)</span>
            <div class="header-buttons">
              <el-button
                v-if="listUserRoles.includes(162) || listUserRoles.includes(1)"
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="handleCreateWorkorder"
              >
                新建工单
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleViewMore"
              >
                查看更多
              </el-button>
            </div>
          </div>
          <div class="table-container">
            <el-table :data="pendingList" style="width: 100%;" v-loading="loading" height="465">
              <el-table-column prop="category" label="工单分类" ></el-table-column>
              <el-table-column prop="user" label="部门用户"></el-table-column>
              <el-table-column prop="techOperator" label="技术运维商" ></el-table-column>
              <el-table-column prop="status" label="状态" >
                <template v-slot="scope">
                  <dict-tag type="trs_workorder_status" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column prop="orderTime" label="下单时间">
                <template v-slot="scope">
                  <span>{{ parseTime(scope.row.orderTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button v-if="(scope.row.status === '21' && queryParams.type === 'user') || (scope.row.status === '31' && queryParams.type === 'dsjzx') || (scope.row.status === '41' && queryParams.type === 'zwgk') || ((scope.row.status === '51' || scope.row.status === '60') && scope.row.techOperatorId === deptId && scope.row.rejectReason ==='' && queryParams.type === 'yws')"
                    size="mini"
                    type="text"
                    icon="el-icon-document" @click="handleViewWorkorder(scope.row,'check')">去处理</el-button>
                    <el-button v-else-if="scope.row.status === '10' || (scope.row.rejectReason !== null && scope.row.rejectReason !== '' && String(scope.row.creator) === String($store.getters.userId) && scope.row.status !== '0')" size="mini" type="text" icon="el-icon-edit" @click="handleViewWorkorder(scope.row,'edit')"
                    v-hasPermi="['server:workorder-infos:update']">修改</el-button>
                   <el-button v-else
                      size="mini"
                      type="text"
                      icon="el-icon-view" @click="handleViewWorkorder(scope.row,'inspect')">查看</el-button>
                      <el-button v-if="scope.row.status === '10' || (scope.row.rejectReason !== null && scope.row.rejectReason !== '' && String(scope.row.creator) === String($store.getters.userId) && scope.row.status !== '0')" size="mini" type="text" icon="el-icon-delete" @click="closeWorkorder(scope.row.id)"
                      v-hasPermi="['server:workorder-infos:update']">关闭</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-if="total > pageSize"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                layout="prev, pager, next"
              >
              </el-pagination>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="24" style="background-color: #fff; margin-top: 20px;">
        <WorkorderInfosUser/>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import * as WorkorderInfosApi from '@/api/server/WorkorderInfos'
import CountTo from 'vue-count-to'
import { Loading } from 'element-ui'
import WorkorderInfosUser from '../server/WorkorderInfosUser';
import * as PermissionApi from "@/api/system/permission";
import * as UserApi from "@/api/system/user";
export default {
  name: "WorkorderHomePage",
  components: {
    CountTo,
    WorkorderInfosUser
  },
  data() {
    return {
      pendingCount: 0,
      completedCount: 0,
      yearlyCount: 0,
      totalCount: 0,
      pendingList: [],
      departmentChart: null,
      departmentChartData: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      loading: false,
      listUserRoles: [],
      queryParams: {
        type: "",
      },
      deptId: "",
    }
  },
  mounted() {
    this.initData()
    this.initDepartmentChart()
  },
  methods: {
    async initData() {
      this.loading = true
      const res = await WorkorderInfosApi.getHomeCardData()
      this.pendingCount = res.data.pendingCount
      this.completedCount = res.data.finidshCount
      this.yearlyCount = res.data.yearCount
      this.totalCount = res.data.allCount

      await this.getWorkorderList()
    },
    async getWorkorderList() {
              //获取当前用户部门
              const userInfo = await UserApi.getUser(this.$store.getters.userId);
        this.deptId = userInfo.data.deptId;
              //获取当前用户角色
              const listUserRoles = await PermissionApi.listUserRoles(
          this.$store.getters.userId
        );
        this.listUserRoles = listUserRoles.data;
        listUserRoles.data.forEach((item) => {
          if (item === 161) {
            this.queryParams.type = "user";
          } else if (item === 162) {
            this.queryParams.type = "yws";
          } else if (item === 163) {
            this.queryParams.type = "dsjzx";
          } else if (item === 164) {
            this.queryParams.type = "zwgk";
          }
        });
      const res = await WorkorderInfosApi.getHomePendingWorkorder({
        pageNo: this.currentPage,
        pageSize: this.pageSize
      })
      this.pendingList = res.data.list
      this.total = res.data.total
      this.loading = false
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getWorkorderList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getWorkorderList()
    },
    handleViewWorkorder(row,type) {
      if (type === "inspect") {
        this.$router.push({
          path: "/server/workorder-infos-view-workorder",
          query: {
            id: row.id,
          },
        });
      } else if (type === "check") {
        this.$router.push({
          path: "/server/workorder-infos-check",
          query: {
            id: row.id,
          },
        });
      }else if (type === "edit") {
        this.$router.push({
        path: '/server/workorder-infos-add-workorder',
        query: {
          type: row.id ? 'edit' : 'add',
          id: row.id
        }
      });
      }
    },
    async initDepartmentChart() {
      const res = await WorkorderInfosApi.getHomeDepartmentStats()
      this.departmentChartData = res.data
      this.departmentChart = echarts.init(this.$refs.departmentChart)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          position: 'top'
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          height: '200',
          bottom: '0',
          left: 'center',
          itemWidth: 12,
          itemHeight: 12,
          textStyle: {
            fontSize: 12,
            color: '#666'
          },
          itemGap: 20
        },
        series: [
          {
            name: '部门工单量',
            type: 'pie',
            radius: ['45%', '70%'],
            center: ['50%', '40%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: false,//改
                fontSize: '12',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.departmentChartData
          }
        ]
      }
      this.departmentChart.setOption(option)
    },
    handleViewMore() {
      this.$router.push('/server/workorder-infos-user')
    },
    handleViewDepartmentStats() {
      this.$router.push('/workorder/department-stats')
    },
    handleCreateWorkorder() {
      this.$router.push('/server/workorder-infos-add-workorder')
    },
        //关闭工单
        async closeWorkorder(id) {
      this.$modal.confirm('是否确认关闭该工单?').then(async () => {
      try {
        await WorkorderInfosApi.closeWorkorderInfos(id);
          await this.getWorkorderList();
          this.$modal.msgSuccess("关闭成功");
        } catch {
          console.log('关闭失败');
        }
      });
    },
  },
  beforeDestroy() {
    if (this.departmentChart) {
      this.departmentChart.dispose()
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.panel-group {
  margin-top: 18px;
}

.card-panel {
  display: flex;
  align-items: center;
}

.card-panel-icon {
  font-size: 30px;
  padding: 10px;
  margin-right: 15px;
}

.card-panel-description {
  flex: 1;
}

.card-panel-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-panel-num {
  font-size: 24px;
  font-weight: bold;
}

.chart-row {
  margin: 20px -10px 0;
}

.chart-col {
  padding: 0 10px;
  margin-bottom: 0;
}

.chart-card {
  height: 600px;
  display: flex;
  flex-direction: column;
  margin: 0;
  border-radius: 4px;
}

.chart-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.card-header {
  position: relative;
  height: 32px;
  line-height: 32px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2f3d;
}

.total-count {
  font-size: 14px;
  color: #909399;
  margin-left: 8px;

}

.header-button {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 6px 16px;
}

.chart-container {
  flex: 1;
  min-height: 0;
  padding: 20px;
}

.table-container {
  padding: 0 20px;
}

.table-container :deep(.el-table) {
  width: 100%;
  border-top: none;
}

.table-container :deep(.el-table::before) {
  height: 0;
}

.table-container :deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}

.table-container :deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.header-buttons {
  float: right;
}

.header-buttons .el-button {
  margin-left: 8px;
}

.header-buttons .el-button:first-child {
  margin-left: 0;
}

.chart-card :deep(.pagination-container) {
  padding: 8px 0;
  text-align: center;
  margin-top: 0px;
}
</style>

