<!--车辆排班   保养弹框-->
<template>
  <el-dialog title="安排用车" :visible.sync="anpai" class="user-car">
    <el-form :model="form"  ref="form" :rules="rules" label-width="140px">
      <el-form-item label="车牌号">
        <span>{{currentItem.item.numberPlate}}</span>
      </el-form-item>
      <el-form-item label="车型名称">
        <span>{{currentItem.item.vehicleModel.name}}</span>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="当前停靠公司:">
            <span>{{currentItem.item.parkCompanyName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属公司">
            <span>{{currentItem.item.subordinateBranchName}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公里数">
            <span>{{currentItem.item.mileageLastUpdate}}km</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="房车配置">
        <span v-if="currentItem.item.vehicleModel.keyword">{{currentItem.item.vehicleModel.keyword}}</span>
      </el-form-item>
      <el-form-item label="选择时间" prop="times">
        <el-date-picker
          v-model="form.times"
          type="datetimerange"
          :picker-options="pickerOptions0"
          format="yyyy-MM-dd HH:00:00" 
          value-format="yyyy-MM-dd HH:00:00"
          placeholder="选择时间范围">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="还车分公司" prop="arrivalBranchCompanyName">
        <el-autocomplete
          class="inline-input"
          v-model="form.arrivalBranchCompanyName"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelectArrivalCompanyName"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="用途" prop="bookType">
        <!--bookType 2-租车、1-分公司使用、3-维修、4、展览、5、旅游、6、保养、7、预约中、8、禁用-->
        <el-select class="filter-item" v-model="form.bookType" placeholder="请选择用途">
          <!-- <el-option label="租车" value="1"></el-option> -->
          <el-option label="维修" value="3"></el-option>
          <el-option label="展览" value="4"></el-option>
          <el-option label="旅游" value="5"></el-option>
          <el-option label="保养" value="6"></el-option>
          <el-option label="禁用" value="8"></el-option>
          <el-option label="客户用车" value="9"></el-option>
          <el-option label="其他" value="10"></el-option>


          <!--<el-option v-for="item  in getAllUseType() " :key="item.code" :label="item.val"-->
                     <!--:value="item.code"></el-option>-->
        </el-select>
      </el-form-item>
      <el-form-item label="保养项目" prop="upkeepIds" v-if="form.bookType==6">
        <el-checkbox-group v-model="form.upkeepIds">
          <el-checkbox v-for="item in upkeepList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="路线" v-if="form.bookType==5" required>
        <el-select class="filter-item" placeholder="请选择路线" v-model="goodId" @change="goodChange">
          <el-option :key="undefined" label="无" :value="undefined"></el-option>
          <el-option v-for="item in goodList" :key="item.goodId" :label="item.goodName" :value="item.goodId"></el-option>
        </el-select>
        <el-select class="filter-item" placeholder="请选择出车公司" v-model="siteId" @change="siteChange">
          <el-option :key="undefined" label="无" :value="undefined"></el-option>
           <el-option v-for="item in siteList" :key="item.siteId" :label="item.siteName" :value="item.siteId"></el-option>
        </el-select>
        <el-select class="filter-item" placeholder="请选择出发时间" v-model="verificationId">
          <el-option v-for="item in timeList" :key="item.verificationId" :label="item.time" :value="item.verificationId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用人" prop="vehicleUsername">
        <el-input v-model="form.vehicleUsername" placeholder="请输入使用人"></el-input>
      </el-form-item>
      <el-form-item label="使用人联系方式" prop="vehicleUserPhone">
        <el-input v-model="form.vehicleUserPhone" type="number" placeholder="请输入使用人联系方式"></el-input>
      </el-form-item>
      <el-form-item label="说明">
        <el-input v-model="form.remark" :rows="3" placeholder="请输入说明"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="handelOk('form')" v-if="vehicleSchedulManage_btn_add_plan">确 定</el-button>
    </div>
  </el-dialog>
</template>
<style>
  .user-car .el-row{
    margin-bottom: 0;
  }
</style>
<script>
  import {mapGetters} from 'vuex';
  import {
    VEHICLE_CONSTANT_VEHICLE_BRAND,
    VEHICLE_CONSTANT_VEHICLE_USE,
    VEHICLE_CONSTANT_BRAND_CODE_UNKOWN,
    BELONG_TO_TYPE_OWN,
    VEHICLE_CONSTANT_USE_TYPE_UNKOWN,
    VEHICLE_CONSTANT_STATUS_NORMAL
  } from '../../../store/modules/baseInfo';
  import {
    getConstantByTypeAndCode,
    getConstantListByType,
    getAllInsuranceCompany,
    getInsuranceCompany
  } from 'api/base_info/constant/';
  import {
    getAllCompany,
    getAll
  } from 'api/base_info/branch_company/';
  import {
    bookPlan,
    getUpkeepAll,
    getTourList
  } from 'api/vehicle/vehicleSchedulManage';
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  import ElFormItem from "../../../../node_modules/element-ui/packages/form/src/form-item.vue";
  import {
    formatDate
  } from 'utils/dateFormattor';
  export default {
    components: {
      ElFormItem,
      ElCol,
      ElRow},
    props: ["currentItem"],
    name: 'vehiclePlanModal',
    data() {
      var checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          const reg = /^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][1,2,3,5,6,7,8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
          console.log(reg.test(value));
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error('请输入正确的手机号'));
          }
        }
      };
      return {
        goodId:undefined,
        siteId:undefined,
        verificationId:undefined,
        goodList:[],
        siteList:[],
        timeList:[],
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        anpai:false,
        allCompaniesArr:[],
        upkeepList:[],
        form:{
          remark: "",
          vehicleUsername: "",
          arrivalBranchCompanyId: undefined,//还车分公司id
          arrivalBranchCompanyName: "",//还车分公司名称
          vehicleUserPhone:"",//使用人联系电话
          bookType: undefined,//用途
          times: [],
          upkeepIds:[]
        },
        rules: {
          vehicleUsername: [
            {
              type: 'string',
              required: true,
              message: '请输入使用人姓名',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 20,
              message: '长度小于 20 个字符',
              trigger: 'blur'
            }
          ],
          arrivalBranchCompanyName:{
            type: 'string',
            required: true,
            message: '请选择还车公司',
            trigger: 'change'
          },
          vehicleUserPhone:{validator: checkPhone, trigger: 'blur',required: true},
          bookType:{
            type: 'string',
            required: true,
            message: '请选择用途',
            trigger: 'change'
          },
          times: {
            required: true,
            message: '请选择时间',
          }
        },
        vehicleSchedulManage_btn_add_plan: false,//申请预定
      }
    },
    created() {
      console.log(this.currentItem);
      this.vehicleSchedulManage_btn_add_plan = this.elements['vehicleSchedulManage:btn_add_plan'];
      getAll()
        .then(response => {
          this.allCompaniesArr = response.data;
        })
      getAllCompany(codeAndBranchCompany => {
        this.allCompanies = codeAndBranchCompany;
      });
      getUpkeepAll().then(response => {
        this.upkeepList = response.data
      })
      getTourList().then(response=> {
        this.goodList = response.data
      })
    },
    computed: {
      ...mapGetters([
        'elements',
      ]),
    },
    watch: {
      anpai(newValue, oldValue){
        if(!newValue){
          this.$emit("anpaiDialogEvent", false);
        }
      },
    },
    mounted() {
      this.anpai = true;
    },
    methods: {
      goodChange(){
        this.siteId = undefined
        getTourList('goodId='+this.goodId).then(response=> {
          this.siteList = response.data
        })
      },
      siteChange(){
        this.verificationId = undefined
        getTourList('siteId='+this.siteId+'&goodId='+this.goodId).then(response=> {
          this.timeList = response.data
          this.verificationId = response.data[0].verificationId
        })
      },
      /**
       * 还车分公司
       */
      handleSelectArrivalCompanyName(item){
        this.form.arrivalBranchCompanyId = item.id;
        this.form.arrivalBranchCompanyName = item.name;
        console.log(item);
      },
      querySearch(queryString, cb) {
        let selectArry = [];
        this.allCompaniesArr.map(function(item){
          item.value = item.name;
          selectArry.push(item);
        });
        this.selectArry = selectArry;
        var results = queryString ? selectArry.filter(this.createFilter(queryString)) : selectArry;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.indexOf(queryString.toLowerCase()) != -1);
        };
      },
      /**
       * 弹框-取消
       * */
      cancel() {
        this.$emit("anpaiDialogEvent", false);
      },
      /**
       * 确定用车
       * */
      handelOk(formName){
        const set = this.$refs;
        // console.log(formatDate(this.form.times[0], "yyyy-MM-dd hh:mm:ss"));
        set[formName].validate(valid => {
          if (valid) {
            if(this.form.bookType==6){
              if(this.form.upkeepIds.length==0){
                this.$notify({
                  title: '警告',
                  message: '请选择保养类型',
                  type: 'warning',
                  duration: 2000
                });
                return false;
              }
            }
            console.log(this.verificationId)
            if(this.form.bookType==5){
              if(this.verificationId==undefined){
                this.$notify({
                  title: '警告',
                  message: '请选择旅游路线',
                  type: 'warning',
                  duration: 2000
                });
                return false;
              }
              this.form.verificationId = this.verificationId
            }
            let params = {
              vehicleId:this.currentItem.item.id,
              bookStartDate: formatDate(this.form.times[0], "yyyy-MM-dd hh") + ":00:00",//预定开始时间
              bookEndDate: formatDate(this.form.times[1], "yyyy-MM-dd hh") + ":00:00",//预定结束时间
              retCompany: this.form.arrivalBranchCompanyId,//还车分公司
              bookType: this.form.bookType,//预定车辆用途类型
              vehicleUsername: this.form.vehicleUsername,//使用人姓名
              vehicleUserPhone: this.form.vehicleUserPhone,//使用人电话
              remark: this.form.remark,//说明
              upkeepIds:this.form.bookType==6?this.form.upkeepIds.join(","):'',//保养类型
              orderNo:this.form.bookType==5?this.verificationId:''
            };
            bookPlan(params).then(response => {
              if (response.status === 200) {
                this.$emit("anpaiDialogEvent", true);
              } else {
                this.$notify({
                  title: '失败',
                  message: response.message,
                  type: 'error',
                  duration: 2000
                });
              }
            })
          }
        })
      },

    }
  }
</script>
