<template>
  <div class="card-container">
    <el-card class="card-heard">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="车主手机号" prop="phone">
          <el-input
            v-model="queryParams.param.phone"
            placeholder="请输入车主手机号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="车牌号" prop="carNumber">
          <el-input
            v-model="queryParams.param.carNumber"
            placeholder="请输入车牌号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.param.name"
            placeholder="请输入姓名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="车牌类型" prop="carNumberType">
          <el-select
            v-model="queryParams.param.carNumberType"
            placeholder="请选择车牌类型"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
              @keyup.enter.native="handleQuery"
            />
          </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-card>
    <el-card class="card-body">
      <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="['car: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="['car: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="['car:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['car:import']"
          >
            导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            :loading="downloadLoading"
            @click="handleExport"
            size="mini"
            v-hasPermi="['car:export']"
          >导出
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="姓名" align="center" prop="name"/>
        <el-table-column label="车主手机号" align="center" prop="phone"/>
        <el-table-column label="车牌号" align="center" prop="carNumber"/>
        <el-table-column label="车牌类型" align="center" prop="carNumberType"/>
        <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="['car:edit']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteOne(scope.row)"
              v-hasPermi="['car:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <pagination
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改用户车辆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" maxlength="20"/>
        </el-form-item>
        <el-form-item label="车主手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入车主手机号" maxlength="11"/>
        </el-form-item>
        <el-form-item label="车牌号" prop="carNumber">
          <el-input v-model="form.carNumber" placeholder="请输入车牌号" maxlength="7"/>
        </el-form-item>
        <el-form-item label="车牌类型" prop="carNumberType">
          <el-select v-model="form.carNumberType" size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button 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-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :http-request="uploadExcel"
        :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" slot="tip">
          <!--            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
          <el-link type="info" style="color: #2866e4; font-size: 12px" @click="downloadTemplate"
          >下载模板
          </el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示:仅允许导入“xls”或“xlsx”格式文件!
        </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 {
  listCar,
  getCar,
  delCar,
  addCar,
  updateCar,
  importData,
  exportCar
} from '@/api/carManage/car'

export default {
  name: 'Car',
  components: {},
  data() {
    return {
      // 上传相关
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        // headers: { Authorization: 'Bearer ' + getToken },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/tCar/import'
      },
      // 状态数据字典
      statusOptions: [],
      downloadLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户车辆表格数据
      carList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        param: {
          userId: null,
          phone: null,
          carNumber: null,
          targetId: null,
          type: null,
          isDel: null,
          version: null,
          name: null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        carNumber: [
          {
            required: true,
            message: '请输入车牌号',
            trigger: 'blur'
          }
        ]
      },
      carNumbers: [] //批量删除用
    }
  },
  created() {
    this.getList()
    this.getDicts('car_number_type').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    // 下载模版 点击
    downloadTemplate() {
      window.open(
        'http://fresh-life.oss-cn-shanghai.aliyuncs.com/sharedCarTemplate/车辆.xlsx'
      )
    },
    // 导入数据
    handleImport() {
      this.upload.title = '车辆导入'
      this.upload.open = true
    },
    // 上传Excel
    uploadExcel(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      importData(formData)
        .then((res) => {
          // console.log("上传成功");
          this.msgSuccess('导入成功')
          param.onSuccess()
        })
        .catch((res) => {
          // console.log("上传失败");
          this.msgError('导入失败')
          param.onError()
        })
    },

    // 文件上传中处理
    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.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    /*导出数据 */
    handleExport() {
      exportCar(this.queryParams.param)
        .then((res) => {
          if (res.code === 200) {
            if (res.result) {
              this.msgSuccess('导出成功')
              window.open(res.result)
            } else {
              this.msgSuccess('导出失败')
            }
          } else {
            this.msgError(res.msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /** 查询用户车辆列表 */
    getList() {
      this.loading = true
      listCar(this.queryParams).then(response => {
        this.carList = response.records
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        phone: null,
        carNumber: null,
        targetId: null,
        type: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        version: null,
        carNumberType: null
      }

      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        param: {}
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.carNumbers = selection.map(item => item.carNumber)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户车辆'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCar(id).then(response => {
        this.form = response.result
        this.open = true
        this.title = '编辑用户车辆'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCar(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCar(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDeleteOne(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除用户车牌号为"' + row.carNumber + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCar(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除用户车牌号为"' + this.carNumbers + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCar(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    }
  }
}
</script>
