<template>
  <div class="app-container">
    <!-- 上报确认弹框 -->
    <el-dialog
      title="上报确认"
      :visible.sync="confirmDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :show-close="false"
      :before-close="handleBeforeClose"
    >
      <div style="margin-bottom: 15px;">
        <p style="font-size: 16px; margin-bottom: 10px;">我已仔细核实，无需修改，确认要上报</p>
        <p style="color: #f56c6c; font-size: 14px;">请仔细核对信息后再进行上报操作</p>
      </div>
      <el-checkbox v-model="hasConfirmed" style="margin-top: 10px;">
        <span :style="{ color: hasConfirmed ? '#67c23a' : '#f56c6c' }">
          我已仔细阅读并确认
        </span>
      </el-checkbox>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleConfirm"
          :disabled="!hasConfirmed"
          size="medium"
        >
          确认进入
        </el-button>
      </div>
    </el-dialog>

    <!-- 页面内容容器，根据弹框状态调整透明度 -->
    <div :style="{ opacity: confirmDialogVisible ? 0.5 : 1, pointerEvents: confirmDialogVisible ? 'none' : 'auto' }">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="所属季度" prop="quarter">
          <el-select v-model="queryParams.quarter" placeholder="请选择所属季度" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_QUARTER)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="departmentName">
          <el-input v-model="queryParams.departmentName" placeholder="请输入报送单位" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="上报人类型" prop="reporterType" label-width="98px">
          <el-select v-model="queryParams.reporterType" placeholder="请选择上报人类型：部门/盟市" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_REPORTER_TYPE)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="报送时间" prop="reportTime">
          <el-date-picker v-model="queryParams.reportTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
        </el-form-item>
        <el-form-item label="状态" prop="reportStatus" v-show=!isAdmin>
          <el-select v-model="queryParams.reportStatus" placeholder="请选择状态" clearable size="small">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_REPORT_STATUS)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                     v-hasPermi="['server:harmful-info-report:create']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                     v-hasPermi="['server:harmful-info-report:export']">导出</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-download" size="mini" @click="handleExportSummary" :loading="exportLoading"
                     v-hasPermi="['server:harmful-info-report:adminexport']">年度汇总表导出</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="单位" align="center" prop="departmentName" />
        <el-table-column label="网站" align="center" prop="website" />
        <el-table-column label="新媒体" align="center" prop="newMedia" />
        <el-table-column label="总数" align="center" prop="totalCount" />
        <el-table-column label="所属季度" align="center" prop="quarter">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.TRS_QUARTER" :value="scope.row.quarter" />
          </template>
        </el-table-column>
        <el-table-column label="报送人" align="center" prop="reporterName" />
        <el-table-column label="上报人类型" align="center" prop="reporterType">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.TRS_REPORTER_TYPE" :value="scope.row.reporterType" />
          </template>
        </el-table-column>
        <el-table-column label="报送人电话" align="center" prop="reporterPhone" />
        <el-table-column label="报送时间" align="center" prop="reportTime" width="120">
          <template v-slot="scope">
            <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="reportStatus">
          <template v-slot="scope">
            <el-tag :type="scope.row.reportStatus === '已上报' ? 'success' :  'warning' ">
              <dict-tag :type="DICT_TYPE.TRS_REPORT_STATUS" :value="scope.row.reportStatus" />
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-guide" @click="handleReport(scope.row)"
                       v-hasPermi="['server:harmful-info-report:report']"
                       v-if="scope.row.reportStatus == '未上报'">上报</el-button>
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row.id)">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                       v-hasPermi="['server:harmful-info-report:update']"
                       v-if="scope.row.reportStatus == '未上报'">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['server:harmful-info-report:delete']"
                       v-if="scope.row.reportStatus == '未上报'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

      <!-- 对话框(添加 / 修改) -->
      <HarmfulInfoReportForm ref="formRef" @success="getList" />
      <HarmfulInfoReportDetail ref="detailRef" />

      <!-- 年度汇总表导出对话框 -->
      <el-dialog title="导出年度汇总表" :visible.sync="exportDialogVisible" width="400px">
        <el-form>
          <el-form-item label="选择年份" prop="year">
            <el-select v-model="exportYear" placeholder="请选择年份" style="width: 100%">
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmExportSummary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as HarmfulInfoReportApi from '@/api/server/harmfulinforeport';
import HarmfulInfoReportForm from './HarmfulInfoReportForm.vue';
import HarmfulInfoReportDetail from './HarmfulInfoReportDetail.vue';
import { mapGetters } from 'vuex';

