<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">
              <el-table-column label="序号" width="50">
                <template slot-scope="scope">
                  {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="企业名称">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.name"></el-input>
                  <span v-else style="color: #2B62F1;">{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="code" label="统一社会信用代码" width="200">
              </el-table-column>
              <el-table-column prop="sshy" label="所属行业">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.sshy"></el-input>
                  <span v-else>{{ scope.row.sshy }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zjjg" label='租金价格'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.zjjg"></el-input>
                  <span v-else>{{ scope.row.zjjg }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zcdz" label='注册地址'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.zcdz"></el-input>
                  <span v-else>{{ scope.row.zcdz }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="clrq" label='成立日期'>
                <template slot-scope="scope">
                  <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.clrq" type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>
                  <span v-else>{{ scope.row.clrq ? new Date(scope.row.clrq).toLocaleDateString('en-CA') : '' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zczb" label='注册资本'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.zczb"></el-input>
                  <span v-else>{{ scope.row.zczb }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="fddbr" label='法定代表人'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.fddbr"></el-input>
                  <span v-else>{{ scope.row.fddbr }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="qylx" label='企业类型'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.qylx"></el-input>
                  <span v-else>{{ scope.row.qylx }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="jyfw" label='经营范围'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.jyfw"></el-input>
                  <span v-else>{{ scope.row.jyfw }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="zzjgdm" label='组织机构代码'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.zzjgdm"></el-input>
                  <span v-else>{{ scope.row.zzjgdm }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="swdjhm" label='税务登记号码'>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.isEditing" v-model.number="scope.row.swdjhm"></el-input>
                  <span v-else>{{ scope.row.swdjhm }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isEditing" size="medium" type="text" icon="el-icon-check"
                    @click="saveRow(scope.row)">保存</el-button>
                  <el-button v-else size="medium" type="text" icon="el-icon-edit"
                    @click="editRow(scope.row)"></el-button>
                  <el-button size="medium" 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) { }
    }
  },
  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 => {
        this.tableData = response.data.records.map(item => ({
          ...item,
          isEditing: false
        }));
        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 => {
        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(() => {
          this.form.rzqys = this.tableData.length;
          this.save();
        });
      }).catch(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: .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;
}

.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: right;
  margin-top: 1rem;
}
</style>