<template>
  <div>
    <el-form :inline="true" :model="requestParam" :rules="dataRule" ref="form">
      <el-form-item prop="enterpriseName">
        <el-input v-model="requestParam.enterpriseName" placeholder="请输入企业名称" maxlength="10" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchHandle()">查询</el-button>
        <el-button type="primary" @click="dialogFormVisible = true">新增</el-button>
        <el-button type="danger" @click="batchDeleteHandle()">批量删除</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="enterprise" :header-cell-style="{ background: '#f5f7fa' }" border v-loading="loading" @selection-change="selectionChangeHandle">
      <el-table-column type="selection" header-align="center" align="center" width="50" />
      <el-table-column type="index" header-align="center" align="center" width="100" label="企业编号">
        <template #default="scope">
          <span>{{ (pageIndex - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="enterprise_name" header-align="center" align="center" label="企业名称" min-width="180" />
      <el-table-column prop="enterprise_car_count" header-align="center" align="center" label="企业车辆数量" min-width="180" />
      <el-table-column prop="enterprise_fence_count" header-align="center" align="center" label="企业电子围栏数量" min-width="180" />
      <el-table-column header-align="center" align="center" width="150" label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row.enterprise_id)">修改</el-button>
          <el-button type="text" @click="deleteHandle(scope.row.enterprise_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50]" :page-size="pageSize" :total="totalCount" layout="total, sizes, prev, pager, next, jumper"></el-pagination>

    <!-- 新增/修改弹窗 -->
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible" ref="dialog">
      <el-form :model="operations" ref="formRef" :rules="dialogDataRule" label-width="130px">

        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="operations.enterpriseName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="企业车辆数量" prop="enterpriseCarCount">
          <el-input-number v-model="operations.enterpriseCarCount" @change="handleChange" :max="52"></el-input-number>
        </el-form-item>

        <el-form-item label="企业电子围栏数量" prop="enterpriseFenceCount">
          <el-input-number v-model="operations.enterpriseFenceCount" @change="handleChange" :max="99"></el-input-number>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import { enterpriseList, insert, updateEnterEnterprise, deleteByIds, searchById } from '@/api/saas/saas';

export default {
  data() {
    return {
      loading:false,
      requestParam: {
        enterpriseName: '',
        page: 1,
        length: 10
      },
      enterprise: [],
      selections: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      dataRule: {
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z\u4e00-\u9fa5]{1,10}$/, message: '企业名称格式不正确' }
        ],
      },
      dialogFormVisible: false,
      formLabelWidth: '130px',
      operations: {
        enterpriseId: '',
        enterpriseName: '',
        enterpriseCarCount: '',
        enterpriseFenceCount: ''
      },
      dialogDataRule: {
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z\u4e00-\u9fa5]{1,10}$/, message: '企业名称格式不正确' }
        ],
        enterpriseCarCount: [
          { required: true, message: '请输入企业车辆数量', trigger: 'blur' }
        ],
        enterpriseFenceCount: [
          { required: true, message: '请输入企业电子围栏数量', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    enterpriseList() {
      enterpriseList({ ...this.requestParam, page: this.pageIndex, length: this.pageSize }).then(res => {
        this.enterprise = res.data.list;
        this.totalCount = res.data.totalCount;
      });
    },
    searchHandle() {
      this.pageIndex = 1;
      this.enterpriseList();
    },

    deleteHandle(enterprise_id) {
      this.$confirm('确认删除该企业吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByIds({ ids: [enterprise_id] }).then(() => {
          console.log('删除成功');
          this.$message.success('删除成功');
          this.enterpriseList();
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请重试');
        });
      });
    },
    batchDeleteHandle() {
      const selectedIds = this.selections.map(item => item.enterprise_id); // 确保这里使用的是正确的属性名，如 enterprise_id
      if (selectedIds.length === 0) {
        this.$message.warning('请选择要删除的企业');
        return;
      }

      this.$confirm('确认批量删除这些企业吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByIds({ ids: selectedIds }).then(() => { // 直接传递 selectedIds 数组
          console.log('删除成功');
          this.$message.success('删除成功');
          this.enterpriseList();
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请重试');
        });
      });
    },
    selectionChangeHandle(val) {
      this.selections = val;
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.enterpriseList();
    },
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.enterpriseList();
    },
    handleEdit(enterprise_id) {
      searchById(enterprise_id).then(res => {
        if (res.code === 200) { // 假设成功状态码为200
          this.operations.enterpriseId = res.data.enterprise_id;
          this.operations.enterpriseName = res.data.enterprise_name;
          this.operations.enterpriseCarCount = res.data.enterprise_car_count;
          this.operations.enterpriseFenceCount = res.data.enterprise_fence_count;
          // this.operations = res.data; // 这里假设res.data直接就是企业信息对象
          console.log('res.data:', res.data);
          this.dialogFormVisible = true;
        } else {
          this.$message.error(res.message); // 显示错误信息
        }
      }).catch(error => {
        console.error('调用searchById失败:', error);
        this.$message.error('服务器错误，请稍后再试');
      });
    },
    submitDialog() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.operations.enterpriseId) {
            // 修改企业信息
            updateEnterEnterprise(this.operations).then(() => {
              this.$message.success('修改成功');
              this.dialogFormVisible = false;
              this.enterpriseList();
            });
          } else {
            // 新增企业信息
            insert(this.operations).then(() => {
              this.$message.success('新增成功');
              this.dialogFormVisible = false;
              this.enterpriseList();
            });
          }
        }
      });
    },
    handleChange(value) {
      console.log(value);
    }
  },
  created() {
    this.enterpriseList();
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {}
};
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>
