<template>
  <!-- 废标项库页面 -->
  <el-card class="rejection-item-container">
    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>

    <!-- 数据列表：完全依赖TableModel的内置搜索 -->
    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :showOperation="true"
        :showRightTools="false"
        ref="rejectionItemTableRef"
        :columnsList="columnsList"
        :sendParams="{ enterpriseId: enterpriseId }"
        :request-api="listRejectionItem"
      >
        <template slot="tableTitle">
          <h3>数据列表</h3>
        </template>
        <template slot="tableActions">
          <el-button
            @click="handleModelExport"
            v-hasPermi="['enterpriseLibrary:rejectionItem:import']"
            class="add-btn"
          >
            导入模板下载
          </el-button>
          <el-button
            @click="handleBatchImport"
            v-hasPermi="['enterpriseLibrary:rejectionItem:import']"
            class="add-btn"
          >
            批量导入
          </el-button>
          <el-button
            @click="handleAdd"
            v-hasPermi="['enterpriseLibrary:rejectionItem:add']"
            class="add-btn"
          >
            <i class="el-icon-plus"></i> 新增废标项
          </el-button>
          <el-button
            @click="handleExport"
            v-hasPermi="['enterpriseLibrary:rejectionItem:export']"
            class="add-btn"
          >
            导出
          </el-button>
        </template>
        <template slot="itemState" slot-scope="{ data }">
          <el-switch
            v-model="data.itemState"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStateChange(data)"
          />
        </template>
        <template slot="handle" slot-scope="{ data }">
          <el-button
            type="text"
            v-hasPermi="['enterpriseLibrary:rejectionItem:edit']"
            class="action-btn"
            style="color: #EAA819;"
            @click="handleUpdate(data)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['enterpriseLibrary:rejectionItem:del']"
            class="action-btn"
            style="color: #DB3E29;"
            @click="handleDelete(data)"
          >
            删除
          </el-button>
        </template>
      </TableModel>
    </div>

    <!-- 新增/编辑废标项弹窗 -->
    <RejectionItemForm
      ref="rejectionItemForm"
      v-if="dialogVisible"
      :isAdd="isAdd"
      :rowData="row"
      @handleQuery="handleQuery"
      @closeDialog="dialogVisible = false"
      :title="dialogTitle"
      :width="600"
    />

    <!-- 批量导入弹窗 -->
    <ImportExcelDialog
      :visible.sync="importExcelDialogVisible"
      ref="importExcelDialog"
      title="废标项导入"
      :upload-url="importExcelDialogUploadUrl"
      @upload-success="handleImportSuccess"
      @close="handleImportClose"
      :maxFileTips="maxFileTips"
      :params="params"
    />
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsList, formLabel } from './config'
import RejectionItemForm from './components/RejectionItemForm.vue'
import {
  importRejectionItem,
  downloadImportTemplate,
  listRejectionItem,
  delRejectionItem,
  updateRejectionItem,
  checkItemNameUnique,
  exportRejectionItem
} from '@/api/enterpriseLibrary/rejectionItem/rejectionItem'
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm'
import { downloadFileWithLoading } from '@/utils/download'
import ImportExcelDialog from '@/views/common/ImportExcelDialog'

// 导入接口地址
const IMPORT_URL = '/smartPlatform/rejectionItem/importData';

