<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div v-if="!oneTourDialogVisible">
      <div class="filter-container" ref="filter-container">
        <el-form
          :rules="rules4Query"
          ref="queryForm"
          :inline="inline"
          :model="listQuery"
          label-width="100px"
        >
          <el-row>
            <el-col :span="5">
              <el-form-item label="旅行名称">
                <el-input v-model.number="listQuery.name" placeholder="请输入旅行名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="标签">
                <el-select class="filter-item" v-model="listQuery.tagId" placeholder="请选择标签">
                  <el-option :key="undefined" label="全部" :value="undefined"></el-option>
                  <el-option
                    v-for="val in allLabelList"
                    :key="val.id"
                    :label="val.name"
                    :value="val.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="所属公司">
                <el-select
                  class="filter-item"
                  v-model="listQuery.corporationId"
                  clearable
                  filterable
                  placeholder="请选择公司"
                >
                  <el-option label="全部" :key="undefined" :value="undefined"></el-option>
                  <el-option
                    v-for="val in companys_list"
                    :key="val.id"
                    :label="val.name"
                    :value="val.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="所属门店">
                <el-select
                  class="filter-item"
                  v-model="listQuery.companyId"
                  clearable
                  placeholder="请选择"
                >
                  <el-option label="全部" :key="undefined" :value="undefined"></el-option>
                  <el-option
                    v-for="val in branchCompany_list"
                    :key="val.id"
                    :label="val.name"
                    :value="val.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-search"
          @click="handleFilter"
        >搜索</el-button>
        <el-button class="filter-item" v-waves @click="clear_handleFilter">清除搜索</el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          @click="handleCreate"
          type="primary"
          icon="el-icon-edit"
          v-if="good_btn_add"
        >添加</el-button>
      </div>
      <el-table :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%">
        <el-table-column type="index" align="center" label="序号" width="65"></el-table-column>
        <el-table-column width="666" align="center" label="旅行名称/价格">
          <template slot-scope="scope">
            <img :src="scope.row.cover" style="width: 30px;" />
            <span>{{scope.row.name}}￥{{scope.row.price}}/{{scope.row.unit}}</span>
          </template>
        </el-table-column>

        <el-table-column width="300" align="center" label="标签">
          <template slot-scope="scope">
            <span>{{scope.row.tagNames}}</span>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center" label="所属门店">
          <template slot-scope="scope">
            <span v-if="scope.row.companyName">{{scope.row.companyName}}</span>
            <span v-else>/</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="所属公司">
          <template slot-scope="scope">
            <span v-if="scope.row.corporationName">{{scope.row.corporationName}}</span>
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="150" label="操作">
          <template slot-scope="scope">
            <el-button
              size="small"
              class="el-button el-button--text el-button--small"
              @click="handleUpdate(scope.row)"
            >{{good_btn_update?'编辑':'查看'}}</el-button>
            <el-button
              size="small"
              class="el-button el-button--text el-button--small"
              style="color: #6ce26c;"
              v-if="(scope.row.status==2&&good_btn_upstatus)||(scope.row.status==0&&good_btn_upstatus)"
              @click="upStatus(scope.row)"
            >上架</el-button>
            <el-button
              size="small"
              class="el-button el-button--text el-button--small"
              style="color: #1d90e6"
              v-if="scope.row.status==1&&good_btn_upstatus"
              @click="upStatus(scope.row)"
            >下架</el-button>
            <el-button
              class="el-button el-button--text el-button--small"
              style="color:red;"
              size="small"
              @click="deleteHandler(scope.row)"
              v-if="good_btn_del"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="listQuery.page"
          :page-sizes="[10,20,30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <!-- 旅游modal弹窗 -->
    <oneTour
      v-if="oneTourDialogVisible"
      :oneTourRow="oneTourRow"
      :good_btn_update="good_btn_update"
      :title="modalTitle"
      v-on:oneTourDialogEvent="oneTourDialogEvent"
    ></oneTour>
  </div>
</template>

<script>
import oneTour from "./modal/oneTourModal"; // 旅游
import "static/css/uploadImg.css"; // 引入图片上传组件对话框

