<template>
  <div>
    <!-- 表单查询项 -->
    <div class="headerbox">
      <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="项目名称" prop="postName" style="width: 100%;">
              <el-input v-model="queryParams.postName" placeholder="请输入项目名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="项目建设起止时间" prop="">
              <el-date-picker type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }"
                start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" clearable
                v-model="queryParams.dateRange"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="现状分类">
              <el-select v-model="queryParams.postCode" 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 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="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 表格内容区 -->
    <div class="tablebox">
      <!-- 标签行 -->
      <div class="tablehead">
        <div class="headtitle"><span>项目清单</span></div>
        <div class="headbtn">
          <el-button type="primary" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
          <el-button type="primary" size="mini" @click="handleImport">批量导入</el-button>
        </div>
      </div>
      <!-- 导出行 -->
      <div class="tablebtntwo">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-upload2" size="medium" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown @command="handleExportCommand">
              <el-button type="primary" size="medium">
                导出材料<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="single-material">单片材料</el-dropdown-item>
                <el-dropdown-item command="report">报告</el-dropdown-item>
                <el-dropdown-item command="project-manual">项目手册</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange" stripe>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="项目名称" align="center" prop="name" width="200" />
        <el-table-column label="现状分类" align="center" prop="xzfl" />
        <el-table-column label="项目法人单位" align="center" prop="xmfrdwxz" 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" prop="totalLandArea" />
        <el-table-column label="当前状态" align="center" prop="status">
          <template slot-scope="scope">
            <span :style="{ color: statusColors[scope.row.status] }">{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="getInfo(scope.row)">详情</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color: #F25353;">删除</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" />
    </div>
  </div>
</template>

<script>
import { getBasicInformationPage } from '@/api/ManageApi/index';

export default {
  name: "Post",
  dicts: ['xzfl'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      postList: [],
      // 状态颜色映射
      statusColors: {
        '审核通过': '#6EDABE',
        '待填报': '#FFBF6B',
        '待审核': '#7693D8'
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        xmfrdwxz: undefined,
        dateRange: [],
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 上传的地址
        url: location.origin + "/api/system/post/importData"
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 导入
    handleImport() {
      this.upload.open = true;
    },
    // 文件上传中处理
    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();
    },
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        current: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        startTime: this.queryParams.dateRange ? this.queryParams.dateRange[0] : undefined,
        endTime: this.queryParams.dateRange ? this.queryParams.dateRange[1] : undefined,
        name: this.queryParams.postName,
        xmfrdwxz: this.queryParams.xmfrdwxz,
        xzfl: this.queryParams.postCode
      };
      getBasicInformationPage(params).then(response => {
        const defaultStatusColors = {
          '审核通过': '#6EDABE',
          '待填报': '#FFBF6B',
          '待审核': '#7693D8'
        };
        const defaultTotalLandAreas = [5000, 6000, 7000]; // 假设默认的用地面积

        this.postList = response.data.records.map((item, index) => ({
          ...item,
          status: item.status || Object.keys(defaultStatusColors)[index % Object.keys(defaultStatusColors).length],
          totalLandArea: item.totalLandArea || defaultTotalLandAreas[index % defaultTotalLandAreas.length]
        }));
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取项目列表失败', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      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 = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      const foundItem = this.postList.find(item => item.id === id);
      if (foundItem) {
        this.form = { ...foundItem };
        this.open = true;
        this.title = "修改项目";
      } else {
        console.error('项目未找到');
      }
    },
    /** 详情按钮操作 */
    getInfo(row) {
      this.$store.commit("SET_CRUMBS", this.$route.meta.title + "详情");
      const id = row.id || this.ids[0];
      this.$router.push({ path: `/manage-info/${id}` });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            const index = this.postList.findIndex(item => item.id === this.form.id);
            if (index !== -1) {
              this.postList.splice(index, 1, { ...this.form });
              this.$modal.msgSuccess("修改成功");
            } else {
              console.error('项目未找到');
            }
          } else {
            this.form.id = this.postList.length + 1;
            this.postList.push({ ...this.form });
            this.$modal.msgSuccess("新增成功");
          }
          this.open = false;
          this.getList();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(',');
      this.postList = this.postList.filter(item => !ids.split(',').includes(String(item.id)));
      this.$modal.msgSuccess("删除成功");
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`);
    },
    handleExportCommand(command) {
      let fileName = '';
      switch (command) {
        case 'single-material':
          fileName = 'single-material';
          break;
        case 'report':
          fileName = 'report';
          break;
        case 'project-manual':
          fileName = 'project-manual';
          break;
        default:
          this.$message.error('未知的导出类型');
          return;
      }
      this.download(`system/post/export/${fileName}`, {
        ...this.queryParams
      }, `${fileName}_${new Date().getTime()}.xlsx`).then(() => {
        this.$message.success('下载成功');
      }).catch(() => {
        this.$message.error('下载失败');
      });
    },
    download(url, params, fileName) {
      return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.open('GET', `${process.env.VUE_APP_BASE_API}/${url}`, true);
        request.responseType = 'blob';
        request.onload = () => {
          if (request.status === 200) {
            const blob = new Blob([request.response], { type: 'application/vnd.ms-excel' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            resolve();
          } else {
            reject(new Error('下载失败'));
          }
        };
        request.onerror = () => {
          reject(new Error('下载失败'));
        };
        request.send();
      });
    },
    // 下载模板
    downloadTemplate() {
      this.download('system/post/template', {}, `template_${new Date().getTime()}.xlsx`).then(() => {
        this.$message.success('模板下载成功');
      }).catch(() => {
        this.$message.error('模板下载失败');
      });
    }
  }
};
</script>

<style scoped>
.headerbox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablebox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablehead {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.headbtn {
  display: flex;
}

.tablebtntwo {
  margin-top: 1rem;
  margin-bottom: 1rem;
}
</style>