<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="enableTime">
        <el-date-picker clearable
          v-model="queryParams.enableTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生效时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="失效时间" prop="overdueTime">
        <el-date-picker clearable
          v-model="queryParams.overdueTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择失效时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否启动" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="请选择" clearable @keyup.enter.native="handleQuery" >
          <el-option
            key="1"
            label="是"
            value="1"
          ></el-option>
          <el-option
            key="0"
            label="否"
            value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号" prop="plate">
        <el-input
          v-model="queryParams.plate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属单位" prop="unit">
        <el-select v-model="queryParams.unit" placeholder="请选择所属单位">
          <el-option
            v-for="dict in dict.type.car_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属人员" prop="peopleName">
        <el-input
          v-model="queryParams.peopleName"
          placeholder="请输入所属人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['system:carInfo: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="['system:carInfo: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="['system:carInfo: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="['system:carInfo: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="['system:carInfo:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属车场" align="center" prop="parkName" />
      <el-table-column label="车牌号" align="center" prop="plate" />
      <el-table-column label="生效时间" align="center" prop="enableTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enableTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效时间" align="center" prop="overdueTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.overdueTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启动" align="center" prop="enable" >
          <template slot-scope="scope">
            <span v-if="scope.row.enable=='1'">是</span>
            <span v-if="scope.row.enable=='0'">否</span>
          </template>
      </el-table-column>
      <el-table-column label="是否启用时间段" align="center" prop="timeSegEnable" >
          <template slot-scope="scope">
            <span v-if="scope.row.timeSegEnable=='1'">是</span>
            <span v-if="scope.row.timeSegEnable=='0'">否</span>
          </template>
      </el-table-column>
      <el-table-column label="时间段" align="center" prop="segTime" width="180">
      </el-table-column>
      <el-table-column label="是否报警" align="center" prop="needAlarm" >
          <template slot-scope="scope">
            <span v-if="scope.row.needAlarm=='1'">是</span>
            <span v-if="scope.row.needAlarm=='0'">否</span>
          </template>
      </el-table-column>
      <el-table-column label="所属单位" align="center" prop="unit">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.car_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="所属人员" align="center" prop="peopleName" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="备注" align="center" prop="remark" />
      <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="['system:carInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:carInfo: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="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" >
            <el-form-item label="所属车场" prop="parkId">
              <el-select v-model="form.parkId" placeholder="请输入所属车场"  >
                <el-option
                  v-for="dict in parkOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="车牌号" prop="plate">
              <el-input v-model="form.plate" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="车辆类型" prop="carType">
              <el-select v-model="form.carType" placeholder="请输入车辆类型"  @change="showNums" >
                <el-option
                  v-for="dict in dict.type.car_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showNum" >
            <el-form-item label="通行次数" prop="num">
              <el-input-number v-model="form.num" placeholder="请输入通行次数" :min="0"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" >
                <el-form-item label="生效时间" prop="enableTime">
                  <el-date-picker clearable
                    v-model="form.enableTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择生效时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
                <el-form-item label="失效时间" prop="overdueTime">
                  <el-date-picker clearable
                    v-model="form.overdueTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择失效时间">
                  </el-date-picker>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
                <el-form-item label="是否启用" prop="enable">
                  <el-select v-model="form.enable" placeholder="请输入是否启动"  >
                    <el-option
                      key="1"
                      label="是"
                      value="1"
                    ></el-option>
                    <el-option
                      key="0"
                      label="否"
                      value="0"
                    ></el-option>
                  </el-select>
                </el-form-item>
          </el-col>

          <el-col :span="12" >
                <el-form-item label="时间段启用" prop="timeSegEnable">
                  <el-select v-model="form.timeSegEnable" placeholder="请输入是否启用时间段"  >
                    <el-option
                      key="1"
                      label="是"
                      value="1"
                    ></el-option>
                    <el-option
                      key="0"
                      label="否"
                      value="0"
                    ></el-option>
                  </el-select>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
                <el-form-item label="时间段" prop="value2">
                  <el-time-picker style="width: 90%"
                    is-range
                    v-model="form.value2"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    value-format="HH:mm:ss"
                  >
                  </el-time-picker>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
                <el-form-item label="是否需要报警" prop="needAlarm">
                  <el-select v-model="form.needAlarm" placeholder="请输入是否需要报警"  >
                    <el-option
                      key="1"
                      label="是"
                      value="1"
                    ></el-option>
                    <el-option
                      key="0"
                      label="否"
                      value="0"
                    ></el-option>
                  </el-select>
                </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="所属单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请输入所属车场"  >
                <el-option
                  v-for="dict in dict.type.car_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="所属人员" prop="peopleId">
              <el-select
                v-model="form.peopleId"
                filterable
                remote
                reserve-keyword
                placeholder="请搜索所属人员"
                :remote-method="remoteMethod"
                :loading="loading"
                @change="selectPhone"
              >
                <el-option
                  v-for="item in peopleOptions"
                  :key="item.id"
                  :label='item.gh+item.name'
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"  />
            </el-form-item>
          </el-col>
          <el-col :span="24" >
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
          </el-col>
          </el-row>
      </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 + '?updateSupport=' + upload.updateSupport"
        :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">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>
          <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 { listCarInfo, getCarInfo, delCarInfo, addCarInfo, updateCarInfo } from "@/api/vehicle/carInfo";
import {listCarPark} from "@/api/vehicle/carPark";
import {getToken} from "@/utils/auth";
import {getSysPeople, listSysPeople} from "@/api/system/sysPeople";

export default {
  name: "CarInfo",
  dicts: ['car_type','car_unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showNum: false,
      // 总条数
      total: 0,
      // 车辆信息表格数据
      carInfoList: [],
      peopleOptions: [],
      parkOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enableTime: null,
        overdueTime: null,
        enable: null,
        plate: null,
        peopleId: null,
      },
      queryParams1: {
        id:null,
        name:"",
      },
      // 表单参数
      form: {},
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/carInfo/importData"
      },
      // 表单校验
      rules: {
        carType: [
          { required: true, message: "车辆类型不能为空", trigger: "blur" }
        ],
        enableTime: [
          { required: true, message: "生效时间不能为空", trigger: "blur" }
        ],
        overdueTime: [
          { required: true, message: "失效时间不能为空", trigger: "blur" }
        ],
        parkId: [
          { required: true, message: "车场不能为空", trigger: "blur" }
        ],
        plate: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
        timeSegEnable: [
          { required: true, message: "是否启用时间段不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getOptions()
  },
  methods: {
    /** 查询车辆信息列表 */
    getList() {
      this.loading = true;
      listCarInfo(this.queryParams).then(response => {
        this.carInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getOptions() {
      this.parkOptions = []
      listCarPark().then(response => {
        this.parkOptions = response.rows
      })
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        enableTime: null,
        overdueTime: null,
        enable: null,
        plate: null,
        timeSegEnable: null,
        segTime: null,
        needAlarm: null,
        vehicleCode: null,
        vehicleComment: null,
        peopleId: null,
        delFlag: null,
        sync: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        partId:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      getCarInfo(customerId).then(response => {
        this.form = response.data;
        if(this.form.segTime!=null){
          let segTime=this.form.segTime.split("-")
          let value2=[segTime[0],segTime[1]]
          this.$set(this.form,'value2',value2)
        }
        this.open = true;
        this.title = "修改车辆信息";
        this.queryParams1.name=null;
        this.queryParams1.id=this.form.peopleId;
        this.peopleOptions=[];
        listSysPeople(this.queryParams1).then(response => {
          this.peopleOptions = response.rows;
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.value2 != null) {
        this.form.segTime = this.form.value2[0] + "-" + this.form.value2[1];
      } else {
        delete this.form.segTime;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateCarInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCarInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除车辆信息编号为"' + customerIds + '"的数据项？').then(function() {
        return delCarInfo(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/carInfo/export', {
        ...this.queryParams
      }, `carInfo_${new Date().getTime()}.xlsx`)
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.queryParams1.name=query;
          this.queryParams1.id=null;
          listSysPeople(this.queryParams1).then(response => {
            this.peopleOptions = response.rows;
            this.loading = false;
          });
        }, 200);
      } else {
        this.peopleOptions = [];
      }
    },
    showNums(){
      let date = new Date()
      let year= date.getFullYear()  // 得到当前年份
      let month = date.getMonth()  + 1 // 得到当前月份（0-11月份，+1是当前月份）
      month  = month > 10 ? month :'0' + month // 补零
      let day  = date.getDate()
      if(this.form.carType==1){
        this.showNum=true;
        this.form.enableTime=new Date();
        this.form.overdueTime=new Date(year,month,day);
      }else{
        this.showNum=false;
        this.form.enableTime=new Date();
        this.form.overdueTime=new Date(year+5,month-1,day);
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "车辆信息导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    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() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/carInfo/importTemplate', {
      }, `carInfo_${new Date().getTime()}.xlsx`)
    },
    selectPhone(){
      getSysPeople(this.form.peopleId).then(response => {
        this.form.phone=response.data.phone;
      });
    }
  }
};
</script>
