<template>
  <!-- 奖惩规则配置 -->
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="区县公司" prop="countyOrgNm">
        <el-input
          v-model="queryParams.countyOrgNm"
          placeholder="请输入区县公司"
        />
      </el-form-item>
      <el-form-item label="队伍名称" prop="teamNm">
        <el-input v-model="queryParams.teamNm" placeholder="请输入队伍名称" />
      </el-form-item>
      <el-form-item label="项目负责人" prop="teamLeader">
        <el-input
          v-model="queryParams.teamLeader"
          placeholder="请输入项目负责人"
        />
      </el-form-item>
      <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-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-upload
          :action="uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-error="handleError"
        >
          <el-button type="primary" icon="el-icon-upload" size="mini"
            >全量导入</el-button
          >
        </el-upload>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div class="table" v-loading="loading">
      <el-table
        v-if="!loading"
        ref="renewalTable"
        :data="wrapperDataList"
        row-key="id"
        border
        :span-method="objectSpanMethod"
      >
        <el-table-column
          label="区县公司"
          align="center"
          prop="countyOrgNm"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="队伍名称"
          align="center"
          prop="teamNm"
          width="220"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="姓名法人代表"
          align="center"
          prop="legalPerson"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="法人代表电话号码"
          align="center"
          prop="legalContactPhone"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组序号"
          align="center"
          prop="teamSerialNo"
          width="70"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组负责人姓名"
          align="center"
          prop="teamLeader"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组负责人电话号码"
          align="center"
          prop="teamLeaderPhone"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组人员类型"
          align="center"
          prop="construct.constructPersonType"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组人员姓名"
          align="center"
          prop="construct.constructPersonnelName"
          width="120"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组人员电话号码"
          align="center"
          prop="construct.constructPersonnelPhone"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="施工小组作业车牌号"
          align="center"
          prop="construcCarNumber"
        >
          <template slot-scope="scope">
            <div style="white-space: wrap">
              {{ scope.row.construcCarNumber.join("、") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="施工小组驻点地理位置"
          align="center"
          prop="arrestPoint"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <div style="white-space: wrap">
              {{ scope.row.arrestPoint }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="操作"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="page-box"
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <add-edit ref="addEdit" @success="getList" />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  constructTeam,
  deleteConstructTeam,
} from "@/api/powerdistribution/team-manage";
import AddEdit from "./add-edit/index";
import { personTypeOptions } from "./team.data";

export default {
  components: {
    AddEdit,
  },
  data() {
    return {
      // 上传相关配置
      uploadUrl:
        process.env.VUE_APP_BASE_API +
        "/powerdistribution/constructTeam/import", // 上传地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      personTypeOptions,
      dataList: [],
      wrapperDataList: [],
      loading: true,
      curKey: null,
      editObj: {},
      total: 0,
      queryParams: {
        countyOrgNm: "",
        teamNm: "",
        teamLeader: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 显示搜索条件
      showSearch: true,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleAdd() {
      this.$refs.addEdit.init();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      constructTeam(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.wrapperData();
        this.loading = false;
      });
    },
    // 处理数据
    wrapperData() {
      this.wrapperDataList = [];
      this.dataList.forEach((item) => {
        if (item.constructorList && item.constructorList.length) {
          item.constructorList.forEach((c) => {
            this.wrapperDataList.push({
              ...item,
              pId: item.id,
              id: c.id,
              construct: { ...c },
            });
          });
        }
      });

      // 修改排序逻辑，添加createTime排序
      this.wrapperDataList = this.wrapperDataList
        .sort((a, b) => {
          // 首先按创建时间降序排序（新的在前）
          if (a.createTime && b.createTime) {
            return new Date(b.createTime) - new Date(a.createTime);
          }
          return 0;
        })
        .sort((a, b) => a.teamNm - b.teamNm)
        .sort((a, b) => a.teamSerialNo - b.teamSerialNo);
    },
    objectSpanMethod({ row, column, rowIndex }) {
      // 需要合并的列
      const mergeColumns = [
        "countyOrgNm",
        "teamNm",
        "legalPerson",
        "legalContactPhone",
        "teamSerialNo",
        "teamLeader",
        "teamLeaderPhone",
        "construcCarNumber",
        "arrestPoint",
      ];

      // 操作列单独处理
      if (column.property === "操作") {
        const currentValue = row.teamNm;
        const currentCounty = row.countyOrgNm;
        let rowspan = 1;

        // 向下检查相同的值
        for (let i = rowIndex + 1; i < this.wrapperDataList.length; i++) {
          if (
            this.wrapperDataList[i].teamNm === currentValue &&
            this.wrapperDataList[i].countyOrgNm === currentCounty &&
            this.wrapperDataList[i].teamSerialNo === row.teamSerialNo
          ) {
            rowspan++;
          } else {
            break;
          }
        }

        // 如果不是第一个出现的值，返回 { rowspan: 0, colspan: 0 }
        if (
          rowIndex > 0 &&
          this.wrapperDataList[rowIndex - 1].teamNm === currentValue &&
          this.wrapperDataList[rowIndex - 1].countyOrgNm === currentCounty &&
          this.wrapperDataList[rowIndex - 1].teamSerialNo === row.teamSerialNo
        ) {
          return { rowspan: 0, colspan: 0 };
        }

        return { rowspan, colspan: 1 };
      }

      // 其他需要合并的列
      if (mergeColumns.includes(column.property)) {
        const currentValue = row[column.property];
        const currentCounty = row.countyOrgNm;
        const currentTeam = row.teamNm;
        let rowspan = 1;

        // 向下检查相同的值
        for (let i = rowIndex + 1; i < this.wrapperDataList.length; i++) {
          const nextRow = this.wrapperDataList[i];

          // 所有列都需要考虑队伍名称
          if (
            nextRow[column.property] === currentValue &&
            nextRow.countyOrgNm === currentCounty &&
            nextRow.teamNm === currentTeam
          ) {
            rowspan++;
          } else {
            break;
          }
        }

        // 如果不是第一个出现的值，返回 { rowspan: 0, colspan: 0 }
        if (rowIndex > 0) {
          const prevRow = this.wrapperDataList[rowIndex - 1];

          // 所有列都需要考虑队伍名称
          if (
            prevRow[column.property] === currentValue &&
            prevRow.countyOrgNm === currentCounty &&
            prevRow.teamNm === currentTeam
          ) {
            return { rowspan: 0, colspan: 0 };
          }
        }

        return { rowspan, colspan: 1 };
      }

      // 其他列不合并
      return { rowspan: 1, colspan: 1 };
    },
    handleUpdate(row) {
      console.log(row, "row");
      let _data = { ...row };
      // 获取完整的施工人员列表
      const constructorList =
        this.dataList.find((item) => item.id === _data.pId)?.constructorList ||
        [];

      // 构造编辑数据
      const editData = {
        id: _data.pId,
        countyOrgNm: _data.countyOrgNm,
        teamNm: _data.teamNm,
        legalPerson: _data.legalPerson,
        legalContactPhone: _data.legalContactPhone,
        teamSerialNo: _data.teamSerialNo,
        teamLeader: _data.teamLeader,
        teamLeaderPhone: _data.teamLeaderPhone,
        construcCarNumber: _data.construcCarNumber,
        arrestPoint: _data.arrestPoint,
        constructorList, // 使用完整的施工人员列表
        teamNo: _data.teamNo,
      };
      this.$refs.addEdit.init(editData);
    },
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除该施工队伍？")
        .then(() => {
          return deleteConstructTeam(row.pId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传前的处理 */
    beforeUpload(file) {
      const isExcel =
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/vnd.ms-excel";
      if (!isExcel) {
        this.$message.error("只能上传Excel文件!");
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("文件大小不能超过 5MB!");
        return false;
      }
      return true;
    },
    /** 文件上传成功的处理 */
    handleSuccess(response, file) {
      // if (response.code === 200) {
      this.$modal.msgSuccess("导入成功");
      this.getList();
      // } else {
      //   this.$modal.msgError(response.msg || "导入失败");
      // }
    },
    /** 文件上传失败的处理 */
    handleError(error) {
      this.$modal.msgError("导入失败，请重试");
      console.error("上传失败:", error);
    },
  },
};
</script>
<style lang="scss" scoped>
.table {
  height: calc(100% - 150px);
}
::v-deep {
  .el-table {
    height: 100%;
    width: 100%;
    .el-table__body-wrapper {
      width: 100% !important;
      height: calc(100% - 70px) !important; // 表格高度减去表头的高度
      overflow-y: scroll;
    }
  }
}
.text {
  cursor: pointer;
}
.red-text {
  color: red;
  margin-bottom: 5px;
}
</style>
