<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form ref="listQuery" :model="listQuery" :rules="rules" label-width="115px">
        <el-form-item label="取/还车公司" required>
          <el-col :span="3">
            <el-form-item prop="startCompanyId">
              <el-autocomplete
                class="inline-input"
                v-model="listQuery.startCompanyId"
                :fetch-suggestions="querySearch"
                placeholder="请输入取车公司"
                @select="handleSelectPark"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="width:20px">一</el-col>
          <el-col :span="5">
            <el-form-item prop="endCompanyId">
              <el-autocomplete
                class="inline-input"
                v-model="listQuery.endCompanyId"
                :fetch-suggestions="querySearch"
                placeholder="请输入取车公司"
                @select="returnCarSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="取/还车时间:" prop="time">
          <el-date-picker
            v-model="listQuery.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            placeholder="请输入取/还车时间"
            end-placeholder="结束日期"
            value-format="timestamp"
            @change="changeTime"
            :picker-options="pickerOptions"
          >></el-date-picker>

          <el-button
            class="filter-item"
            type="primary"
            v-waves
            @click="lookType('listQuery')"
            style="margin:0 0 0 10px"
            :loading="lookLoad"
          >查看可用车型</el-button>
        </el-form-item>

        <div v-show="isHave">
          <el-row>
            <el-form-item label="选择车型:" :prop="isHave === true ? domains.modelId : ''">
              <el-radio-group v-model="listQuery.modelId">
                <el-radio-button
                  v-for="(item,index) in motorcycle"
                  :key="index"
                  :label="item.id"
                >{{item.name}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-col :span="5">
              <el-form-item label="手机号:" :prop="isHave === true ? domains.tel : ''">
                <el-input v-model="listQuery.tel" placeholder="请输入手机号" @blur="lose"></el-input>
              </el-form-item>
              <el-form-item label="车损免赔:" :prop="isHave === true ? domains.damageSafe : ''">
                <el-radio-group v-model="listQuery.damageSafe">
                  <el-radio-button label="需要"></el-radio-button>
                  <el-radio-button label="不需要"></el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="使用会员天数:" :prop="isHave === true ? domains.rentFreeDay : ''">
                <el-radio-group v-model="listQuery.rentFreeDay">
                  <el-radio-button label="使用" :disabled="userFreeDay"></el-radio-button>
                  <el-radio-button label="不使用"></el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-button
            class="filter-item"
            type="primary"
            v-waves
            @click="createOrder('listQuery')"
          >创建订单</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getAll } from "api/base_info/branch_company/";
