<template>
  <div class="app-container repair-stat-page">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <!-- 按月查看分类 -->
      <el-tab-pane label="按月查看" name="monthView">
        <el-form :inline="true" size="small" class="filter-form">
          <el-form-item label="选择月份">
            <el-date-picker v-model="monthViewMonth" type="month" value-format="yyyy-MM" placeholder="选择月份"
              @change="loadMonthView" />
          </el-form-item>
          <el-form-item label="维修类型">
            <el-select v-model="monthViewType" clearable placeholder="全部类型" @change="loadMonthView">
              <el-option v-for="item in repairTypeOptions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="loadMonthView">查询</el-button>
            <el-button icon="el-icon-download" @click="handleExportMonth">导出</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="16" class="summary-cards">
          <el-col :span="4" v-for="item in monthCategorySummary" :key="item.type">
            <el-card shadow="hover" class="summary-card">
              <div class="card-label">{{ item.label }}</div>
              <div class="card-value">{{ item.count }} 笔</div>
              <div class="card-money">¥ {{ formatMoney(item.amount) }}</div>
            </el-card>
          </el-col>
          <el-col :span="4">
            <el-card shadow="hover" class="summary-card total-card">
              <div class="card-label">当月合计</div>
              <div class="card-value">{{ monthViewList.length }} 笔</div>
              <div class="card-money">¥ {{ formatMoney(monthViewTotalAmount) }}</div>
            </el-card>
          </el-col>
        </el-row>

        <el-table v-loading="monthViewLoading" :data="monthViewList" border stripe>
          <el-table-column label="申请日期" align="center" prop="applyDate" width="110">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="维修类型" align="center" width="100">
            <template slot-scope="scope">
              <el-tag size="small" :type="repairTypeTag(scope.row.repairUsage)">
                {{ repairTypeLabel(scope.row.repairUsage) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="申请人" align="center" width="100">
            <template slot-scope="scope">
              <span>{{ getUserName(scope.row.applier) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="申请部门" align="center" width="120">
            <template slot-scope="scope">
              <span>{{ getDeptName(scope.row.applyDept) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="情况说明" align="center" prop="applyReason" min-width="160" show-overflow-tooltip />
          <el-table-column label="关联项目" align="center" prop="_projectName" min-width="140" show-overflow-tooltip />
          <el-table-column label="关联设备" align="center" prop="_deviceName" min-width="140" show-overflow-tooltip />
          <el-table-column label="维修费用" align="center" width="110">
            <template slot-scope="scope">
              <span class="money-text">{{ formatMoney(scope.row.repairMoney) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="处理情况" align="center" prop="handlerComment" min-width="140" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 按月费用汇总 -->
      <el-tab-pane label="按月费用汇总" name="monthAmount">
        <el-form :inline="true" size="small" class="filter-form">
          <el-form-item label="选择年份">
            <el-date-picker v-model="monthAmountYear" type="year" value-format="yyyy" placeholder="选择年份"
              @change="loadMonthAmount" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-refresh" @click="loadMonthAmount">刷新</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="14">
            <el-table :data="monthAmountTable" border stripe show-summary :summary-method="monthAmountSummary">
              <el-table-column label="月份" align="center" prop="month" width="100" />
              <el-table-column label="维修笔数" align="center" prop="count" width="100" />
              <el-table-column label="维修费用(元)" align="center" prop="amount">
                <template slot-scope="scope">
                  <span class="money-text">{{ formatMoney(scope.row.amount) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="10">
            <div id="monthAmountChart" class="chart-box"></div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 按年费用汇总 -->
      <el-tab-pane label="按年费用汇总" name="yearAmount">
        <el-form :inline="true" size="small" class="filter-form">
          <el-form-item>
            <el-button type="primary" icon="el-icon-refresh" @click="loadYearAmount">刷新</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="14">
            <el-table v-loading="yearAmountLoading" :data="yearAmountTable" border stripe show-summary
              :summary-method="yearAmountSummary">
              <el-table-column label="年份" align="center" prop="year" width="120" />
              <el-table-column label="维修笔数" align="center" prop="count" width="120" />
              <el-table-column label="维修费用(元)" align="center" prop="amount">
                <template slot-scope="scope">
                  <span class="money-text">{{ formatMoney(scope.row.amount) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="10">
            <div id="yearAmountChart" class="chart-box"></div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 按年查看分类 -->
      <el-tab-pane label="按年查看分类" name="yearCategory">
        <el-form :inline="true" size="small" class="filter-form">
          <el-form-item label="选择年份">
            <el-date-picker v-model="yearCategoryYear" type="year" value-format="yyyy" placeholder="选择年份"
              @change="loadYearCategory" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="loadYearCategory">查询</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-table v-loading="yearCategoryLoading" :data="yearCategoryTable" border stripe show-summary
              :summary-method="yearCategorySummary">
              <el-table-column label="维修类型" align="center" prop="label" width="120" />
              <el-table-column label="维修笔数" align="center" prop="count" width="120" />
              <el-table-column label="维修费用(元)" align="center" prop="amount">
                <template slot-scope="scope">
                  <span class="money-text">{{ formatMoney(scope.row.amount) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="占比" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.ratio }}%</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <div id="yearCategoryChart" class="chart-box"></div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 按类别汇总 -->
      <el-tab-pane label="按类别汇总" name="categoryTotal">
        <el-form :inline="true" size="small" class="filter-form">
          <el-form-item label="统计范围">
            <el-radio-group v-model="categoryScope" @change="loadCategoryTotal">
              <el-radio label="all">全部</el-radio>
              <el-radio label="year">按年</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择年份" v-if="categoryScope === 'year'">
            <el-date-picker v-model="categoryYear" type="year" value-format="yyyy" placeholder="选择年份"
              @change="loadCategoryTotal" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-refresh" @click="loadCategoryTotal">刷新</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-table v-loading="categoryLoading" :data="categoryTable" border stripe show-summary
              :summary-method="categorySummary">
              <el-table-column label="维修类型" align="center" prop="label" width="120" />
              <el-table-column label="维修笔数" align="center" prop="count" width="120" />
              <el-table-column label="维修费用(元)" align="center" prop="amount">
                <template slot-scope="scope">
                  <span class="money-text">{{ formatMoney(scope.row.amount) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="占比" align="center" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.ratio }}%</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <div id="categoryChart" class="chart-box"></div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="维修审批详情" :visible.sync="detailOpen" width="75%" append-to-body>
      <repair-form v-if="detailOpen" :key="detailTaskForm.formId" :taskForm="detailTaskForm" :taskName="''"
        :isFlow="false" />
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listRepair, getRepairStatistic } from "@/api/oa/repair/repair";
import { getProject } from "@/api/oa/project/project";
import { getDevice } from "@/api/oa/device/device";
import repairForm from '@/views/flowable/form/oa/repairForm.vue';

const REPAIR_TYPES = [
  { value: '0', label: '电脑' },
  { value: '1', label: '打印机' },
  { value: '2', label: '其他' },
  { value: '3', label: '仪器设备' }
];

export default {
  name: "Repair",
  components: { repairForm },
  data() {
    const now = new Date();
    const year = String(now.getFullYear());
    const month = `${year}-${String(now.getMonth() + 1).padStart(2, '0')}`;
    return {
      activeTab: 'monthView',
      repairTypeOptions: REPAIR_TYPES,
      // 按月查看
      monthViewMonth: month,
      monthViewType: null,
      monthViewLoading: false,
      monthViewList: [],
      detailOpen: false,
      detailTaskForm: {
        formId: ''
      },
      // 按月费用
      monthAmountYear: year,
      monthAmountTable: [],
      monthAmountChart: null,
      // 按年费用
      yearAmountLoading: false,
      yearAmountTable: [],
      yearAmountChart: null,
      // 按年分类
      yearCategoryYear: year,
      yearCategoryLoading: false,
      yearCategoryTable: [],
      yearCategoryChart: null,
      // 按类别汇总
      categoryScope: 'all',
      categoryYear: year,
      categoryLoading: false,
      categoryTable: [],
      categoryChart: null
    };
  },
  computed: {
    monthCategorySummary() {
      return REPAIR_TYPES.map(type => {
        const rows = this.monthViewList.filter(item => item.repairUsage === type.value);
        return {
          type: type.value,
          label: type.label,
          count: rows.length,
          amount: rows.reduce((sum, row) => sum + Number(row.repairMoney || 0), 0)
        };
      });
    },
    monthViewTotalAmount() {
      return this.monthViewList.reduce((sum, row) => sum + Number(row.repairMoney || 0), 0);
    }
  },
  mounted() {
    this.loadMonthView();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    handleViewDetail(row) {
      this.detailTaskForm = { formId: row.repairId };
      this.detailOpen = true;
    },
    repairTypeLabel(val) {
      const item = REPAIR_TYPES.find(t => t.value === val);
      return item ? item.label : val || '-';
    },
    repairTypeTag(val) {
      const map = { '0': 'primary', '1': 'success', '2': 'info', '3': 'warning' };
      return map[val] || 'info';
    },
    formatMoney(val) {
      const num = Number(val || 0);
      return num.toFixed(2);
    },
    handleTabChange() {
      this.$nextTick(() => {
        if (this.activeTab === 'monthView') {
          this.loadMonthView();
        } else if (this.activeTab === 'monthAmount') {
          this.loadMonthAmount();
        } else if (this.activeTab === 'yearAmount') {
          this.loadYearAmount();
        } else if (this.activeTab === 'yearCategory') {
          this.loadYearCategory();
        } else if (this.activeTab === 'categoryTotal') {
          this.loadCategoryTotal();
        }
      });
    },
    async loadMonthView() {
      if (!this.monthViewMonth) return;
      this.monthViewLoading = true;
      try {
        const params = {
          pageNum: 1,
          pageSize: 9999,
          repairUsage: this.monthViewType,
          params: { statMonth: this.monthViewMonth }
        };
        const res = await listRepair(params);
        const list = res.rows || [];
        await this.enrichProjectDeviceNames(list);
        this.monthViewList = list;
      } finally {
        this.monthViewLoading = false;
      }
    },
    async enrichProjectDeviceNames(list) {
      const projectIds = [...new Set(list.map(row => row.projectId).filter(Boolean))];
      const deviceIds = [...new Set(list.map(row => row.deviceId).filter(Boolean))];
      const projectMap = {};
      const deviceMap = {};
      await Promise.all(projectIds.map(async id => {
        const res = await getProject(id);
        if (res.data) projectMap[id] = res.data;
      }));
      await Promise.all(deviceIds.map(async id => {
        const res = await getDevice(id);
        if (res.data) deviceMap[id] = res.data;
      }));
      list.forEach(row => {
        row._projectName = row.projectId && projectMap[row.projectId]
          ? projectMap[row.projectId].projectName : '';
        row._deviceName = row.deviceId && deviceMap[row.deviceId]
          ? `${deviceMap[row.deviceId].name || ''}${deviceMap[row.deviceId].code ? '（' + deviceMap[row.deviceId].code + '）' : ''}` : '';
      });
    },
    async loadMonthAmount() {
      if (!this.monthAmountYear) return;
      const res = await getRepairStatistic({ applyDate: `${this.monthAmountYear}-01-01` });
      const monthCount = res.data.monthCount ? res.data.monthCount[0] : {};
      const monthAmount = res.data.monthAmount ? res.data.monthAmount[0] : {};
      this.monthAmountTable = [];
      for (let i = 1; i <= 12; i++) {
        const key = `${this.monthAmountYear}-${String(i).padStart(2, '0')}`;
        this.monthAmountTable.push({
          month: `${i}月`,
          monthKey: key,
          count: monthCount[key] || 0,
          amount: Number(monthAmount[key] || 0)
        });
      }
      this.$nextTick(() => this.renderMonthAmountChart());
    },
    async loadYearAmount() {
      this.yearAmountLoading = true;
      try {
        const res = await getRepairStatistic({});
        const yearCount = res.data.yearCount ? res.data.yearCount[0] : {};
        const yearAmount = res.data.yearAmount ? res.data.yearAmount[0] : {};
        this.yearAmountTable = Object.keys(yearCount).sort().map(year => ({
          year,
          count: yearCount[year] || 0,
          amount: Number(yearAmount[year] || 0)
        }));
        this.$nextTick(() => this.renderYearAmountChart());
      } finally {
        this.yearAmountLoading = false;
      }
    },
    async loadYearCategory() {
      if (!this.yearCategoryYear) return;
      this.yearCategoryLoading = true;
      try {
        const res = await getRepairStatistic({ applyDate: `${this.yearCategoryYear}-01-01` });
        this.yearCategoryTable = this.buildCategoryTable(
          res.data.usageCount ? res.data.usageCount[0] : {},
          res.data.usageAmount ? res.data.usageAmount[0] : {}
        );
        this.$nextTick(() => this.renderYearCategoryChart());
      } finally {
        this.yearCategoryLoading = false;
      }
    },
    async loadCategoryTotal() {
      this.categoryLoading = true;
      try {
        let res;
        if (this.categoryScope === 'year' && this.categoryYear) {
          res = await getRepairStatistic({ applyDate: `${this.categoryYear}-01-01` });
        } else {
          res = await getRepairStatistic({});
        }
        this.categoryTable = this.buildCategoryTable(
          res.data.usageCount ? res.data.usageCount[0] : {},
          res.data.usageAmount ? res.data.usageAmount[0] : {}
        );
        this.$nextTick(() => this.renderCategoryChart());
      } finally {
        this.categoryLoading = false;
      }
    },
    buildCategoryTable(countObj, amountObj) {
      const rows = REPAIR_TYPES.map(type => ({
        label: type.label,
        count: countObj[type.label] || 0,
        amount: Number(amountObj[type.label] || 0)
      }));
      const totalAmount = rows.reduce((sum, row) => sum + row.amount, 0);
      return rows.map(row => ({
        ...row,
        ratio: totalAmount > 0 ? ((row.amount / totalAmount) * 100).toFixed(1) : '0.0'
      }));
    },
    monthAmountSummary({ columns, data }) {
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (column.property === 'count') {
          sums[index] = data.reduce((sum, row) => sum + row.count, 0);
        } else if (column.property === 'amount') {
          const total = data.reduce((sum, row) => sum + row.amount, 0);
          sums[index] = this.formatMoney(total);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    yearAmountSummary(param) {
      return this.monthAmountSummary(param);
    },
    yearCategorySummary(param) {
      const sums = [];
      param.columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (column.property === 'count') {
          sums[index] = param.data.reduce((sum, row) => sum + row.count, 0);
        } else if (column.property === 'amount') {
          const total = param.data.reduce((sum, row) => sum + row.amount, 0);
          sums[index] = this.formatMoney(total);
        } else if (column.property === 'ratio') {
          sums[index] = '100%';
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    categorySummary(param) {
      return this.yearCategorySummary(param);
    },
    renderMonthAmountChart() {
      const dom = document.getElementById('monthAmountChart');
      if (!dom) return;
      if (!this.monthAmountChart) {
        this.monthAmountChart = echarts.init(dom);
      }
      this.monthAmountChart.setOption({
        title: { text: `${this.monthAmountYear}年 月度维修费用`, left: 'center', textStyle: { fontSize: 14 } },
        tooltip: { trigger: 'axis' },
        grid: { left: 50, right: 20, bottom: 30, top: 50 },
        xAxis: { type: 'category', data: this.monthAmountTable.map(item => item.month) },
        yAxis: { type: 'value', name: '元' },
        series: [{
          type: 'bar',
          data: this.monthAmountTable.map(item => item.amount),
          itemStyle: { color: '#409EFF' },
          barMaxWidth: 36
        }]
      });
    },
    renderYearAmountChart() {
      const dom = document.getElementById('yearAmountChart');
      if (!dom) return;
      if (!this.yearAmountChart) {
        this.yearAmountChart = echarts.init(dom);
      }
      this.yearAmountChart.setOption({
        title: { text: '年度维修费用汇总', left: 'center', textStyle: { fontSize: 14 } },
        tooltip: { trigger: 'axis' },
        grid: { left: 50, right: 20, bottom: 30, top: 50 },
        xAxis: { type: 'category', data: this.yearAmountTable.map(item => item.year) },
        yAxis: { type: 'value', name: '元' },
        series: [{
          type: 'bar',
          data: this.yearAmountTable.map(item => item.amount),
          itemStyle: { color: '#67C23A' },
          barMaxWidth: 40
        }]
      });
    },
    renderPieChart(chartRef, domId, title, tableData) {
      const dom = document.getElementById(domId);
      if (!dom) return;
      if (!this[chartRef]) {
        this[chartRef] = echarts.init(dom);
      }
      this[chartRef].setOption({
        title: { text: title, left: 'center', textStyle: { fontSize: 14 } },
        tooltip: { trigger: 'item', formatter: '{b}: ¥{c} ({d}%)' },
        legend: { bottom: 0 },
        series: [{
          type: 'pie',
          radius: ['40%', '65%'],
          center: ['50%', '45%'],
          data: tableData.map(item => ({ name: item.label, value: item.amount })),
          emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.2)' } }
        }]
      });
    },
    renderYearCategoryChart() {
      this.renderPieChart('yearCategoryChart', 'yearCategoryChart', `${this.yearCategoryYear}年 分类费用占比`, this.yearCategoryTable);
    },
    renderCategoryChart() {
      const title = this.categoryScope === 'year' ? `${this.categoryYear}年 分类费用占比` : '全部分类费用占比';
      this.renderPieChart('categoryChart', 'categoryChart', title, this.categoryTable);
    },
    resizeCharts() {
      ['monthAmountChart', 'yearAmountChart', 'yearCategoryChart', 'categoryChart'].forEach(key => {
        if (this[key]) this[key].resize();
      });
    },
    disposeCharts() {
      ['monthAmountChart', 'yearAmountChart', 'yearCategoryChart', 'categoryChart'].forEach(key => {
        if (this[key]) {
          this[key].dispose();
          this[key] = null;
        }
      });
    },
    handleExportMonth() {
      this.download('oa/repair/export', {
        params: { statMonth: this.monthViewMonth },
        repairUsage: this.monthViewType
      }, `repair_${this.monthViewMonth}.xlsx`);
    }
  }
};
</script>

<style lang="scss" scoped>
.repair-stat-page {
  .filter-form {
    margin-bottom: 16px;
  }

  .summary-cards {
    margin-bottom: 20px;
  }

  .summary-card {
    text-align: center;
    border-radius: 8px;

    .card-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .card-value {
      font-size: 22px;
      font-weight: 600;
      color: #303133;
    }

    .card-money {
      margin-top: 6px;
      font-size: 16px;
      color: #E6A23C;
      font-weight: 500;
    }

    &.total-card {
      background: linear-gradient(135deg, #ecf5ff 0%, #f0f9ff 100%);
    }
  }

  .money-text {
    color: #E6A23C;
    font-weight: 500;
  }

  .chart-box {
    width: 100%;
    height: 380px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background: #fff;
  }
}
</style>
