<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
          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>
        <el-button type="primary" size="medium" plain v-if="checkRole(['admin', 'common','gov'])"
          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>
      </div>
    </div>
    <!-- 内容区 -->
    <div class="content">
      <div class="custom-table-container">
        <div class="custom-table-header">
          <div class="table-cell">进度月份</div>
          <div class="table-cell">状态</div>
          <div class="table-cell">当月完成投资</div>
          <div class="table-cell">累计完成投资</div>
          <div
            style="width: auto; text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding: 0 0.5rem;">
            截止目前累计建成面积（平方米）</div>
          <div class="table-cell">项目进展详情</div>
          <div class="table-cell">操作</div>
        </div>

        <div class="custom-table-body">
          <div v-if="tableData.length === 0" class="no-data-row">
            暂无数据
          </div>
          <div v-else v-for="item in tableData" :key="item.id" class="custom-table-row">
            <!-- 进度月份 -->
            <div class="table-cell">
              <template v-if="item.isEditing">
                <el-date-picker v-model="item.month" type="month" value-format="yyyy-MM"
                  style="width: 100%;"></el-date-picker>
              </template>
              <template v-else>
                {{ item.month }}
              </template>
            </div>

            <!-- 状态（始终不编辑） -->
            <div class="table-cell">
              <span :style="getStatusColor(item.status)">{{ item.status }}</span>
            </div>

            <!-- 当月完成投资 -->
            <div class="table-cell">
              <template v-if="item.isEditing">
                <el-input-number v-model.number="item.monthDoneAmount" :controls="false" style="width: 100%;" />
              </template>
              <template v-else>
                {{ item.monthDoneAmount }}
              </template>
            </div>

            <!-- 累计完成投资 -->
            <div class="table-cell">
              <template v-if="item.isEditing">
                <el-input-number v-model.number="item.totalDoneAmount" :controls="false" style="width: 100%;" />
              </template>
              <template v-else>
                {{ item.totalDoneAmount }}
              </template>
            </div>

            <!-- 累计建成面积 -->
            <div class="table-cell">
              <template v-if="item.isEditing">
                <el-input v-model="item.jzmqjc" style="width: 100%;" />
              </template>
              <template v-else>
                {{ item.jzmqjc }}
              </template>
            </div>

            <!-- 项目进展详情 -->
            <div class="table-cell">
              <template v-if="item.isEditing">
                <el-input v-model="item.xmjzxq" style="width: 100%;" />
              </template>
              <template v-else>
                {{ formattedXmjzxq(item.xmjzxq) }}
              </template>
            </div>

            <!-- 操作列 -->
            <div class="table-cell">
              <el-button v-if="!item.isEditing" type="text" icon="el-icon-edit" @click="handleEdit(item)">编辑</el-button>
              <el-button v-else type="text" icon="el-icon-check" @click="handleSave(item)">保存</el-button>
              <el-button type="text" icon="el-icon-delete" style="color: #F25353;"
                @click="handleDelete(item)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="新增月度进展" :visible.sync="dialogVisible" width="55%">
      <el-form :model="form" :rules="rules" label-width="240px" 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="jzmqjc">
              <el-input v-model="form.jzmqjc" 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 class="yuedu">
      <yuedutouzi :xmId="xmId" />
    </div> -->
  </div>
</template>

<script>
// 查看详情信息
import { getMonthInformationPage } from "@/api/ManageApi/index";
// 在Apitwo里
import { updateProjectProgress, deletemonth, addmonth } from "@/api/manageApitwo/index";
import { checkPermi, checkRole } from "@/utils/permission";
//  投资
import yuedutouzi from '@/views/components/analysis/yuedutouzi.vue'