import { inquire, addIndent } from "api/order/rentVehicle";
import { getYMD_hm, timestamp2Date } from "utils/dateUtils";
import { username } from "api/admin/userManagement";
export default {
  created() {
    getAll().then(response => {
      this.allCompaniesArr = response.data;
    });
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          // console.log(Date.now());
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      appUserId: null,
      userFreeDay: true,
      isPhone: true,
      motorcycle: [],
      isHave: false,
      allCompaniesArr: [],
      lookLoad: false,
      listQuery: {
        startCompanyId: null,
        endCompanyId: null,
        startCompanyIds: null,
        endCompanyIds: null,
        // time: [new Date(2019, 10, 10, 9, 0), new Date(2019, 10, 11, 18, 0)],
        time: [],
        limit: 100,
        page: 1,
        modelId: "",
        radio1: "",
        tel: "",
        damageSafe: "",
        rentFreeDay: ""
      },
      domains: {
        modelId: "modelId",
        tel: "tel",
        damageSafe: "damageSafe",
        rentFreeDay: "rentFreeDay"
      },
      rules: {
        startCompanyId: [
          {
            required: true,
            message: "请选择取车公司",
            trigger: "change"
          }
        ],
        endCompanyId: [
          {
            required: true,
            message: "请选择还车公司",
            trigger: "change"
          }
        ],
        time: [
          {
            type: "array",
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        modelId: [
          {
            type: "array",
            required: true,
            message: "请选择车型",
            trigger: "change"
          }
        ],
        tel: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
        damageSafe: [
          {
            type: "array",
            required: true,
            message: "请选择是否购买免赔",
            trigger: "change"
          }
        ],
        rentFreeDay: [
          { required: true, message: "请输入使用会员天数", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    changeTime() {
      !!this.listQuery.time[0] ? "" : (this.listQuery.time = []);
    },
    //创建订单
    createOrder(formName) {
      if (this.listQuery.startCompanyId == "") {
        this.$notify({
          title: "失败",
          message: "请选择取/还车公司",
          type: "error",
          duration: 2000
        });
        return false;
      } else if (this.listQuery.time == "") {
        this.$notify({
          title: "失败",
          message: "请选择取/还车时间",
          type: "error",
          duration: 2000
        });
        return false;
      } else if (this.listQuery.modelId == "") {
        this.$notify({
          title: "失败",
          message: "请选择车型",
          type: "error",
          duration: 2000
        });
        return false;
      } else if (this.listQuery.tel == "") {
        this.$notify({
          title: "失败",
          message: "请选择输入手机号",
          type: "error",
          duration: 2000
        });
        return false;
      } else if (this.isPhone == false) {
        return false;
      } else if (this.listQuery.damageSafe == "") {
        this.$notify({
          title: "失败",
          message: "请选择车损免赔",
          type: "error",
          duration: 2000
        });
        return false;
      } else if (this.listQuery.rentFreeDay == "") {
        this.$notify({
          title: "失败",
          message: "请选择是否使用会员天数",
          type: "error",
          duration: 2000
        });
        return false;
      } else {
        var nTime =
          this.listQuery.time[1].getTime() - this.listQuery.time[0].getTime();
        let params = {
          dayNum: (nTime / (24 * 60 * 60 * 1000)) + 1, //天数
          endAddr: this.listQuery.startEndAddr, //还车地点
          endCity: this.listQuery.startAddrCity, //还车城市编号
          endCityName: this.listQuery.startCityName, //还车城市名称
          endCompanyId: this.listQuery.startCompanyIds, //还车公司id
          endTime: this.listQuery.time[1].getTime(), //结束时间

          modelId: this.listQuery.modelId, //车型
          startAddr: this.listQuery.endEndAddr, //取车地点
          startCity: this.listQuery.endAddrCity, //取车城市编号
          startCityName: this.listQuery.endtCityName, //取车城市名称
          startCompanyId: this.listQuery.endCompanyIds, //出发公司id
          startTime: this.listQuery.time[0].getTime(), //开始时间

          damageSafe: this.listQuery.damageSafe == "需要" ? 1 : 0, //是否购买免赔
          rentFreeDay: this.listQuery.rentFreeDay == "使用" ? 1 : 0, //是否使用出租免费天数
          orderOrigin: 3, //订车来源
          appUserId: this.appUserId
        };
        addIndent(params).then(data => {
          console.log(data);
          if (data.status == 200) {
            this.$alert("创建订单成功", "标题名称", {
              confirmButtonText: "确定",
              callback: action => {
                this.listQuery = {
                  startCompanyId: null,
                  endCompanyId: null,
                  startCompanyIds: null,
                  endCompanyIds: null,
                  time: [],
                  limit: 100,
                  page: 1,
                  modelId: "",
                  radio1: "",
                  tel: "",
                  damageSafe: "",
                  rentFreeDay: ""
                };
                this.userFreeDay = true;
              }
            });
          } else {
            this.$notify({
              title: "失败",
              message: data.message,
              type: "error",
              duration: 2000
            });
          }
        });
      }
    },
    //检车用户是否注册
    lose() {
      username(this.listQuery.tel).then(data => {
        if (data.status == 200) {
          if (!!data.data) {
            // console.log(!!data.data.rentFreeDays);
            // console.log(data.data);
            // console.log(data.data.userid);
            this.appUserId = data.data.userid;
            if (!!data.data.rentFreeDays) {
              if (data.data.rentFreeDays >= 1) {
                this.userFreeDay = false;
              }
            } else {
              this.userFreeDay = true;
            }
            this.isPhone = true;
          }
        } else if (data.status == 1009) {
          this.$notify({
            title: "失败",
            message: "该手机号未注册",
            type: "error",
            duration: 2000
          });
          this.isPhone = false;
        }
      });
    },
    lookType(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            startCompanyIds: this.listQuery.startCompanyIds,
            endCompanyIds: this.listQuery.endCompanyIds,
            startDateTamp: this.listQuery.time[0].getTime(),
            endDateTamp: this.listQuery.time[1].getTime(),
            limit: 100,
            page: 1,
            parkBranchCompanyId: this.listQuery.startCompanyIds
          };
          this.lookLoad = true;
          inquire(params).then(data => {
            if (data.status == 200) {
              let all = [];
              let allCar = {};
              data.data.data.forEach(element => {
                if (element.hasVehicle == 1) {
                  if (all.indexOf(element.vehicleModel.name) == -1) {
                    all.push({
                      id: element.vehicleModel.id,
                      name: element.vehicleModel.name
                    });
                  }
                }
              });

              all = all.reduce(function(item, next) {
                allCar[next.id]
                  ? ""
                  : (allCar[next.id] = true && item.push(next));
                return item;
              }, []);
              this.motorcycle = all;

              if (all.length < 1) {
                this.$notify({
                  title: "失败",
                  message: "暂无可用车辆,修改取车公司或时间试试",
                  type: "error",
                  duration: 3000
                });
              } else {
                this.isHave = true;
              }
            }
          });
          this.lookLoad = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    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);
    },
    returnCarSelect(item) {
      //取车
      this.listQuery.endEndAddr = item.addrDetail; //取车地点
      this.listQuery.endAddrCity = item.addrCity; //还车城市编号
      this.listQuery.endtCityName = item.cityName; //还车城市名称
      this.listQuery.endCompanyIds = item.id;
      this.listQuery.endCompanyId = item.name;
    },
    handleSelectPark(item) {
      //还车
      this.listQuery.startEndAddr = item.addrDetail; //换成地点
      this.listQuery.startAddrCity = item.addrCity; //还车城市编号
      this.listQuery.startCityName = item.cityName; //还车城市名称
      this.listQuery.startCompanyIds = item.id; //公司id
      this.listQuery.startCompanyId = item.name;
    },
    createFilter(queryString) {
      return restaurant => {
        return restaurant.name.indexOf(queryString.toLowerCase()) != -1;
      };
    }
  }
};
</script>