<template>
  <div class="divBox">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="项目名称">
        <el-input v-model="dataForm.projectName" placeholder="请输入项目名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="物业服务公司">
        <el-input v-model="dataForm.propertyCompany" placeholder="请输入物业服务公司" clearable></el-input>
      </el-form-item>
      <el-form-item label="项目状态">
        <el-select v-model="dataForm.status" placeholder="请选择项目状态" clearable>
          <el-option
            v-for="dict in dict.type.project_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
        <el-button v-hasPermi="['autogencode:pmproject:save']" type="primary" @click="addOrUpdateHandle()">新增数据</el-button>
        <el-button v-hasPermi="['autogencode:pmproject:delete']" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        <el-button type="success" @click="handleImport">导入</el-button>
        <el-button type="info" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="projectName"
        header-align="center"
        align="center"
        label="项目名称">
      </el-table-column>
      <el-table-column
        prop="address"
        header-align="center"
        align="center"
        label="项目地址">
      </el-table-column>
      <el-table-column
        prop="jd"
        header-align="center"
        align="center"
        label="经度">
      </el-table-column>
      <el-table-column
        prop="wd"
        header-align="center"
        align="center"
        label="纬度">
      </el-table-column>
      <el-table-column
        prop="buildingArea"
        header-align="center"
        align="center"
        label="总建筑面积">
      </el-table-column>
      <el-table-column
        prop="floorAreaRate"
        header-align="center"
        align="center"
        label="容积率">
      </el-table-column>
      <el-table-column
        prop="greenRate"
        header-align="center"
        align="center"
        label="绿化率">
      </el-table-column>
      <el-table-column
        prop="propertyCompany"
        header-align="center"
        align="center"
        label="物业服务公司">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="项目状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.project_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ '修改' }}</el-button>
          <el-button v-hasPermi="['autogencode:pmproject:delete']" type="text" size="small" @click="deleteHandle(scope.row.id)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 表单弹窗, 新增数据和修改数据 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!-- 导入弹窗 -->
    <el-dialog title="导入项目数据" :visible.sync="importDialogVisible" width="400px">
      <div style="margin-bottom: 10px;">
        <el-link type="primary" @click="downloadTemplate">下载导入模板</el-link>
      </div>
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls"
        action="#"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImportSubmit" :loading="importLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AddOrUpdate from './pmproject-add-and-update'
  import * as api from '@/api/pmproject.js'

  export default {
    dicts: ['project_status','building_type','property_type','house_status'],
    data () {
      return {
        dataForm: {
          projectName: '',
          address: '',
          jd: '',
          wd: '',
          buildingArea: '',
          floorAreaRate: '',
          greenRate: '',
          propertyCompany: '',
          status: '',
          remark: '',
        },

        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        importDialogVisible: false,
        importFile: null,
        importLoading: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataList()
    },
    mounted() {
      // 确保页面加载时自动查询
      this.getDataList()
    },
    methods: {
      // 重置表单
      resetForm() {
        this.dataForm = {
          projectName: '',
          address: '',
          jd: '',
          wd: '',
          buildingArea: '',
          floorAreaRate: '',
          greenRate: '',
          propertyCompany: '',
          status: '',
          remark: '',
        }
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        // 根据后端PmProjectController和PageParamRequest的期望格式构建参数
        const params = {
          page: this.pageIndex,
          limit: this.pageSize
        }

        // 将查询条件添加到参数中
        if (this.dataForm.projectName) params.projectName = this.dataForm.projectName;
        if (this.dataForm.address) params.address = this.dataForm.address;
        if (this.dataForm.jd) params.jd = this.dataForm.jd;
        if (this.dataForm.wd) params.wd = this.dataForm.wd;
        if (this.dataForm.buildingArea) params.buildingArea = this.dataForm.buildingArea;
        if (this.dataForm.floorAreaRate) params.floorAreaRate = this.dataForm.floorAreaRate;
        if (this.dataForm.greenRate) params.greenRate = this.dataForm.greenRate;
        if (this.dataForm.propertyCompany) params.propertyCompany = this.dataForm.propertyCompany;
        if (this.dataForm.status) params.status = this.dataForm.status;
        if (this.dataForm.remark) params.remark = this.dataForm.remark;

        api.pmprojectListApi(params).then(res => {
          this.dataListLoading = false
          this.dataList = res.list || [];
          this.totalPage = res.total;
        }).catch(e => {
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除处理（支持单个删除和批量删除）
      deleteHandle (id) {
        let ids = []
        let idText = ''

        // 如果传入了单个id参数，则为单个删除
        if (id) {
          ids = [id]
          idText = id
        } else {
          // 否则为批量删除
          ids = this.dataListSelections.map(item => {
            return item.id
          })
          idText = ids.join(',')
        }

        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用批量删除API
          api.pmprojectDeleteApi(ids).then(res => {
            this.$message.success('删除成功')
            this.getDataList()
          })
        })
      },
      // 打开导入弹窗
      handleImport() {
        this.importDialogVisible = true
        this.importFile = null
      },
      // 文件选择变化
      handleFileChange(file) {
        this.importFile = file.raw
      },
      // 提交导入
      handleImportSubmit() {
        if (!this.importFile) {
          this.$message.warning('请选择要导入的文件')
          return
        }
        this.importLoading = true
        api.pmprojectImportApi(this.importFile).then(res => {
          this.$message.success('导入成功')
          this.importDialogVisible = false
          this.getDataList()
        }).catch(err => {
          this.$message.error('导入失败：' + (err.message || '未知错误'))
        }).finally(() => {
          this.importLoading = false
        })
      },
      // 下载导入模板
      downloadTemplate() {
        api.pmprojectDownloadTemplateApi().then(res => {
          const url = window.URL.createObjectURL(new Blob([res]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '项目导入模板.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }).catch(err => {
          this.$message.error('下载模板失败：' + (err.message || '未知错误'))
        })
      },
      // 导出项目数据
      handleExport() {
        this.download('autogencode/pmproject/export', {
          ...this.queryParams
        }, `房产管理报表_${new Date().getTime()}.xlsx`)
      }
    }
  }
</script>
<!---->
