<template>
  <div class="container">
    <!-- 查询表单 -->
    <!-- 政务端 -->
    <div class="headerbox" v-if="checkRole(['common', 'gov'])">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="200"
      >
        <el-row>
          <el-col :span="5">
            <el-form-item label="项目名称" style="width: 100%">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="建设起止时间">
              <el-date-picker
                v-model="queryParams.startTime"
                type="month"
                placeholder="开始月份"
                value-format="yyyy-MM"
                style="width: 9rem"
                :clearable="true"
              ></el-date-picker>
              ~
              <el-date-picker
                v-model="queryParams.endTime"
                type="month"
                placeholder="结束月份"
                value-format="yyyy-MM"
                style="width: 9rem"
                :clearable="true"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="现状分类">
              <el-select
                v-model="queryParams.xzfl"
                placeholder="请选择现状分类"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.xzfl"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目法人单位">
              <el-input
                v-model="queryParams.xmfrdwxz"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="当前状态">
              <el-select
                v-model="queryParams.status"
                placeholder="选择当前状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.tbzt"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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-col>
        </el-row>
      </el-form>
    </div>
    <!-- 企业端的查询项 -->
    <div class="headerbox" v-else>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="200"
      >
        <el-row>
          <el-col :span="5">
            <el-form-item label="项目名称" style="width: 100%">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入项目名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="建设起止时间">
              <el-date-picker
                v-model="queryParams.startTime"
                type="month"
                placeholder="开始月份"
                value-format="yyyy-MM"
                style="width: 9rem"
                :clearable="true"
              >
              </el-date-picker>
              ~
              <el-date-picker
                v-model="queryParams.endTime"
                type="month"
                placeholder="结束月份"
                value-format="yyyy-MM"
                style="width: 9rem"
                :clearable="true"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="现状分类">
              <el-select
                v-model="queryParams.xzfl"
                placeholder="现状分类"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.xzfl"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="medium"
                @click="handleQuery"
                >查询</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="medium"
                @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 表格内容区 -->
    <!-- 政务端 -->
    <div class="table-container" v-if="checkRole(['common', 'gov'])">
      <!-- 按钮行 -->
      <div class="table-header">
        <el-row :gutter="4">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleExport">全量导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleExporttwo"
              >单片材料导出</el-button
            >
          </el-col>
        </el-row>
        <el-row :gutter="4">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-download"
              @click="importTemplate"
              >下载模板</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="handleImport">批量导入</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="postList"
          @selection-change="handleSelectionChange"
          stripe
          height="100%"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center">
            <template slot-scope="scope">
              {{
                scope.$index + 1 + (queryParams.current - 1) * queryParams.size
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="项目名称"
            align="center"
            prop="name"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column label="现状分类" align="center" prop="xzfl">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.xzfl" :value="scope.row.xzfl" />
            </template>
          </el-table-column>
          <el-table-column
            label="项目法人单位"
            align="center"
            prop="xmfrdwxz"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column
            label="统一社会信用代码"
            align="center"
            prop="tyshxydm"
            width="200"
          />
          <el-table-column label="项目建设起止时间" align="center" width="200">
            <template slot-scope="scope">
              {{ formatMonth(scope.row.begainTime) }} 至
              {{ formatMonth(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="总投资额（万元）"
            align="center"
            width="130"
            prop="ztze"
          />
          <el-table-column
            label="总用地面积（平方米）"
            align="center"
            width="180"
            prop="zydmj"
          />
          <el-table-column label="当前状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.tbzt" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="getAdd(scope.row, 'fill')"
                v-if="scope.row.status === 2"
                >审核</el-button
              >
              <el-button
                type="text"
                @click="getAdd(scope.row, 'okay')"
                v-if="scope.row.status === 3"
                >编辑</el-button
              >
              <el-button
                type="text"
                @click="getAdd(scope.row, 'detail')"
                v-if="scope.row.status === 1"
                >详情</el-button
              >
              <el-button
                type="text"
                @click="handleDelete(scope.row)"
                style="color: #f25353"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 企业端表格内容区 -->
    <div class="table-container" v-else>
      <!-- 导入弹窗 -->
      <el-dialog
        title="导入"
        :visible.sync="upload.open"
        width="400px"
        append-to-body
      >
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :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 text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button @click="upload.open = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitFileForm"
            :loading="upload.isUploading"
            >确定</el-button
          >
        </span>
      </el-dialog>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="postList"
          @selection-change="handleSelectionChange"
          stripe
        >
          <el-table-column label="序号" align="center">
            <template slot-scope="scope">
              {{
                scope.$index + 1 + (queryParams.current - 1) * queryParams.size
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="项目名称"
            align="center"
            prop="name"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column label="现状分类" align="center" prop="xzfl">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.xzfl" :value="scope.row.xzfl" />
            </template>
          </el-table-column>
          <el-table-column
            label="项目法人单位"
            align="center"
            prop="xmfrdwxz"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column
            label="统一社会信用代码"
            align="center"
            prop="tyshxydm"
            width="200"
          />
          <el-table-column label="项目建设起止时间" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.begainTime }} 至 {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column
            label="总投资额（万元）"
            align="center"
            width="130"
            prop="ztze"
          />
          <el-table-column
            label="总用地面积（平方米）"
            align="center"
            width="180"
            prop="zydmj"
          />
          <el-table-column label="当前状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.tbzt" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="medium"
                type="text"
                @click="getInfo(scope.row, 'fill')"
                v-if="scope.row.status === 1"
                >填报</el-button
              >
              <el-button
                size="medium"
                type="text"
                @click="getInfo(scope.row, 'detail')"
                v-if="scope.row.status !== 1"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 导入按钮弹窗 -->
    <el-dialog
      title="导入"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :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 text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="upload.isUploading"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBasicInformationPage,
  deleteBasicInformation,
} from "@/api/ManageApi/index";
import { getToken } from "@/utils/auth";
import { checkPermi, checkRole } from "@/utils/permission";
export default {
  dicts: ["xzfl", "tbzt"],
  data() {
    return {
      ids: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      postList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        xzfl: undefined,
        name: undefined,
        xmfrdwxz: undefined,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
      },
      // 导入相关数据
      upload: {
        open: false, // 是否显示导入弹窗
        isUploading: false, // 是否正在上传
        updateSupport: 0, // 是否更新已存在数据
        headers: { Authorization: "Bearer " + getToken() }, // 上传请求头
        url: process.env.VUE_APP_BASE_API + "/gysl/basicInformation/import", // 上传地址
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkPermi,
    checkRole,
    /** 格式化月份显示 */
    formatMonth(dateStr) {
      if (!dateStr) return "";
      // 如果已经是 YYYY-MM 格式，直接返回
      if (/^\d{4}-\d{2}$/.test(dateStr)) return dateStr;
      // 如果是 YYYY-MM-DD 格式，截取前7位
      if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return dateStr.substring(0, 7);
      return dateStr;
    },

    /** 查询项目列表 */
    getList() {
      this.loading = true;
      // 确保日期参数格式正确
      const params = {
        ...this.queryParams,
        begainTime: this.formatMonth(this.queryParams.begainTime),
        endTime: this.formatMonth(this.queryParams.endTime),
      };

      getBasicInformationPage(params)
        .then((response) => {
          this.postList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error("API请求错误:", error);
          console.error("错误详情:", error.response);
          this.loading = false;
        });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/gysl/basicInformation/importTemplate",
        {},
        `项目导入模板${new Date().getTime()}.xlsx`
      );
    },

    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/gysl/basicInformation/exportInfo",
        {
          idList: this.ids,
        },
        `基本信息${new Date().getTime()}.xlsx`
      );
    },

    /** 单片材料导出按钮操作 */
    handleExporttwo() {
      if (this.ids.length === 0) {
        this.$message.warning("请选择要导出的项目");
        return;
      }

      this.download(
        "/gysl/basicInformation/wordExport",
        {
          ids: this.ids.join(","),
        },
        `单片材料${new Date().getTime()}.zip`
      );
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const projectName = row.name;
      const ids = row.id || this.ids;
      this.$modal
        .confirm(`是否确认删除项目"${projectName}"？`)
        .then(() => {
          return deleteBasicInformation(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 详情按钮操作 */
    getAdd(row, type) {
      this.$store.commit("SET_CRUMBS", "项目详情");
      const id = row.id || this.ids[0];
      this.$router.push({ path: `/manage-add/${id}`, query: { action: type } });
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        xzfl: undefined,
        name: undefined,
        xmfrdwxz: undefined,
        begainTime: undefined,
        endTime: undefined,
        status: undefined,
      };
      this.getList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 详情按钮操作 */
    getInfo(row, type) {
      this.$store.commit("SET_CRUMBS", "项目详情");
      const id = row.id || this.ids[0];
      this.$router.push({
        path: `/manage-info/${id}`,
        query: { action: type },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  overflow: hidden;
}
.headerbox {
  background-color: #fff;
  border-radius: 0.5rem;
  padding: 1rem 1rem 0rem 1rem;
  margin-bottom: 0.5rem;
  border: 1px solid #eee;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 0.5rem;
  padding: 1rem;
  border: 1px solid #eee;
  overflow: hidden;
}

.table-header {
  margin-bottom: 1rem;
  width: 99.7%;
  display: flex;
  justify-content: space-between;
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.el-table {
  height: 100% !important;
}

/* 隐藏滚动条但保留功能 */
.table-container ::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
  display: none;
}

/* 兼容 Firefox */
.table-container {
  scrollbar-width: none;
}
</style>