import { formatDate } from "utils/dateFormattor";
import { company_all_list, branchCompany_all_list } from "api/company.js";

import {
  toEast8Date,
  deepCopyDate,
  newEast8Date,
  convertDate2Str,
} from "utils/dateUtils";

import rsCode from "../../utils/rsCode";

import { mapGetters } from "vuex";
import { getToken } from "utils/auth";

import {
  page,
  goodsEdit,
  getAllTourTag,
  goodDel,
  upStatusChange,
} from "api/tourManage";

import Element1 from "../admin/menu/components/element";
import ElRow from "element-ui/packages/row/src/row";
import ElCol from "element-ui/packages/col/src/col";

export default {
  name: "tourManage",
  components: {
    ElCol,
    ElRow,
    Element1,
    oneTour,
  },
  data() {
    return {
      modalTitle: "创建",
      BASE_API: process.env.BASE_API,
      oneTourDialogVisible: false, //添加、编辑弹框
      showLoadingBody: false,
      form: {
        tagNames: "", //标签
        name: undefined, //旅游名称
        saleCount: undefined, //销量
        stock: undefined, //总数量
      },
      allLabelList: [], //全部标签
      rules: {
        subordinateBranch: [
          {
            type: "integer",
            required: true,
            message: "请选择公司",
            trigger: "blur",
          },
        ],
        maintenanceMileage: [this.integerValidator()],
        code: [
          {
            validator: (rule, value, callback) => {
              if (this.$utils.isUndefined(value) || this.$utils.isNull(value)) {
                return callback();
              }
              if (!this.$utils.isInteger(value)) {
                return callback(new Error("编码必须为整数"));
              }
              if (value < 1 || value > 9999999999) {
                return callback(new Error("编码合法范围：[1 - 9999999999]"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        vin: [
          {
            min: 0,
            max: 200,
            message: "长度小于 200 个字符",
            trigger: "blur",
          },
        ],
        numberPlate: [
          {
            min: 0,
            max: 20,
            message: "长度小于 20 个字符",
            trigger: "blur",
          },
        ],
        remark: [
          {
            min: 0,
            max: 2000,
            message: "长度小于 2000 个字符",
            trigger: "blur",
          },
        ],
      },
      pickerOptions4Apply: {
        disabledDate: this.checkBookDate,
      },
      rules4Query: {
        vin: [
          {
            min: 0,
            max: 200,
            message: "长度小于 200 个字符",
            trigger: "blur",
          },
        ],
        subordinateBranch: [
          {
            validator: (rule, value, callback) => {
              if (
                (this.$utils.isString(this.listQuery.bookedStartDate) &&
                  this.listQuery.bookedStartDate !== "") ||
                (this.$utils.isString(this.listQuery.bookedEndDate) &&
                  this.listQuery.bookedEndDate !== "") ||
                (this.$utils.isString(this.listQuery.notBookedStartDate) &&
                  this.listQuery.notBookedStartDate !== "") ||
                (this.$utils.isString(this.listQuery.notBookedEndDate) &&
                  this.listQuery.notBookedEndDate !== "")
              ) {
                if (!this.listQuery.subordinateBranch) {
                  return callback(
                    new Error("若需按预定日期查询车辆，选择分公司")
                  );
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        notBookDateRange: [
          {
            validator: (rule, value, callback) => {
              if (this.notBookDateRange) {
                let startDate = toEast8Date(this.listQuery.notBookedStartDate);
                let endDate = toEast8Date(this.listQuery.notBookedEndDate);
                if (
                  this.$utils.isDate(startDate) &&
                  startDate.setMonth(startDate.getMonth() + 2) < endDate
                ) {
                  return callback(new Error("日期范围不能超过2个月"));
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        bookDateRange: [
          {
            validator: (rule, value, callback) => {
              if (this.bookDateRange) {
                let startDate = toEast8Date(this.listQuery.bookedStartDate);
                let endDate = toEast8Date(this.listQuery.bookedEndDate);
                if (
                  this.$utils.isDate(startDate) &&
                  startDate.setMonth(startDate.getMonth() + 2) < endDate
                ) {
                  return callback(new Error("日期范围不能超过2个月"));
                }
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      },
      rules4Apply: {
        bookDateRange4Apply: [
          {
            validator: (rule, value, callback) => {
              if (
                !this.$utils.isArray(this.bookDateRange4Apply) ||
                this.bookDateRange4Apply.length === 0
              ) {
                return callback(new Error("请输入预定时间。"));
              }
              let [oriStartDate, ortEndDate] = this.bookDateRange4Apply;
              if (
                !this.$utils.isDate(oriStartDate) ||
                !this.$utils.isDate(ortEndDate)
              ) {
                return callback(new Error("请输入预定时间。"));
              }
              let [startDate, endDate] = [
                deepCopyDate(oriStartDate),
                deepCopyDate(ortEndDate),
              ];
              if (
                !this.$utils.isDate(oriStartDate) ||
                !this.$utils.isDate(ortEndDate)
              ) {
                return callback();
              }
              for (
                let curDate = startDate;
                curDate <= endDate;
                curDate.setDate(curDate.getDate() + 1)
              ) {
                if (this.checkBookDate(curDate)) {
                  return callback(
                    new Error("请选择从今天起两个月内，未预定的时间。")
                  );
                }
              }
              callback();
            },
            required: true,
            trigger: "blur",
          },
        ],
        liftCompany: [
          {
            required: true,
            message: "请选择提车分公司",
            trigger: "blur",
            type: "integer",
          },
        ],
        retCompany: [
          {
            required: true,
            message: "请选择还车分公司",
            trigger: "blur",
            type: "integer",
          },
        ],
        destination: [
          {
            min: 0,
            max: 200,
            message: "长度小于 200 个字符",
            trigger: "blur",
          },
        ],
        remark: [
          {
            min: 0,
            max: 2000,
            message: "长度小于 2000 个字符",
            trigger: "blur",
          },
        ],
      },
      selectArry: [],
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        tagId: undefined,
        corporationId: undefined,
        companyId: undefined,
        name: "", //关键词
      },
      inline: true,
      tourManage_btn_edit: false, //编辑
      tourManage_btn_add: false, //添加
      vehicleInfo_btn_apply: false,
      allCompanies: {},
      allCompaniesArr: [],
      textMap: {
        update: "编辑",
        create: "创建",
      },
      tableKey: 0,
      departureDialogVisible: false,
      arrivalDialogVisible: false,
      good_btn_add: false, //旅游添加
      good_btn_update: false, //旅游编辑
      good_btn_upstatus: false, //旅游上下架
      good_btn_del: false, //旅游删除
      companys_list: [], //门店列表
      branchCompany_list: [], //公司列表
    };
  },
  created() {
    this.getList();
    this.getAllLabelList(); //获取全部标签
    this.good_btn_add = this.elements["good:btn_add"]; //旅游添加
    this.good_btn_update = this.elements["good:btn_update"]; //旅游编辑
    this.good_btn_upstatus = this.elements["good:btn_upstatus"]; //旅游上下架
    this.good_btn_del = this.elements["good:btn_del"]; //旅游删除
    this.get_all_companys(); //门店列表
    this.get_all_branchCompany(); //公司列表
  },
  computed: {
    ...mapGetters(["elements", "belong2Type", "vehicleStatus"]),
    provinceRegions() {
      return getSonRegionByCodes(1);
    },
    cityRegions() {
      if (!this.$utils.isInteger(this.form.addrProvince)) {
        return null;
      }
      return getSonRegionByCodes(this.form.addrProvince);
    },
    townRegions() {
      if (!this.$utils.isInteger(this.form.addrCity)) {
        return null;
      }
      return getSonRegionByCodes(this.form.addrCity);
    },
    cityRegions4Query() {
      if (!this.$utils.isInteger(this.listQuery.addrProvince)) {
        return null;
      }
      return getSonRegionByCodes(this.listQuery.addrProvince);
    },
    townRegions4Query() {
      if (!this.$utils.isInteger(this.listQuery.addrCity)) {
        return null;
      }
      return getSonRegionByCodes(this.listQuery.addrCity);
    },
    getHeaderWithToken() {
      return { Authorization: getToken() };
    },
    getSelectedAccItemStr() {
      if (!this.$utils.isEmpty(this.form4Apply.selectedAccItem)) {
        let rsStr = "";
        for (let key in this.form4Apply.selectedAccItem) {
          rsStr =
            rsStr +
            this.$refs.accItemSelector.getNameById(key) +
            " : " +
            this.form4Apply.selectedAccItem[key] +
            "\n";
        }
        return rsStr;
      }
      return "";
    },
    getUnkownBrandCode: () => VEHICLE_CONSTANT_BRAND_CODE_UNKOWN,
    getCurBookedInfo: function () {
      if (
        !this.$utils.isEmpty(this.curBookedInfo3Month) &&
        this.curBookedInfo3Month.length > 0
      ) {
        let rs = {};
        for (let index in this.curBookedInfo3Month) {
          rs[
            this.curBookedInfo3Month[index].yearMonth
          ] = this.curBookedInfo3Month[index].bookedDate;
        }
        return rs;
      }
      return undefined;
    },
    bookDateRange: {
      get: function () {
        let startDate = undefined;
        let endDate = undefined;
        if (
          this.$utils.isString(this.listQuery.bookedStartDate) &&
          this.listQuery.bookedStartDate !== ""
        ) {
          startDate = toEast8Date(this.listQuery.bookedStartDate);
        }
        if (
          this.$utils.isString(this.listQuery.bookedEndDate) &&
          this.listQuery.bookedEndDate !== ""
        ) {
          endDate = toEast8Date(this.listQuery.bookedEndDate);
        }
        return [startDate, endDate];
      },
      set: function ([startDate, endDate]) {
        if (this.$utils.isDate(startDate)) {
          this.listQuery.bookedStartDate = formatDate(startDate, "yyyy-MM-dd");
        } else {
          this.listQuery.bookedStartDate = undefined;
        }
        if (this.$utils.isDate(endDate)) {
          this.listQuery.bookedEndDate = formatDate(endDate, "yyyy-MM-dd");
        } else {
          this.listQuery.bookedEndDate = undefined;
        }
      },
    },
    notBookDateRange: {
      get: function () {
        let startDate = undefined;
        let endDate = undefined;
        if (
          this.$utils.isString(this.listQuery.notBookedStartDate) &&
          this.listQuery.notBookedStartDate !== ""
        ) {
          startDate = toEast8Date(this.listQuery.notBookedStartDate);
        }
        if (
          this.$utils.isString(this.listQuery.notBookedEndDate) &&
          this.listQuery.notBookedEndDate !== ""
        ) {
          endDate = toEast8Date(this.listQuery.notBookedEndDate);
        }
        return [startDate, endDate];
      },
      set: function ([startDate, endDate]) {
        if (this.$utils.isDate(startDate)) {
          this.listQuery.notBookedStartDate = formatDate(
            startDate,
            "yyyy-MM-dd"
          );
        } else {
          this.listQuery.notBookedStartDate = undefined;
        }
        if (this.$utils.isDate(endDate)) {
          this.listQuery.notBookedEndDate = formatDate(endDate, "yyyy-MM-dd");
        } else {
          this.listQuery.notBookedEndDate = undefined;
        }
      },
    },
    bookDateRange4Apply: {
      get: function () {
        let startDate = undefined;
        let endDate = undefined;
        if (
          this.$utils.isString(this.form4Apply.bookStartDate) &&
          this.form4Apply.bookStartDate !== ""
        ) {
          startDate = toEast8Date(this.form4Apply.bookStartDate);
        }
        if (
          this.$utils.isString(this.form4Apply.bookEndDate) &&
          this.form4Apply.bookEndDate !== ""
        ) {
          endDate = toEast8Date(this.form4Apply.bookEndDate);
        }
        return [startDate, endDate];
      },
      set: function ([startDate, endDate]) {
        if (this.$utils.isDate(startDate)) {
          this.form4Apply.bookStartDate = formatDate(startDate, "yyyy-MM-dd");
        } else {
          this.form4Apply.bookStartDate = undefined;
        }
        if (this.$utils.isDate(endDate)) {
          this.form4Apply.bookEndDate = formatDate(endDate, "yyyy-MM-dd");
        } else {
          this.form4Apply.bookEndDate = undefined;
        }
      },
    },
  },
  methods: {
    /**
     * 获取全部旅游标签
     * */
    getAllLabelList() {
      getAllTourTag().then((response) => {
        this.allLabelList = response.data;
      });
    },
    /**
     * 添加
     * */
    handleCreate() {
      this.resetTemp();
      this.oneTourRow = {};
      this.modalTitle = "创建";
      this.oneTourDialogVisible = true;
    },
    /**
     * 操作-删除
     * */
    deleteHandler(row) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        goodDel(row.id).then((response) => {
          if (response.status === 200) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
            this.oneTourDialogVisible = false;
            this.getList();
          } else {
            this.$notify({
              title: "删除失败",
              message: rsCode.msg[response.code]
                ? rsCode.msg[response.code]
                : "操作失败！",
              type: "error",
              duration: 2000,
            });
          }
        });
      });
    },
    /**
     * 上架、下架  参数 id status 1-上架；2-下架  post
     */
    upStatus(row) {
      let params = {
        id: row.id,
        status: row.status == 1 ? 2 : 1,
      };
      upStatusChange(params).then((response) => {
        if (response.status === 200) {
          this.$notify({
            title: "成功",
            message: "成功",
            type: "success",
            duration: 2000,
          });
          this.oneTourDialogVisible = false;
          this.getList();
        } else {
          this.$notify({
            title: "失败",
            message: rsCode.msg[response.code]
              ? rsCode.msg[response.code]
              : "操作失败！",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    /**
     * 编辑
     * */
    handleUpdate(row) {
      this.modalTitle = "编辑";
      this.oneTourRow = row;
      this.oneTourDialogVisible = true;
    },
    /**
     * 下架
     * */
    undercarriageHandler(row) {
      // open dialog
      this.departureDialogVisible = true;
      this.clearDepartureForm();
      let that = this;
      let selectArry = [];
      this.allCompaniesArr.map(function (item) {
        item.value = item.name;
        selectArry.push(item);
      });
      this.departureForm.mileage = row.mileage;
      this.departureForm.expectArrivalBranchCompanyId = row.subordinateBranch;
      this.departureForm.departureBranchCompanyId = row.subordinateBranch;
      selectArry.map(function (iitem) {
        if (row.subordinateBranch == iitem.id) {
          that.departureForm.departureBranchCompanyName = iitem.name;
          that.departureForm.expectArrivalBranchCompanyName = iitem.name;
        }
      });
      this.departureForm.vehicleId = row.id;
      this.departureForm.numberPlate = row.numberPlate;
      this.departureForm.departureDate = Date();
    },
    /**
     * 旅游modal传递回来的数据
     * */
    oneTourDialogEvent(e) {
      this.oneTourDialogVisible = false;
      if (!e) {
        //关闭编辑
        this.oneTourDialogVisible = e;
      } else if (e) {
        //编辑成功-重新加载列表
        this.getList();
      }
    },
    clearDepartureForm() {
      this.departureForm = {
        vehicleId: null,
        numberPlate: null,
        departureBranchCompanyName: "",
        departureDate: null,
        departureBranchCompanyId: null,
        use: null,
        user: null,
        userTel: null,
        checkMan: null,
        checkManTel: null,
        expectArrivalBranchCompanyId: null,
        expectArrivalBranchCompanyName: "",
        mileage: null,
      };
    },
    departureVehicleHandler() {
      console.log(this.departureForm);
      if (
        this.departureForm.expectArrivalBranchCompanyName == "全部" ||
        this.departureForm.expectArrivalBranchCompanyName == ""
      ) {
        this.departureForm.expectArrivalBranchCompanyId = undefined;
      }
      if (
        this.departureForm.departureBranchCompanyName == "全部" ||
        this.departureForm.departureBranchCompanyName == ""
      ) {
        this.departureForm.departureBranchCompanyId = undefined;
      }
      departureVehicle(this.departureForm).then((response) => {
        if (response.code === rsCode.RS_CODE_SUC) {
          this.departureDialogVisible = false;
          this.$notify({
            title: "成功",
            message: "出车成功",
            type: "success",
            duration: 2000,
          });
          this.getList();
        } else {
          this.$notify({
            title: "失败",
            message: rsCode.msg[response.code]
              ? rsCode.msg[response.code]
              : "操作失败！",
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    getAllBelong2Type: function () {
      return this.belong2Type;
    },
    getBelongToNameStr(row) {
      if (!this.$utils.isInteger(row.belongTo)) {
        return undefined;
      }
      if (BELONG_TO_TYPE_OWN === row.belongTo) {
        return this.belong2Type[row.belongTo].val;
      }
      if (
        this.$utils.isString(row.belongToName) &&
        !this.$utils.isEmpty(row.belongToName)
      ) {
        return row.belongToName;
      }
      return undefined;
    },
    showImgDialog(drivingLicensePath) {
      this.licenceSrcUrl = this.getDrivingLicenseUrl(drivingLicensePath);
      this.dialogForm4LicenceVisible = true;
    },
    getDrivingLicenseUrl(drivingLicensePath) {
      return (
        process.env.BASE_API +
        "/vehicle/vehicleInfo/download/drivingLicense?realFileRelPath=" +
        encodeURI(drivingLicensePath)
      );
    },
    handleAvatarSuccess(res, file) {
      this.form.drivingLicensePath = res.data;
      this.showLoadingBody = false;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 10MB!");
      }
      this.showLoadingBody = true;
      return isJPG && isLt2M;
    },
    accItemSelected(selected) {
      this.form4Apply.selectedAccItem = selected;
    },
    accItemClear() {
      this.form4Apply.selectedAccItem = undefined;
    },
    handleAccItemSelect() {
      this.$refs.accItemSelector.show();
    },
    integerValidator: function () {
      return {
        validator: (rule, value, callback) => {
          if (this.$utils.isUndefined(value) || this.$utils.isNull()) {
            return callback();
          }
          if (!this.$utils.isInteger(value)) {
            return callback(new Error("必须为整数"));
          }
          if (value < 1 || value > 9999999999) {
            return callback(new Error("编码合法范围：[1 - 9999999999]"));
          }
          callback();
        },
        trigger: "blur",
      };
    },
    fillDateRange2Object: function (
      realBelong,
      rangePropName,
      startDatePropName,
      endDatePropName
    ) {
      if (
        this.$utils.isEmpty(realBelong) ||
        !this.$utils.isArray(realBelong[rangePropName])
      ) {
        return realBelong;
      }
      let belong = this.$utils.clone(realBelong, true);
      let [startDate, endDate] = belong[rangePropName];
      if (this.$utils.isDate(startDate)) {
        belong[startDatePropName] = formatDate(
          startDate,
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        belong[startDatePropName] = undefined;
      }
      if (this.$utils.isDate(endDate)) {
        belong[endDatePropName] = formatDate(endDate, "yyyy-MM-dd hh:mm:ss");
      } else {
        belong[endDatePropName] = undefined;
      }
      belong[rangePropName] = undefined;
      return belong;
    },
    fillDates2Range: function (
      belong,
      rangePropName,
      startDatePropName,
      endDatePropName
    ) {
      if (
        this.$utils.isEmpty(belong) ||
        !this.$utils.isString(belong[startDatePropName]) ||
        belong[startDatePropName] === "" ||
        !this.$utils.isString(belong[endDatePropName]) ||
        belong[endDatePropName] === ""
      ) {
        return;
      }
      let [startDateStr, endDateStr] = [
        belong[startDatePropName],
        belong[endDatePropName],
      ];
      belong[rangePropName] = [
        toEast8Date(startDateStr),
        toEast8Date(endDateStr),
      ];
    },
    changeDate4BookInfo: function (date) {
      getBookedInfo(this.form4BookInfo.vehicle, date).then((response) => {
        this.curBookedInfo = response.data;
      });
    },
    checkBookDate: function (time) {
      let nowDate = newEast8Date();
      if (
        this.$utils.toDateString(time, "yyyy-MM-dd") <
        this.$utils.toDateString(nowDate, "yyyy-MM-dd")
      ) {
        return true;
      }
      if (nowDate.setMonth(nowDate.getMonth() + 2) < time) {
        //预定范围两个月内
        return true;
      }
      let curYearMonth = formatDate(time, "yyyy-MM");
      if (
        !this.$utils.isEmpty(this.getCurBookedInfo) &&
        this.$utils.isInteger(this.getCurBookedInfo[curYearMonth])
      ) {
        let int4BitMap = this.getCurBookedInfo[curYearMonth];
        let dayOfMonth = time.getDate();
        return (int4BitMap & (1 << (dayOfMonth - 1))) != 0;
      }
      return false;
    },
    checkIfRuning: (vehicle) =>
      vehicle.status === VEHICLE_CONSTANT_STATUS_NORMAL,
    getVehicleStatus: function (code) {
      return this.vehicleStatus[code].val;
    },
    getAllVehicleStatus: function () {
      return this.vehicleStatus;
    },
    getBrand: function (code) {
      if (
        !this.$utils.isInteger(code) ||
        code == VEHICLE_CONSTANT_BRAND_CODE_UNKOWN
      ) {
        return "未知";
      }
      return getConstantByTypeAndCode(VEHICLE_CONSTANT_VEHICLE_BRAND, code).val;
    },
    getAllBranch: () => {
      return getConstantListByType(VEHICLE_CONSTANT_VEHICLE_BRAND);
    },
    getUseType: function (code) {
      if (
        !this.$utils.isInteger(code) ||
        code == VEHICLE_CONSTANT_USE_TYPE_UNKOWN
      ) {
        return "未知";
      }
      return getConstantByTypeAndCode(VEHICLE_CONSTANT_VEHICLE_USE, code).val;
    },
    getAllUseType: () => {
      return getConstantListByType(VEHICLE_CONSTANT_VEHICLE_USE);
    },
    /**
     * 获取旅游列表
     * */
    getList() {
      this.listLoading = true;
      page(this.listQuery).then((response) => {
        let totalCountRs = undefined;
        let listRs = undefined;
        if (
          !this.$utils.isEmpty(response.data.data) &&
          this.$utils.isInteger(response.data.totalCount)
        ) {
          listRs = response.data.data;
          totalCountRs = response.data.totalCount;
          listRs.map(function (item) {
            item.visible2 = false;
          });
        }
        this.listLoading = false;
        this.list = listRs;
        this.total = totalCountRs;
      });
    },
    getAddrStr(branchCompany) {
      let regions = getRegionByCodes([
        branchCompany.addrProvince,
        branchCompany.addrCity,
        branchCompany.addrTown,
      ]);
      let address = "";
      for (let i = 0; i < regions.length; i++) {
        address += regions[i].name + " ";
      }
      return address;
      //        return regions[0].name + ' ' + regions[1].name + ' ' + regions[2].name + ' ';
    },
    clear_handleFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
        tagId: undefined,
        corporationId: undefined,
        companyId: undefined,
        name: "", //关键词
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.getList();
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    /**
     * 操作-申请预定
     * */
    handleApply(row) {
      this.resetTemp4Apply();
      let that = this;
      let selectArry = [];
      this.allCompaniesArr.map(function (item) {
        item.value = item.name;
        selectArry.push(item);
      });
      this.form4Apply.liftCompany = row.subordinateBranch;
      selectArry.map(function (iitem) {
        if (row.subordinateBranch == iitem.id) {
          that.form4Apply.state3 = iitem.name;
        }
      });
      this.form4Apply.vehicle = row.id;
      getBookedInfoIn2Month(row.id).then((response) => {
        this.curBookedInfo3Month = response.data;
        this.dialogStatus = "apply";
        this.dialogForm4ApplyVisible = true;
      });
    },
    handleBookInfo(row) {
      this.$refs.bookInfoViewer.handleBookInfo(row.id);
    },
    create(formName) {
      const set = this.$refs;
      if (!this.form.state2 || this.form.state2 == "全部") {
        this.form.subordinateBranch = undefined;
        this.$notify({
          title: "失败",
          message: "请选择分公司",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      set[formName].validate((valid) => {
        if (valid) {
          let formTemp = this.fillDateRange2Object(
            this.form,
            "insuranceDateRange4form",
            "insuranceStartDate",
            "insuranceEndDate"
          );
          convertDate2Str(formTemp);
          addObj(formTemp).then((response) => {
            if (response.code === rsCode.RS_CODE_SUC) {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000,
              });
              this.getList();
            } else {
              this.$notify({
                title: "失败",
                message: rsCode.msg[response.code]
                  ? rsCode.msg[response.code]
                  : "操作失败！",
                type: "error",
                duration: 2000,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.dialogForm4ApplyVisible = false;
      this.$refs[formName].resetFields();
    },
    cancel4Apply(formName) {
      this.dialogForm4ApplyVisible = false;
      this.$refs[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      if (!this.form.state2 || this.form.state2 == "全部") {
        this.form.subordinateBranch = undefined;
        this.$notify({
          title: "失败",
          message: "请选择分公司",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      set[formName].validate((valid) => {
        if (valid) {
          let formTemp = this.fillDateRange2Object(
            this.form,
            "insuranceDateRange4form",
            "insuranceStartDate",
            "insuranceEndDate"
          );
          convertDate2Str(formTemp);
          putObj(formTemp).then((response) => {
            if (response.code === rsCode.RS_CODE_SUC) {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 2000,
              });
              this.getList();
            } else {
              this.$notify({
                title: "失败",
                message: rsCode.msg[response.code]
                  ? rsCode.msg[response.code]
                  : "操作失败！",
                type: "error",
                duration: 2000,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 申请预定-确定
     * @param formName
     */
    apply(formName) {
      if (!this.form4Apply.state3 || this.form4Apply.state3 == "全部") {
        this.form4Apply.liftCompany = undefined;
        this.$notify({
          title: "失败",
          message: "请选择提车分公司",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      if (!this.form4Apply.state4 || this.form4Apply.state4 == "全部") {
        this.form4Apply.retCompany = undefined;
        this.$notify({
          title: "失败",
          message: "请选择还车分公司",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      const set = this.$refs;
      set[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          book(this.form4Apply).then(() => {
            this.dialogForm4ApplyVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "预定成功",
              type: "success",
              duration: 2000,
            });
          });
        } else {
          return false;
        }
      });
    },
    resetTemp() {
      this.form = {
        tagNames: "", //标签
        name: undefined, //旅游名称
        saleCount: undefined, //销量
        stock: undefined, //总数量
      };
    },
    resetTemp4Apply() {
      this.form4Apply = {
        bookStartDate: undefined,
        bookEndDate: undefined,
        state3: "",
        state4: "",
        retCompany: undefined,
        vehicle: undefined,
        selectedAccItem: undefined,
        liftCompany: undefined,
        liftAddr: undefined,
        destination: undefined,
        remark: undefined,
      };
    },
    resetTemp4BookInfo() {
      this.form4BookInfo = {
        selectedMonth: this.$utils.toDateString(newEast8Date(), "yyyy-MM"),
        vehicle: undefined,
      };
    },
    //所有公司
    get_all_companys() {
      company_all_list().then((res) => {
        if (res.status == 200) {
          this.companys_list = res.data;
        }
      });
    },
    //所有门店
    get_all_branchCompany() {
      branchCompany_all_list({ state: 1 }).then((res) => {
        if (res.status == 200) {
          this.branchCompany_list = res.data;
        }
      });
    },
  },
};
</script>
