<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 v-if="!isEditing" type="primary" size="medium" plain
          style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="edit">
          <img src="../../../assets/images/detailsicon/icon-bj@2x.png" alt="编辑"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          编辑
        </el-button>
        <el-button v-else type="primary" size="medium" plain
          style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="save">
          <img src="../../../assets/images/detailsicon/icon-bj@2x.png" alt="保存"
            style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
          保存
        </el-button>
      </div>
    </div>
    <!-- 内容区 -->
    <div class="content">
      <div class="descriptionsdiv">
        <el-descriptions class="margin-top" :column="4" border>
          <el-descriptions-item label="入驻企业数（家）">
            <span>{{ tableData.length }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="入驻企业行业类型">
            <el-input v-if="isEditing" v-model="form.rzqyhylx" style="width: 100%;"></el-input>
            <span v-else>{{ form.rzqyhylx || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="人员数量（人）">
            <el-input v-if="isEditing" v-model.number="form.rysl" style="width: 100%;"></el-input>
            <span v-else>{{ form.rysl || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="入住率（%）">
            <el-input v-if="isEditing" v-model.number="form.rzl" style="width: 100%;"></el-input>
            <span v-else>{{ form.rzl || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="已出租（售）面积（平方米）">
            <el-input v-if="isEditing" v-model.number="form.yczmj" style="width: 100%;"></el-input>
            <span v-else>{{ form.yczmj || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="空置出租（售）面积（平方米）">
            <el-input v-if="isEditing" v-model.number="form.kzczmj" style="width: 100%;"></el-input>
            <span v-else>{{ form.kzczmj || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工业厂房平均租金（元/平方米*月）">
            <el-input v-if="isEditing" v-model.number="form.gycfpjzj" style="width: 100%;"></el-input>
            <span v-else>{{ form.gycfpjzj || "" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工业厂房平均物业费(元/平方米*月)">
            <el-input v-if="isEditing" v-model.number="form.gycfpjwyf" style="width: 100%;"></el-input>
            <span v-else>{{ form.gycfpjwyf || "" }}</span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="btnarea" v-if="action === 'fill' || !action || action === 'okay'">
          <el-button type="primary" size="mini" @click="handleImport">
            批量导入
          </el-button>
        </div>
        <!-- 表格显示区 -->
        <div class="contenttwo">
          <div class="descriptionsdiv">
            <el-table :data="tableData" style="width: 98%">
              <el-table-column label="序号" width="200">
                <template slot-scope="scope">
                  {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="企业名称" width="300">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.name" style="width: 100%;"></el-input>
                  <span v-else style="color: #2B62F1;">{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="code" label="统一社会信用代码" width="300">
              </el-table-column>
              <el-table-column prop="sshy" label="所属行业" width="300">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.sshy" style="width: 100%;"></el-input>
                  <span v-else>{{ scope.row.sshy }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zjjg" label='租金价格' width="250">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.zjjg" style="width: 100%;"></el-input>
                  <span v-else>{{ scope.row.zjjg }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isEditing" size="mini" type="text" icon="el-icon-check"
                    @click="saveRow(scope.row)">保存</el-button>
                  <el-button v-else size="mini" type="text" icon="el-icon-edit"
                    @click="editRow(scope.row)">编辑</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F25353;"
                    @click="deleteRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="block">
              <el-pagination :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]"
                :page-size="pagination.pageSize" layout="total, prev, pager, next, jumper" :total="pagination.total"
                @current-change="handleCurrentChange" @size-change="handleSizeChange">
              </el-pagination>
            </div>
          </div>
        </div>
        <!-- 导入弹窗 -->
        <el-dialog title="数据导入" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
          <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :auto-upload="false" :data="upload.data" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button @click="upload.open = false">取 消</el-button>
            <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">
              确 定
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { download } from "@/utils/request";
import { getqyBasicInformationPage, updateqyBasicInformation, deleteqyBasicInformation } from "@/api/ManageApi/index";

export default {
  props: {
    qyrzInfo: {
      type: Object,
      required: true,
      default: () => ({
        rzqys: 0,
        rzqyhylx: '',
        rysl: 0,
        rzl: 0,
        yczmj: 0,
        kzczmj: 0,
        gycfpjzj: 0,
        gycfpjwyf: 0
      })
    },
    action: {
      type: String,
      required: true
    },
    xmId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      isEditing: false,
      form: {
        ...this.qyrzInfo
      },
      tableData: [], // 初始化为空数组
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      upload: {
        open: false,
        isUploading: false,
        updateSupport: 0,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        url: process.env.VUE_APP_BASE_API + "/gysl/enterprise/importEnterprise",
        data: {
          xmId: this.xmId
        }
      }
    };
  },
  created() {
    this.fetchTableData(); // 仅加载数据，不主动保存
  },
  methods: {
    async fetchTableData() {
      const params = { xmId: this.xmId, current: 1, size: 10 };
      try {
        const response = await getqyBasicInformationPage(params);
        this.tableData = response.data.records.map(item => ({ ...item, isEditing: false }));
        this.pagination.total = response.data.total;

        // 数据加载完成后，更新 form.rzqys 并通知父组件
        this.form.rzqys = this.tableData.length;
        this.$emit('update-data', { ...this.form }); // 确保传递完整数据
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    }
  },
  watch: {
    qyrzInfo: {
      handler(newVal) {
        // 仅合并父组件传入的字段，保留子组件自己的状态（如 tableData 生成的 rzqys）
        this.form = {
          ...newVal,
          rzqys: this.tableData.length // 优先使用本地计算的 rzqys
        };
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 获取表格数据
    fetchTableData() {
      const params = {
        xmId: this.xmId,
        current: this.pagination.currentPage,
        size: this.pagination.pageSize
      };
      return getqyBasicInformationPage(params).then(response => {
        // console.log('Fetched Data:', response.data.records);
        this.tableData = response.data.records.map(item => ({
          ...item,
          isEditing: false
        }));
        // console.log('Table Data:', this.tableData);
        this.pagination.total = response.data.total;
      }).catch();
    },

    // 编辑/保存方法
    edit() {
      this.isEditing = true;
    },
    save() {
      const formData = {
        ...this.form,
        rzqys: this.tableData.length,
        rysl: Number(this.form.rysl),
        rzl: Number(this.form.rzl),
        yczmj: Number(this.form.yczmj),
        kzczmj: Number(this.form.kzczmj),
        gycfpjzj: Number(this.form.gycfpjzj),
        gycfpjwyf: Number(this.form.gycfpjwyf)
      };
      this.$emit('update-data', formData);
      this.isEditing = false;
    },

    // 表格编辑相关方法
    editRow(row) {
      row.isEditing = true;
    },
    saveRow(row) {
      row.isEditing = false;
      updateqyBasicInformation(row).then(response => {
        this.$modal.msgSuccess('保存成功');
      }).catch(error => {
        console.error('保存失败:', error);
        this.$modal.msgError('保存失败');
      });
    },
    deleteRow(index) {
      const id = this.tableData[index].id;
      deleteqyBasicInformation([id]).then(response => {
        this.$modal.msgSuccess('删除成功');
        this.tableData.splice(index, 1);
        // 重新获取表格数据以确保分页正确
        this.fetchTableData().then(() => {
          // 更新 form 数据
          this.form.rzqys = this.tableData.length;
          // 调用 save 方法发送最新的数据
          this.save();
        });
      }).catch(error => {
        console.error('删除失败:', error);
        this.$modal.msgError('删除失败');
      });
    },

    // 导入相关方法
    handleImport() {
      this.upload.open = true;
    },
    //模板下载
    importTemplate() {
      download(
        "/gysl/enterprise/importTemplate",
        {},
        `企业入驻模板_${new Date().getTime()}.xlsx`
      );
    },

    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response) {
      this.upload.isUploading = false;
      this.upload.open = false;
      this.$refs.upload.clearFiles();

      if (response.code === 200) {
        this.$modal.msgSuccess(response.msg);
        // 重新获取表格数据
        this.fetchTableData().then(() => {
          // 更新 form 数据
          this.form.rzqys = this.tableData.length;
          // 调用 save 方法发送最新的数据
          this.save();
        });
      } else {
        this.$modal.msgError(response.msg || "导入失败");
      }
    },
    submitFileForm() {
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.$modal.msgWarning("请先选择文件");
        return;
      }
      // 将 xmId 添加到请求参数中
      const formData = new FormData();
      formData.append('file', this.$refs.upload.uploadFiles[0].raw);
      formData.append('xmId', this.upload.data.xmId);

      this.$refs.upload.submit(formData);
    },

    // 分页处理
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchTableData();
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchTableData();
    }
  }
};
</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: .7rem 0;
  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: 0.88rem;
  font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
  font-weight: 500;
  font-size: 0.88rem;
  color: #3D424C;
  line-height: 0.88rem;
  text-align: right;
  font-style: normal;
  text-transform: none;
}

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

.contenttwo {
  margin-top: 1rem;
  margin-left: -1rem;
}

.btnarea {
  margin-top: 1rem;
}

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