export default {
  name: "HarmfulInfoReport",
  components: {
    HarmfulInfoReportForm,
    HarmfulInfoReportDetail
  },
  data() {
    return {
      // 新增数据项 - 上报确认弹框
      confirmDialogVisible: false,
      hasConfirmed: false,
      isReporterRole: false,

      // 原有数据项
      exportDialogVisible: false,
      exportYear: new Date().getFullYear().toString(),
      yearOptions: [],
      loading: true,
      exportLoading: false,
      showSearch: true,
      total: 0,
      list: [],
      isExpandAll: true,
      refreshTable: true,
      currentRow: {},
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        website: null,
        newMedia: null,
        internalNetwork: null,
        totalCount: null,
        quarter: null,
        reporterName: null,
        reporterType: null,
        reporterPhone: null,
        reportTime: [],
        departmentId: null,
        reportStatus: null,
        reportRemark: null,
      },
    };
  },
  created() {
    // 检查用户角色并显示确认弹框
    this.checkUserRole();

    // 原有created逻辑
    this.getList();
    const currentYear = new Date().getFullYear();
    for (let i = 0; i < 5; i++) {
      this.yearOptions.unshift((currentYear - i).toString());
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    isAdmin() {
      const userInfo = this.$store.state.user;
      const roles = userInfo.roles || [];
      if (roles.includes("trs_report_admin")) {
        return true;
      }
    }
  },
  methods: {
    // 检查用户角色
    checkUserRole() {
      const userInfo = this.$store.state.user;
      const roles = userInfo.roles || [];

      // 判断是否为上报角色（请根据实际角色标识调整）
      // 这里假设上报角色的标识为 'reporter'，请根据实际情况修改
      this.isReporterRole = roles.includes("trs_report_user") ||
        roles.some(role => role.toLowerCase().includes('trs_report_user'));

      // 如果是上报角色，每次进入都显示确认弹框
      if (this.isReporterRole) {
        this.confirmDialogVisible = true;
        this.hasConfirmed = false; // 每次重置确认状态
      }
    },

    // 处理确认操作
    handleConfirm() {
      if (this.hasConfirmed) {
        this.confirmDialogVisible = false;
        // 这里可以添加其他确认后的逻辑
      }
    },

    // 防止用户通过关闭按钮关闭弹框
    handleBeforeClose(done) {
      if (this.hasConfirmed) {
        done();
      } else {
        this.$message.warning('请先确认已仔细阅读并核实信息');
      }
    },

    // 原有方法保持不变
    async getList() {
      try {
        this.loading = true;
        if (this.isAdmin) {
          this.queryParams.reportStatus = '已上报';
        }
        const res = await HarmfulInfoReportApi.getHarmfulInfoReportPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleDetail(id) {
      this.$refs["detailRef"].open(id);
    },

    openForm(id) {
      this.$refs["formRef"].open(id);
    },

    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除信息上报编号为"' + id + '"的数据项?')
      try {
        await HarmfulInfoReportApi.deleteHarmfulInfoReport(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    async handleReport(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认上报信息上报编号为"' + id + '"的数据项?')
      try {
        await HarmfulInfoReportApi.reportHarmfulInfoReport(id);
        await this.getList();
        this.$modal.msgSuccess("上报成功");
      } catch {}
    },

    async handleExport() {
      await this.$modal.confirm('是否确认导出所有有害信息上报数据项?');
      try {
        this.exportLoading = true;
        const data = await HarmfulInfoReportApi.exportHarmfulInfoReportExcel(this.queryParams);
        this.$download.excel(data, '有害信息上报.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    handleExportSummary() {
      this.exportDialogVisible = true;
    },

    async confirmExportSummary() {
      if (!this.exportYear) {
        this.$modal.msgWarning('请选择年份');
        return;
      }
      this.exportDialogVisible = false;
      this.exportLoading = true;
      try {
        const params = {
          ...this.queryParams,
          year: this.exportYear
        };
        const response = await HarmfulInfoReportApi.exportSummaryExcel(params);
        this.$download.excel(response, `有害信息上报${this.exportYear}年度汇总表.xlsx`);
      } finally {
        this.exportLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  position: relative;
}

.dialog-footer {
  text-align: right;
}

/* 添加一些样式增强用户体验 */
.el-dialog__body p {
  line-height: 1.6;
}

.el-checkbox {
  margin-left: 5px;
}
</style>
