<template>
  <div class="container">
    <!-- 顶部信息 -->
    <div class="containertop">
      <div class="topleft">
        <img src="../../../assets/images/detailsicon/1.png" alt="">
        <span>月度进展信息</span>
      </div>
      <div class="topright" v-if="action === 'fill' || !action || action === 'okay'">
        <!-- <el-button type="primary" size="medium" plain v-if="checkRole(['admin', 'common'])"
          style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleExport">
          <img src="../../../assets/images/detailsicon/icon-dc@2x.png" alt="导出"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          导出
        </el-button> -->
        <el-button type="primary" size="medium" plain
          style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleAdd">
          <img src="../../../assets/images/detailsicon/icon-xz@2x.png" alt="新增"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          新增
        </el-button>
      </div>
    </div>
    <!-- 内容区 -->
    <div class="content">
      <div class="descriptionsdiv">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="month" label="进度月份">
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <span :style="getStatusColor(scope.row.status)">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="monthDoneAmount" label="当月完成投资" align="center">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isEditing" v-model.number="scope.row.monthDoneAmount"
                style="width: 100%;"></el-input>
              <span v-else>{{ scope.row.monthDoneAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalDoneAmount" label="累计完成投资" align="center">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isEditing" v-model.number="scope.row.totalDoneAmount"
                style="width: 100%;"></el-input>
              <span v-else>{{ scope.row.totalDoneAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="cumulativeArea" label='截止目前累计建成面积(平方米)' align="center">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isEditing" v-model.number="scope.row.cumulativeArea"
                style="width: 100%;"></el-input>
              <span v-else>{{ scope.row.cumulativeArea }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="xmjzxq" label='项目进展详情' align="center">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.xmjzxq" style="width: 100%;"></el-input>
              <span v-else>{{ scope.row.xmjzxq }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isEditing" type="text" icon="el-icon-check"
                @click="handleSave(scope.row)">保存</el-button>
              <el-button v-else type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" style="color: #F25353;"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <div style="visibility: hidden;"></div>
          <el-pagination :current-page="current" :page-sizes="[10, 20, 30, 40]" :page-size="size"
            layout="total, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="新增月度进展" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" label-width="160px" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进度月份" prop="month">
              <el-date-picker v-model="form.month" type="month" placeholder="选择月份" value-format="yyyy-MM"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" style="display: none;">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                <el-option label="未更新" value="未更新"></el-option>
                <el-option label="已更新" value="已更新"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当月完成投资" prop="monthDoneAmount">
              <el-input v-model.number="form.monthDoneAmount" placeholder="请输入金额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="累计完成投资" prop="totalDoneAmount">
              <el-input v-model.number="form.totalDoneAmount" placeholder="请输入金额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="累计建成面积(㎡)" prop="cumulativeArea">
              <el-input v-model="form.cumulativeArea" placeholder="请输入面积"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目进展详情" prop="xmjzxq">
              <el-input v-model="form.xmjzxq" type="textarea" :rows="3" placeholder="请输入详情"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 查看详情信息
import { getMonthInformationPage } from "@/api/ManageApi/index";
//在Apitwo里
import { updateProjectProgress, deletemonth, addmonth } from "@/api/manageApitwo/index";
import { checkPermi, checkRole } from "@/utils/permission";

export default {
  props: {
    action: {
      type: String,
      required: true,
    },
    xmId: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      tableData: [],
      current: 1,
      size: 10,
      total: 0,
      dialogVisible: false, // 控制弹窗显示
      form: {
        month: '', // 进度月份
        status: '未更新', // 状态
        monthDoneAmount: 0, // 当月完成投资
        totalDoneAmount: 0, // 累计完成投资
        cumulativeArea: '', // 截止目前累计建成面积
        xmjzxq: '' // 项目进展详情
      },
      rules: {
        month: [
          { required: true, message: '请选择月份', trigger: 'change' }
        ],
        monthDoneAmount: [
          { required: true, message: '请输入当月完成投资', trigger: 'blur' }
        ],
        totalDoneAmount: [
          { required: true, message: '请输入累计完成投资', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    checkPermi,
    checkRole,
    handleAdd() {
      this.form = {
        month: '',
        status: '未更新',
        monthDoneAmount: 0,
        totalDoneAmount: 0,
        cumulativeArea: '',
        xmjzxq: ''
      };
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const payload = {
            ...this.form,
            xmId: this.xmId, // 来自 props 的项目ID
            projectId: this.xmId, // 如果后端需要projectId也传相同值
            status: this.form.status
          };

          addmonth(payload)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功');
                this.dialogVisible = false;
                this.getMonthInformationPage(); // 刷新列表
              } else {
                this.$message.error(response.msg || '新增失败');
              }
            })
            .catch(error => {
              console.error('新增失败:', error);
              this.$message.error('新增失败，请稍后再试');
            });
        } else {
          this.$message.error('请填写必填项');
          return false;
        }
      });
    },
    /** 导出 */
    handleExport() {
      this.download(
        "/gysl/projectProgress/export",
        {
          xmId: this.xmId
        },
        `月度信息${new Date().getTime()}.xlsx`
      );
    },
    getStatusColor(status) {
      switch (status) {
        case "未更新":
          return "color: #2DD29F;";
        case "已更新":
          return "color: #2B62F1;";
        default:
          return "";
      }
    },
    handleEdit(row) {
      row.originalData = { ...row };
      row.isEditing = true;
    },
    async handleSave(row) {
      try {
        const updateData = {
          id: row.id,
          monthDoneAmount: row.monthDoneAmount,
          totalDoneAmount: row.totalDoneAmount,
          cumulativeArea: row.cumulativeArea,
          xmjzxq: row.xmjzxq,
        };
        const response = await updateProjectProgress(updateData);
        if (response.code === 200) {
          this.$message({
            type: "success",
            message: "更新成功!",
          });
          row.isEditing = false;
          row.status = "已更新";

          // this.getMonthInformationPage();
        } else {
          this.$message.error(response.msg || "更新失败");
          Object.assign(row, row.originalData);
        }
      } catch (error) {
        console.error("更新失败:", error);
        this.$message.error("更新失败");
        Object.assign(row, row.originalData);
      } finally {
        delete row.originalData;
      }
    },
    handleDelete(row) {
      this.$confirm("确定要删除此条月度进展记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            // 调用删除接口
            const response = await deletemonth([row.id]);

            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });

              // 从本地数据中移除已删除项
              const index = this.tableData.findIndex(item => item.id === row.id);
              if (index !== -1) {
                this.tableData.splice(index, 1);
              }

              // 更新总数
              this.total -= 1;

              // 如果当前页没有数据且不是第一页，则返回上一页
              if (this.tableData.length === 0 && this.current > 1) {
                this.current -= 1;
                // this.getMonthInformationPage();
              }
            } else {
              this.$message.error(response.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请稍后重试");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getMonthInformationPage() {
      try {
        const response = await getMonthInformationPage({ xmId: this.xmId });

        if (Array.isArray(response.data.records) && response.data.records.length > 0) {
          this.tableData = response.data.records;
          this.total = response.data.total || 0;
        } else {
          // 空数组保留为空数组
          this.tableData = [];
          this.total = 0;
        }
      } catch (error) {
        console.error("获取月度进展信息失败:", error);
        this.$message.error("获取月度进展信息失败");
      }
    },
  },
  created() {
    this.getMonthInformationPage();
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: #FFFFFF;
  box-shadow: 0rem 0.13rem 0.63rem 0rem rgba(177, 177, 177, 0.1);
  border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
}


.content {
  padding: 1rem;
  display: flex;
}

.containertop {
  height: auto;
  display: flex;
  justify-content: space-between;
  padding: .5rem;
  border-bottom: 1px solid #E5E5E5;
}

.topleft {
  width: 8rem;
  height: 2rem;
  display: flex;
  gap: 0.4rem;
  align-items: center;
}

.topleft img {
  width: 0.81rem;
  height: 0.81rem;
}

.topleft span {
  width: auto;
  height: 1rem;
  font-family: aliregular;
  font-weight: 500;
  font-size: 1rem;
  color: #3D424C;
  line-height: 1rem;
  text-align: right;
  font-style: normal;
  text-transform: none;
}

.picturediv {
  width: 18.31rem;
  height: 25.31rem;
  background-color: lightblue;
}

.descriptionsdiv {
  width: 100%;
  margin-left: 1rem;
  height: auto;
}

.two-row-item {
  height: 20rem;
}

.block {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 1rem;
}

.no-data {
  text-align: center;
  padding: 2rem;
  color: #999;
}
</style>