<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="业主名称" prop="proprietorName">
        <el-input
          v-model="queryParams.proprietorName"
          placeholder="请输入业主名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业主电话" prop="proprietorPhone">
        <el-input
          v-model="queryParams.proprietorPhone"
          placeholder="请输入业主电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业主户号" prop="room">
        <el-input
          v-model="queryParams.room"
          placeholder="请输入业主户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登记车牌" prop="plateNumber">
        <el-input
          v-model="queryParams.plateNumber"
          placeholder="请输入登记车牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车型" prop="vehicleModel">
        <el-input
          v-model="queryParams.vehicleModel"
          placeholder="请输入车型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车主电话" prop="carportPhone">
        <el-input
          v-model="queryParams.carportPhone"
          placeholder="请输入车主电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位号" prop="carportNumber">
        <el-input
          v-model="queryParams.carportNumber"
          placeholder="请输入车位号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择车位类型" clearable>
          <el-option
            v-for="dict in dict.type.wx_carport_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:carport:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:carport:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:carport:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:carport:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['business:carport:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="carportId" v-if="true"/>-->
<!--      <el-table-column label="业主ID" align="center" prop="proprietorId" />-->
      <el-table-column label="业主名称" align="center" prop="proprietorName" />
      <el-table-column label="业主电话" align="center" prop="proprietorPhone" />
      <el-table-column label="业主户号" align="center" prop="room" />
      <el-table-column label="登记车牌" align="center" prop="plateNumber" />
      <el-table-column label="车型" align="center" prop="vehicleModel" />
      <el-table-column label="车主电话" align="center" prop="carportPhone" />
      <el-table-column label="车位号" align="center" prop="carportNumber" />
      <el-table-column label="月费" align="center" prop="monthMoney" />
      <el-table-column label="缴费日期" align="center" prop="startTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期日期" align="center" prop="endTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车位类型" align="center" prop="type" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wx_carport_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:carport:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:carport:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业主车位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="小区业主" prop="proprietorId">
              <el-select v-model="form.proprietorId" @change="proprietorIdChange" filterable style="width: 100%" placeholder="请选择小区业主" clearable>
                <el-option v-for="item in proprietorLedgerList" :key="item.proprietorId" :value="item.proprietorId" :label="`${item.communityName} | ${item.room} | ${item.name} | ${item.phone}`" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="小区" prop="communityName">
              <el-input v-model="form.communityName" disabled placeholder="请输入小区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主名称" prop="proprietorName">
              <el-input v-model="form.proprietorName" disabled placeholder="请输入业主名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业主电话" prop="proprietorPhone">
              <el-input v-model="form.proprietorPhone" disabled placeholder="请输入业主电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主户号" prop="room">
              <el-input v-model="form.room" disabled placeholder="请输入业主户号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="登记车牌" prop="plateNumber">
              <el-input v-model="form.plateNumber" placeholder="请输入登记车牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车主电话" prop="carportPhone">
              <el-input v-model="form.carportPhone" placeholder="请输入车主电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车位号" prop="carportNumber">
              <el-input v-model="form.carportNumber" placeholder="请输入车位号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车位类型" prop="type">
              <el-select v-model="form.type" style="width: 100%" placeholder="请选择车位类型">
                <el-option
                  v-for="dict in dict.type.wx_carport_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="月费" prop="monthMoney">
              <el-input-number v-model="form.monthMoney" :min="0" style="width: 100%" placeholder="请输入月费" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车型" prop="vehicleModel">
              <el-input v-model="form.vehicleModel" placeholder="请输入车型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="缴费日期" prop="startTime">
              <el-date-picker clearable
                              v-model="form.startTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择缴费日期"
                              style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期日期" prop="endTime">
              <el-date-picker clearable
                              v-model="form.endTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择到期日期"
                              style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-select v-model="upload.communityId" style="width: 100%" placeholder="请选择小区">
            <el-option v-for="item in communityList" :key="item.communityId" :value="item.communityId" :label="item.communityName" />
          </el-select>
        </el-col>
      </el-row>
      <el-divider />
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&communityId=' + upload.communityId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        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 type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCarport, getCarport, delCarport, addCarport, updateCarport } from "@/api/business/carport";
import {getToken} from "@/utils/auth";
import {listCommunityAll} from "@/api/business/community";
import {listProprietorLedgerAll} from "@/api/business/proprietorLedger";
import {authCarNumber, authPhone} from "@/utils/ruoyi";

export default {
  name: "Carport",
  dicts: ['wx_carport_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业主车位表格数据
      carportList: [],
      communityList: [],
      proprietorLedgerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proprietorId: undefined,
        proprietorName: undefined,
        proprietorPhone: undefined,
        room: undefined,
        plateNumber: undefined,
        vehicleModel: undefined,
        carportPhone: undefined,
        carportNumber: undefined,
        type: undefined,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        communityId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/carport/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        proprietorId: [
          { required: true, message: "业主不能为空", trigger: "change" }
        ],
        plateNumber: [
          { required: true, trigger: "blur", validator: authCarNumber }
        ],
        carportPhone: [
          { required: true, trigger: "blur", validator: authPhone }
        ],
        carportNumber: [
          { required: true, message: "车位号不能为空", trigger: "blur" }
        ],
        monthMoney: [
          { required: true, message: "月费不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "车位类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getCommunityListAll();
  },
  methods: {
    /** 查询业主车位列表 */
    getList() {
      this.loading = true;
      listCarport(this.queryParams).then(response => {
        this.carportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询全部小区列表 */
    getCommunityListAll() {
      listCommunityAll().then(response => {
        this.communityList = response.data;
      });
    },
    /** 查询小区业主台账信息列表 */
    getProprietorLedgerList() {
      this.loading = true
      listProprietorLedgerAll().then(response => {
        this.proprietorLedgerList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carportId: undefined,
        proprietorId: undefined,
        proprietorName: undefined,
        proprietorPhone: undefined,
        room: undefined,
        plateNumber: undefined,
        vehicleModel: undefined,
        carportPhone: undefined,
        carportNumber: undefined,
        monthMoney: undefined,
        startTime: undefined,
        endTime: undefined,
        type: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 业主改变 */
    proprietorIdChange(id) {
      let proprietorLedger = this.proprietorLedgerList.find(item => item.proprietorId === id)
      if (proprietorLedger) {
        this.form.communityId= proprietorLedger.communityId
        this.form.communityName = proprietorLedger.communityName
        this.form.proprietorName = proprietorLedger.name
        this.form.proprietorPhone = proprietorLedger.phone
        this.form.room = proprietorLedger.room
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业主车位";
      this.getProprietorLedgerList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getProprietorLedgerList()
      const carportId = row.carportId || this.ids
      getCarport(carportId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改业主车位";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.carportId != null) {
            updateCarport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCarport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carportIds = row.carportId || this.ids;
      this.$modal.confirm('是否确认删除业主车位编号为"' + carportIds + '"的数据项？').then(() => {
        this.loading = true;
        return delCarport(carportIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/carport/export', {
        ...this.queryParams
      }, `carport_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "业主车位导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/carport/importTemplate', {
      }, `业主车位导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.communityId) {
        this.$modal.msgError("提交失败，小区选项不能为空");
      }
      this.$refs.upload.submit();
    },
  }
};
</script>
