<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="openDialog('add')">
          <img src="../../../assets/images/detailsicon/icon-bj@2x.png" alt="新增"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          新增
        </el-button>
        <el-button type="primary" size="medium" plain v-if="action === 'fill' || !action || action === 'okay'"
          style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="toggleEditMode"
          :loading="saveLoading">
          <img src="../../../assets/images/detailsicon/icon-bj@2x.png" alt="编辑"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          {{ isEditMode ? '保存' : '编辑' }}
        </el-button>
        <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>
      </div>
    </div>

    <!-- 数据展示表格 -->
    <div class="tagdiv">
      <div class="descriptionsdiv">
        <el-descriptions class="margin-top" :column="5" border>
          <el-descriptions-item v-for="(item, index) in anotherInfo" :key="index" :label="item.zdname">
            <template v-if="isEditMode">
              <el-input v-model="item.zdinfor" size="small" @change="handleFieldChange(item)"
                style="width:7rem;"></el-input>
            </template>
            <template v-else>
              {{ item.zdinfor }}
            </template>
              <el-button v-if="checkRole(['admin', 'common']) && isEditMode" type="text" size="small" @click="handleDeleteField(item)"
                style="margin-left: 1rem;color: #F25353;">删除</el-button>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <!-- 新增表单弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="字段名称">
          <el-input v-model="form.zdname" placeholder="请输入字段名称"></el-input>
        </el-form-item>
        <el-form-item label="字段内容">
          <el-input v-model="form.zdinfor" placeholder="请输入字段内容 "></el-input>
        </el-form-item>
      </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 { checkPermi, checkRole } from "@/utils/permission";
import { addxmqt, deletexmqt } from "@/api/ManageApi";

export default {
  props: {
    anotherInfo: {
      type: Array,
      required: true,
      default: () => []
    },
    action: {
      type: String,
      required: true
    },
    xmId: {
      type: Number,
      default: 0
    }
  },
  created() {  },
  data() {
    return {
      dialogVisible: false, // 控制弹窗显示
      dialogTitle: '', // 弹窗标题
      form: {
        zdname: '',
        zdinfor: ''
      },
      isEditMode: false, // 是否为编辑模式
      saveLoading: false, // 保存加载状态
      editedData: [] // 存储编辑后的数据
    };
  },
  methods: {
    checkPermi,
    checkRole,

    // 打开新增对话框
    openDialog(type) {
      if (type === 'add') {
        this.dialogTitle = '新增信息';
        this.form = {
          zdname: '',
          zdinfor: ''
        };
        this.dialogVisible = true;
      }
    },

    // 切换编辑模式
    toggleEditMode() {
      if (this.isEditMode) {
        // 保存操作
        this.saveChanges();
      } else {
        // 进入编辑模式
        this.isEditMode = true;
        // 创建编辑数据的副本
        this.editedData = JSON.parse(JSON.stringify(this.anotherInfo));
      }
    },

    // 处理字段变化
    handleFieldChange(item) {
      const index = this.editedData.findIndex(i => i.zdname === item.zdname);
      if (index !== -1) {
        this.editedData[index] = { ...item };
      }
    },

    // 保存修改
    saveChanges() {
      this.saveLoading = true;

      try {
        // 准备要发送给父组件的数据
        const updatedData = this.editedData.map(item => ({
          ...item,
        }));

        // 发送给父组件
        this.$emit('update-info', updatedData);

        // 更新 anotherInfo 数据
        this.anotherInfo = updatedData;

        // 退出编辑模式
        this.isEditMode = false;
        this.$message.success('保存成功');
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败: ' + (error.message || '请检查网络连接'));
      } finally {
        this.saveLoading = false;
      }
    },
    /**导出 */
    handleExport() {
      this.download(
        "/gysl/projectOtherInfo/export",
        {
          xmId: this.xmId,
        },
        `其他信息${new Date().getTime()}.xlsx`
      );
    },
    // 删除字段
    async handleDeleteField(item) {
      this.$confirm(`确定要删除字段 "${item.zdname}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除API
          await deletexmqt([item.id]);

          // 如果是编辑模式，直接从editedData中移除
          if (this.isEditMode) {
            this.editedData = this.editedData.filter(i => i.id !== item.id);
          }

          // 从 anotherInfo 中移除对应的数据
          this.anotherInfo = this.anotherInfo.filter(i => i.id !== item.id);

          // 通知父组件更新数据
          this.$emit('delete-info', item.id);
          this.$message.success('删除成功');
        } catch (error) {
          this.$message.error('删除失败: ' + (error.message || '请检查网络连接'));
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 提交新增表单
    async submitForm() {
      if (!this.form.zdname || !this.form.zdinfor) {
        this.$message.warning('请填写完整的字段名称和内容');
        return;
      }

      try {
        // 准备请求数据
        const requestData = {
          xmId: this.xmId, // 使用父组件传递的项目ID
          zdname: this.form.zdname,
          zdinfor: this.form.zdinfor,
          // 其他字段使用默认值或空值
          createBy: "",
          createId: 0,
          createTime: "",
          updateBy: "",
          updateId: 0,
          updateTime: ""
        };

        // 调用API新增数据
        const response = await addxmqt(requestData);
        console.log('新增成功:', response);

        // 将新数据添加到 anotherInfo 数组中
        this.anotherInfo.push({
          id: response.data.id,
          zdname: this.form.zdname,
          zdinfor: this.form.zdinfor
        });

        // 关闭对话框
        this.dialogVisible = false;
        this.$message.success('新增成功');
      } catch (error) {
        this.$message.error('新增失败: ' + (error.message || '请检查网络连接'));
      }
    },

    // 删除数据
    deleteData() {
      this.$confirm('确定要删除这些信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('delete-info');
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</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 {
    height: 2rem;
    width: 8rem;
    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;
  display: flex;
  justify-content: space-between;
}

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

.tagdiv {
  width: 100%;
  padding: 1rem 2rem 1rem 0;
}

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