<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px" class="query-form">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="员工工号" prop="staffId">
            <el-select v-model="queryParams.staffId" placeholder="请选择员工工号" clearable filterable style="width: 100%">
              <el-option
                v-for="item in staffOptions"
                :key="item.staffId"
                :label="item.staffId"
                :value="item.staffId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="员工姓名" prop="staffName">
            <el-input
              v-model="queryParams.staffName"
              placeholder="请输入员工姓名"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调动类型" prop="transferType">
            <el-select v-model="queryParams.transferType" placeholder="请选择调动类型" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.ccdi_transfer_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调动日期" prop="transferDateRange">
            <el-date-picker
              v-model="queryParams.transferDateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调动前部门" prop="deptNameBefore">
            <el-input
              v-model="queryParams.deptNameBefore"
              placeholder="请输入调动前部门"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调动后部门" prop="deptNameAfter">
            <el-input
              v-model="queryParams.deptNameAfter"
              placeholder="请输入调动后部门"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ccdi:staffTransfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ccdi:staffTransfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ccdi:staffTransfer:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5" v-if="showFailureButton">
        <el-tooltip
          :content="getLastImportTooltip()"
          placement="top"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-warning"
            size="mini"
            @click="viewImportFailures"
          >查看导入失败记录</el-button>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工工号" align="center" prop="staffId" width="120"/>
      <el-table-column label="员工姓名" align="center" prop="staffName" :show-overflow-tooltip="true"/>
      <el-table-column label="调动类型" align="center" prop="transferType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ccdi_transfer_type" :value="scope.row.transferType"/>
        </template>
      </el-table-column>
      <el-table-column label="调动子类型" align="center" prop="transferSubType" :show-overflow-tooltip="true"/>
      <el-table-column label="调动前部门" align="center" prop="deptNameBefore" :show-overflow-tooltip="true"/>
      <el-table-column label="调动前职级" align="center" prop="gradeBefore" width="100"/>
      <el-table-column label="调动前岗位" align="center" prop="positionBefore" :show-overflow-tooltip="true"/>
      <el-table-column label="调动后部门" align="center" prop="deptNameAfter" :show-overflow-tooltip="true"/>
      <el-table-column label="调动后职级" align="center" prop="gradeAfter" width="100"/>
      <el-table-column label="调动后岗位" align="center" prop="positionAfter" :show-overflow-tooltip="true"/>
      <el-table-column label="调动日期" align="center" prop="transferDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ccdi:staffTransfer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ccdi:staffTransfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="员工" prop="staffId">
              <el-select
                v-model="form.staffId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入员工姓名或工号搜索"
                :remote-method="searchStaff"
                :loading="staffLoading"
                :disabled="!isAdd"
                @change="handleStaffChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in staffOptions"
                  :key="item.staffId"
                  :label="item.staffId + ' - ' + item.name"
                  :value="item.staffId"
                >
                  <span style="float: left">{{ item.staffId }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动类型" prop="transferType">
              <el-select v-model="form.transferType" placeholder="请选择调动类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ccdi_transfer_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="调动子类型" prop="transferSubType">
              <el-input v-model="form.transferSubType" placeholder="请输入调动子类型" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动日期" prop="transferDate">
              <el-date-picker
                v-model="form.transferDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">调动前信息</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="调动前部门" prop="deptIdBefore">
              <treeselect
                v-model="form.deptIdBefore"
                :options="enabledDeptOptions"
                :show-count="true"
                placeholder="请选择调动前部门"
                @input="handleDeptBeforeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动前职级" prop="gradeBefore">
              <el-input v-model="form.gradeBefore" placeholder="请输入调动前职级" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="调动前岗位" prop="positionBefore">
              <el-input v-model="form.positionBefore" placeholder="请输入调动前岗位" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动前薪酬等级" prop="salaryLevelBefore">
              <el-input v-model="form.salaryLevelBefore" placeholder="请输入调动前薪酬等级" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">调动后信息</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="调动后部门" prop="deptIdAfter">
              <treeselect
                v-model="form.deptIdAfter"
                :options="enabledDeptOptions"
                :show-count="true"
                placeholder="请选择调动后部门"
                @input="handleDeptAfterChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动后职级" prop="gradeAfter">
              <el-input v-model="form.gradeAfter" placeholder="请输入调动后职级" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="调动后岗位" prop="positionAfter">
              <el-input v-model="form.positionAfter" placeholder="请输入调动后岗位" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调动后薪酬等级" prop="salaryLevelAfter">
              <el-input v-model="form.salaryLevelAfter" placeholder="请输入调动后薪酬等级" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      @close="handleImportDialogClose"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span>仅允许导入"xls"或"xlsx"格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入失败记录对话框 -->
    <el-dialog
      title="导入失败记录"
      :visible.sync="failureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="lastImportInfo"
        :title="lastImportInfo"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="failureList" v-loading="failureLoading">
        <el-table-column label="员工工号" prop="staffId" align="center" width="120"/>
        <el-table-column label="员工姓名" prop="staffName" align="center" width="120"/>
        <el-table-column label="调动类型" prop="transferType" align="center" width="100"/>
        <el-table-column label="失败原因" prop="errorMessage" align="center" min-width="200" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="failureTotal > 0"
        :total="failureTotal"
        :page.sync="failureQueryParams.pageNum"
        :limit.sync="failureQueryParams.pageSize"
        @pagination="getFailureList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="failureDialogVisible = false">关闭</el-button>
        <el-button type="danger" plain @click="clearImportHistory">清除历史记录</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addTransfer,
  delTransfer,
  getImportFailures,
  getImportStatus,
  getStaffList,
  getTransfer,
  listTransfer,
  updateTransfer
} from "@/api/ccdiStaffTransfer";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptTreeSelect} from "@/api/system/user";