export default {
  name: 'RejectionItem',
  components: {
    TableModel,
    RejectionItemForm,
    ImportExcelDialog
  },
  data() {
    return {
      formLabel,
      columnsList,
      listRejectionItem, // 列表查询接口
      dialogVisible: false,
      isAdd: '',
      row: {},
      dialogTitle: '',
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0',
      // 导入相关配置
      maxFileTips: '20MB',
      importExcelDialogVisible: false,
      importExcelDialogUploadUrl: process.env.VUE_APP_BASE_API + IMPORT_URL,
      params: {
        enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0'
      }
    }
  },
  created() {
    // 初始化企业ID到TableModel的查询参数中
    this.$nextTick(() => {
      this.$refs.rejectionItemTableRef.queryParams.enterpriseId = this.enterpriseId
      this.$refs.rejectionItemTableRef.getTableList()
    })
  },
  methods: {
    // 返回上一页
    handleBack() {
      const obj = {
        path: "/enterpriseKnowledge/index",
        query: {
          enterpriseId: encryptWithSM4(this.$refs.rejectionItemTableRef.queryParams.enterpriseId || '0'),
        }
      }
      this.$tab.closeOpenPage(obj)
    },
    // 新增废标项
    handleAdd() {
      this.dialogTitle = "新增废标项";
      this.isAdd = 'add';
      this.row = {
        enterpriseId: this.$refs.rejectionItemTableRef.queryParams.enterpriseId
      }; // 携带企业ID
      this.dialogVisible = true;
    },
    // 修改废标项
    handleUpdate(row) {
      this.dialogTitle = "修改废标项";
      this.isAdd = 'edit';
      this.row = { ...row };
      this.dialogVisible = true;
    },
    // 切换状态（启用/未启用）
    handleStateChange(row) {
      // 保存当前状态（用于更新失败时回滚）
      const originalState = row.itemState;

      // 调用更新接口
      updateRejectionItem({
        ...row,
        itemState: row.itemState
      }).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess("状态更新成功");
          // 状态更新成功后，调用列表接口刷新数据
          this.handleQuery();
        } else {
          this.$modal.msgError(res.msg);
          // 更新失败时回滚开关状态
          row.itemState = originalState;
        }
      }).catch(error => {
        this.$modal.msgError("状态更新失败：" + error);
        // 接口调用失败时回滚开关状态
        row.itemState = originalState;
      });
    },
    // 删除废标项
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除“${row.itemName}”？`).then(() => {
        this.$modal.loading("正在删除，请稍候...");
        delRejectionItem({
          itemId: row.itemId,
          enterpriseId: this.$refs.rejectionItemTableRef.queryParams.enterpriseId
        }).then(res => {
          this.$modal.closeLoading();
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功");
            this.handleQuery();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError(error);
        });
      });
    },
    // 查询列表（调用TableModel的内置方法）
    handleQuery() {
      this.$refs.rejectionItemTableRef.getTableList();
    },

    // 导出废标项
    handleExport() {
      // 1. 获取表格的查询参数
      const queryParams = {
        ...this.$refs.rejectionItemTableRef.queryParams,
        enterpriseId: this.enterpriseId  // 确保携带企业ID
      };

      // 2. 显示加载中提示
      this.$modal.loading("正在导出数据，请稍候...");

      // 3. 调用导出接口
      exportRejectionItem(queryParams)
        .then(blob => {
          this.$modal.closeLoading();

          // 4. 处理文件流，生成下载链接
          const url = window.URL.createObjectURL(new Blob([blob]));
          const a = document.createElement('a');
          a.href = url;
          // 文件名格式：废标项数据_时间戳.xlsx
          a.download = `废标项数据_${new Date().getTime()}.xlsx`;
          document.body.appendChild(a);
          a.click();

          // 5. 清理资源
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);

          // 6. 提示导出成功
          this.$modal.msgSuccess("导出成功");
        })
        .catch(error => {
          this.$modal.closeLoading();
          // 错误处理
          this.$modal.msgError(`导出失败：${error.message || error}`);
        });
    },

    // 模板下载
    handleModelExport() {
      downloadFileWithLoading(
        'smartPlatform/commonDownload/downLoadRejectionModel',
        '废标项导入模板.xlsx',
        '正在下载模板，请稍候...',
      )
    },

    // 批量导入
    handleBatchImport() {
      this.importExcelDialogVisible = true;
    },

    // 导入成功回调
    handleImportSuccess() {
      this.handleQuery();
    },

    // 导入弹窗关闭回调
    handleImportClose() {
      this.handleQuery();
    }
  }
}
</script>

<style scoped lang="scss">
.rejection-item-container {
  height: calc(100vh - 84px);
  overflow: auto;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  padding: 20px;
}

::v-deep .table-card {
  height: calc(100vh - 240px) !important;
}


.back-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;

  .back-btn {
    width: 98px;
    height: 36px;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px;
    border: none;
    color: #666;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
      color: #409EFF;
      box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
  }
}

.add-btn {
  width: 121px;
  height: 36px;
  background: #1F72EA;
  box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
  border-radius: 4px;
  border: none;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s;
  margin-right: 10px;

  &:hover {
    background: #4A8BFF;
    box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
  }
}

.action-btn {
  margin-right: 8px;

  &:last-child {
    margin-right: 0;
  }
}
</style>