export default {
  components: { yuedutouzi },
  props: {
    action: {
      type: String,
      required: true
    },
    xmId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      tableData: [], // 表格数据
      dialogVisible: false, // 控制弹窗显示
      form: {
        month: "", // 进度月份
        status: "已更新", // 状态固定为“已更新”
        monthDoneAmount: "", // 当月完成投资
        totalDoneAmount: "", // 累计完成投资
        jzmqjc: "", // 截止目前累计建成面积
        xmjzxq: "" // 项目进展详情
      },
      rules: {
        month: [
          { required: true, message: "请选择月份", trigger: "change" }
        ],
        monthDoneAmount: [
          { required: true, message: "请输入当月完成投资", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === '' || value === null) {
                callback(new Error("请输入数字"));
              } else if (isNaN(value)) {
                callback(new Error("只能输入数字"));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        totalDoneAmount: [
          { required: true, message: "请输入累计完成投资", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === '' || value === null) {
                callback(new Error("请输入数字"));
              } else if (isNaN(value)) {
                callback(new Error("只能输入数字"));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  computed: {
    formattedXmjzxq() {
      return (text) => {
        return text === 'etry' ? '' : text;
      };
    }
  },
  methods: {
    checkPermi,
    checkRole,

    // 新增按钮点击
    handleAdd() {
      this.form = {
        month: "",
        status: "已更新",
        monthDoneAmount: "",
        totalDoneAmount: "",
        jzmqjc: "",
        xmjzxq: ""
      };
      this.dialogVisible = true;
    },

    // 提交新增表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const payload = {
            ...this.form,
            xmId: this.xmId
          };

          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`
      );
    },

    // 获取月度进展信息
    async getMonthInformationPage() {
      try {
        const response = await getMonthInformationPage({ xmId: this.xmId });

        if (Array.isArray(response.data) && response.data.length > 0) {
          // 接口返回的数据处理：统一 status 为 “已更新”
          this.tableData = response.data.map(item => ({
            ...item,
            status: '已更新',
            monthDoneAmount: item.monthDoneAmount ?? 0,
            totalDoneAmount: item.totalDoneAmount ?? 0,
            jzmqjc: item.jzmqjc ?? '',
            xmjzxq: item.xmjzxq ?? ''
          }));
        } else {
          this.tableData = [];
        }
      } catch (error) {
        console.error("获取月度进展信息失败:", error);
        this.$message.error("获取月度进展信息失败");
      }
    },

    // 编辑某一行
    handleEdit(row) {
      // 设置当前行为可编辑状态
      this.tableData.forEach(item => {
        this.$set(item, 'isEditing', item.id === row.id);
      });
    },

    // 保存编辑行
    async handleSave(row) {
      try {
        const updateData = {
          id: row.id,
          month: row.month,
          monthDoneAmount: row.monthDoneAmount,
          totalDoneAmount: row.totalDoneAmount,
          jzmqjc: row.jzmqjc,
          xmjzxq: row.xmjzxq
        };

        const response = await updateProjectProgress(updateData);

        if (response.code === 200) {
          this.$message.success("更新成功");
          this.$set(row, 'isEditing', false);
        } else {
          this.$message.error(response.msg || "更新失败");
        }
      } catch (error) {
        console.error("更新失败:", error);
        this.$message.error("更新失败");
      }
    },

    // 删除某条记录
    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);
              }
            } else {
              this.$message.error(response.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请稍后重试");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 状态颜色
    getStatusColor(status) {
      switch (status) {
        case "未更新":
          return "color: #23B88E;";
        case "已更新":
          return "color: #23B88E;";
        default:
          return "";
      }
    }
  },
  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;
}

.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 {
  font-family: aliregular;
  font-weight: 500;
  font-size: 1rem;
  color: #3D424C;
  line-height: 1rem;
}

.content {
  padding: 1rem 1rem 1rem 2rem;
}

/* 自定义表格样式 */
.custom-table-container {
  width: 100%;
  border: 1px solid #EBEEF5;
  overflow: hidden;
}

.custom-table-header {
  display: flex;
  background-color: #f5f7fa;
  /* font-weight: bold; */
  font-size: 0.88rem;
  padding: 0.5rem 0;
}

.custom-table-body {
  max-height: 14rem;
  overflow-y: auto;
  font-size: 0.88rem;
  padding-right: 0.5rem;
}

.custom-table-row {
  display: flex;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid #EBEEF5;
}

.table-cell {
  flex: 1;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 0.5rem;
}

.no-data-row {
  text-align: center;
  padding: 1rem 0;
  color: #999;
  font-size: 0.875rem;
}
.yuedu{
  width: 100%;
  height: 100%;
  padding: 0rem 1rem 1rem 2rem;
}
</style>