export default {
  name: "StaffTransfer",
  dicts: ['ccdi_transfer_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工调动记录表格数据
      transferList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为新增操作
      isAdd: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        staffId: null,
        staffName: null,
        transferType: null,
        transferDateRange: null,
        deptNameBefore: null,
        deptNameAfter: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        staffId: [
          { required: true, message: "员工不能为空", trigger: "change" }
        ],
        transferType: [
          { required: true, message: "调动类型不能为空", trigger: "change" }
        ],
        transferDate: [
          { required: true, message: "调动日期不能为空", trigger: "change" }
        ],
        deptIdBefore: [
          { required: true, message: "调动前部门不能为空", trigger: "change" }
        ],
        deptIdAfter: [
          { required: true, message: "调动后部门不能为空", trigger: "change" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ccdi/staffTransfer/importData"
      },
      // 导入轮询定时器
      importPollingTimer: null,
      // 是否显示查看失败记录按钮
      showFailureButton: false,
      // 当前导入任务ID
      currentTaskId: null,
      // 失败记录对话框
      failureDialogVisible: false,
      failureList: [],
      failureLoading: false,
      failureTotal: 0,
      failureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 员工选项
      staffOptions: [],
      staffLoading: false,
      // 部门树选项
      deptOptions: undefined,        // 所有部门树选项
      enabledDeptOptions: undefined  // 过滤掉已禁用部门树选项
    };
  },
  computed: {
    /**
     * 上次导入信息摘要
     */
    lastImportInfo() {
      const savedTask = this.getImportTaskFromStorage();
      if (savedTask && savedTask.totalCount) {
        return `导入时间: ${this.parseTime(savedTask.saveTime)} | 总数: ${savedTask.totalCount}条 | 成功: ${savedTask.successCount}条 | 失败: ${savedTask.failureCount}条`;
      }
      return '';
    }
  },
  created() {
    this.getList();
    this.restoreImportState();
    this.loadAllStaff();
    this.getDeptTree();
  },
  beforeDestroy() {
    if (this.importPollingTimer) {
      clearInterval(this.importPollingTimer);
      this.importPollingTimer = null;
    }
  },
  methods: {
    /** 查询员工调动记录列表 */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      // 处理日期范围
      if (params.transferDateRange && params.transferDateRange.length === 2) {
        params.beginTransferDate = params.transferDateRange[0];
        params.endTransferDate = params.transferDateRange[1];
      }
      delete params.transferDateRange;

      listTransfer(params).then(response => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索员工 */
    searchStaff(query) {
      this.staffLoading = false;
      if (query !== '') {
        this.staffLoading = true;
        getStaffList(query).then(response => {
          this.staffOptions = response.data;
          this.staffLoading = false;
        }).catch(() => {
          this.staffLoading = false;
        });
      }
    },
    /** 加载所有员工(用于查询条件下拉) */
    loadAllStaff() {
      getStaffList('').then(response => {
        this.staffOptions = response.data || [];
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
      });
    },
    /** 过滤禁用的部门 */
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    /** 员工选择变化 */
    handleStaffChange(staffId) {
      // 不再自动填充调动前信息，由用户手动输入
      // 因为新的 baseStaff 接口不返回部门等信息
    },
    /** 调动前部门选择变化 - 自动填充部门名称 */
    handleDeptBeforeChange(value) {
      if (value) {
        const dept = this.findDeptById(this.enabledDeptOptions, value);
        if (dept) {
          this.form.deptIdBefore = value;
          this.form.deptNameBefore = dept.label;
        }
      } else {
        this.form.deptIdBefore = null;
        this.form.deptNameBefore = null;
      }
    },
    /** 调动后部门选择变化 - 自动填充部门名称 */
    handleDeptAfterChange(value) {
      if (value) {
        const dept = this.findDeptById(this.enabledDeptOptions, value);
        if (dept) {
          this.form.deptIdAfter = value;
          this.form.deptNameAfter = dept.label;
        }
      } else {
        this.form.deptIdAfter = null;
        this.form.deptNameAfter = null;
      }
    },
    /** 递归查找部门 */
    findDeptById(tree, id) {
      for (let node of tree) {
        if (node.id === id) return node;
        if (node.children && node.children.length > 0) {
          const found = this.findDeptById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    /**
     * 恢复导入状态
     */
    restoreImportState() {
      const savedTask = this.getImportTaskFromStorage();
      if (!savedTask) {
        this.showFailureButton = false;
        this.currentTaskId = null;
        return;
      }
      if (savedTask.hasFailures && savedTask.taskId) {
        this.currentTaskId = savedTask.taskId;
        this.showFailureButton = true;
      }
    },
    /**
     * 获取上次导入的提示信息
     */
    getLastImportTooltip() {
      const savedTask = this.getImportTaskFromStorage();
      if (savedTask && savedTask.saveTime) {
        const date = new Date(savedTask.saveTime);
        const timeStr = this.parseTime(date, '{y}-{m}-{d} {h}:{i}');
        return `上次导入: ${timeStr}`;
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        staffId: null,
        transferType: null,
        transferSubType: null,
        deptIdBefore: null,
        deptNameBefore: null,
        gradeBefore: null,
        positionBefore: null,
        salaryLevelBefore: null,
        deptIdAfter: null,
        deptNameAfter: null,
        gradeAfter: null,
        positionAfter: null,
        salaryLevelAfter: null,
        transferDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.transferDateRange = null;
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工调动记录";
      this.isAdd = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getTransfer(id).then(response => {
        this.form = response.data;
        // 加载员工信息以支持下拉显示
        if (this.form.staffId) {
          this.searchStaff(this.form.staffName || '');
        }
        this.open = true;
        this.title = "修改员工调动记录";
        this.isAdd = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            addTransfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateTransfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? row.id : this.ids;
      this.$modal.confirm('是否确认删除选中的数据项?').then(function() {
        return delTransfer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "员工调动记录数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('ccdi/staffTransfer/importTemplate', {}, `员工调动记录导入模板_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.upload.open = false;

      if (response.code === 200) {
        if (!response.data || !response.data.taskId) {
          this.$modal.msgError('导入任务创建失败:缺少任务ID');
          this.upload.isUploading = false;
          this.upload.open = true;
          return;
        }

        const taskId = response.data.taskId;

        if (this.importPollingTimer) {
          clearInterval(this.importPollingTimer);
          this.importPollingTimer = null;
        }

        this.clearImportTaskFromStorage();

        this.saveImportTaskToStorage({
          taskId: taskId,
          status: 'PROCESSING',
          timestamp: Date.now(),
          hasFailures: false
        });

        this.showFailureButton = false;
        this.currentTaskId = taskId;

        this.$notify({
          title: '导入任务已提交',
          message: '正在后台处理中,处理完成后将通知您',
          type: 'info',
          duration: 3000
        });

        this.startImportStatusPolling(taskId);
      } else {
        this.$modal.msgError(response.msg);
      }
    },
    /** 开始轮询导入状态 */
    startImportStatusPolling(taskId) {
      let pollCount = 0;
      const maxPolls = 150;

      this.importPollingTimer = setInterval(async () => {
        try {
          pollCount++;

          if (pollCount > maxPolls) {
            clearInterval(this.importPollingTimer);
            this.$modal.msgWarning('导入任务处理超时,请联系管理员');
            return;
          }

          const response = await getImportStatus(taskId);

          if (response.data && response.data.status !== 'PROCESSING') {
            clearInterval(this.importPollingTimer);
            this.handleImportComplete(response.data);
          }
        } catch (error) {
          clearInterval(this.importPollingTimer);
          this.$modal.msgError('查询导入状态失败: ' + error.message);
        }
      }, 2000);
    },
    /** 查询失败记录列表 */
    getFailureList() {
      this.failureLoading = true;
      getImportFailures(
        this.currentTaskId,
        this.failureQueryParams.pageNum,
        this.failureQueryParams.pageSize
      ).then(response => {
        this.failureList = response.rows;
        this.failureTotal = response.total;
        this.failureLoading = false;
      }).catch(error => {
        this.failureLoading = false;
        if (error.response && error.response.status === 404) {
          this.$modal.msgWarning('导入记录已过期,无法查看失败记录');
          this.clearImportTaskFromStorage();
          this.showFailureButton = false;
          this.currentTaskId = null;
          this.failureDialogVisible = false;
        } else {
          this.$modal.msgError('查询失败记录失败');
        }
      });
    },
    /** 查看导入失败记录 */
    viewImportFailures() {
      this.failureDialogVisible = true;
      this.getFailureList();
    },
    /** 处理导入完成 */
    handleImportComplete(statusResult) {
      this.saveImportTaskToStorage({
        taskId: statusResult.taskId,
        status: statusResult.status,
        hasFailures: statusResult.failureCount > 0,
        totalCount: statusResult.totalCount,
        successCount: statusResult.successCount,
        failureCount: statusResult.failureCount
      });

      if (statusResult.status === 'SUCCESS') {
        this.$notify({
          title: '导入完成',
          message: `全部成功!共导入${statusResult.totalCount}条数据`,
          type: 'success',
          duration: 5000
        });
        this.showFailureButton = false;
        this.getList();
      } else if (statusResult.failureCount > 0) {
        this.$notify({
          title: '导入完成',
          message: `成功${statusResult.successCount}条,失败${statusResult.failureCount}条`,
          type: 'warning',
          duration: 5000
        });
        this.showFailureButton = true;
        this.currentTaskId = statusResult.taskId;
        this.getList();
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 关闭导入对话框
    handleImportDialogClose() {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    /**
     * 保存导入任务到localStorage
     */
    saveImportTaskToStorage(taskData) {
      try {
        const data = {
          ...taskData,
          saveTime: Date.now()
        };
        localStorage.setItem('staff_transfer_import_last_task', JSON.stringify(data));
      } catch (error) {
        console.error('保存导入任务状态失败:', error);
      }
    },
    /**
     * 从localStorage读取导入任务
     */
    getImportTaskFromStorage() {
      try {
        const data = localStorage.getItem('staff_transfer_import_last_task');
        if (!data) return null;

        const task = JSON.parse(data);
        if (!task || !task.taskId) {
          this.clearImportTaskFromStorage();
          return null;
        }

        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        if (Date.now() - task.saveTime > sevenDays) {
          this.clearImportTaskFromStorage();
          return null;
        }

        return task;
      } catch (error) {
        console.error('读取导入任务状态失败:', error);
        this.clearImportTaskFromStorage();
        return null;
      }
    },
    /**
     * 清除导入历史记录
     */
    clearImportHistory() {
      this.$confirm('确认清除上次导入记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearImportTaskFromStorage();
        this.showFailureButton = false;
        this.currentTaskId = null;
        this.failureDialogVisible = false;
        this.$message.success('已清除');
      }).catch(() => {});
    },
    /**
     * 清除localStorage中的导入任务
     */
    clearImportTaskFromStorage() {
      try {
        localStorage.removeItem('staff_transfer_import_last_task');
      } catch (error) {
        console.error('清除导入任务状态失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.query-form ::v-deep .el-row {
  display: flex;
  flex-wrap: wrap;
}

.query-form ::v-deep .el-col {
  float: none;
}

.query-form ::v-deep .el-form-item {
  margin-right: 0;
}
</style>
