<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div v-if="!oneTypeDialogVisible">
      <div class="filter-container" ref="filter-container">
        <el-form :inline="inline" ref="queryForm" :model="listQuery" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="房车品牌">
                <el-select class="filter-item" v-model="listQuery.vehicleType" placeholder="请选择房车品牌">
                  <el-option :key="undefined" label="无" :value="undefined"></el-option>
                  <el-option v-for="(val, key, index) in brandlist " :key="val.id" :label="val.name"
                             :value="val.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房车名称">
                <el-input v-model.number="listQuery.vehicleName" placeholder="请输入房车名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="乘卧数量">
                <el-select class="filter-item" v-model="listQuery.takeALieTheNumber" placeholder="请选择乘卧数量">
                  <el-option :key="undefined" label="无" :value="undefined"></el-option>
                  <el-option v-for="(val, key, index) in numberList " :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="search" @click="handleFilter">搜索</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate"
                   type="primary" icon="edit" v-if="vehicleTypeList_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 align="center" label="车型名称/价格">
          <template scope="scope">
            <img :src="scope.row.picture" style="width: 30px;"/>
            <span>{{scope.row.name}}</span><span style="color:red;">￥{{scope.row.price}}</span>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center" label="乘卧数量">
          <template scope="scope">
            <span>{{scope.row.numberName}}</span>
          </template>
        </el-table-column>

        <el-table-column  align="center" label="品牌">
          <template scope="scope">
            <span>{{scope.row.brandName}}</span>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center" label="关键标签">
          <template scope="scope">
            <span>{{scope.row.keyword}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="总数量">
          <template scope="scope">
            <span>{{scope.row.sum}}</span>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" label="可租借数量">
          <template scope="scope">
            <span>{{scope.row.leasableQuantity}}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="排序">
          <template scope="scope">
            <el-button size="mini" type="text" @click="clickRank(scope.row)">{{scope.row.sort?scope.row.sort:0}}</el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" width="200" label="操作" fixed="right">
          <template scope="scope">
            <el-button size="small"  class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">{{vehicleTypeList_btn_edit?'编辑':'查看'}}
            </el-button>
            <el-button size="small" class="el-button el-button--text el-button--small" style="color: #6ce26c;" v-if="scope.row.status==2|| scope.row.status==0" @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" @click="upStatus(scope.row)">下架
            </el-button>
						 <el-button  class="el-button el-button--text el-button--small" style="color:#1d90e6;" size="small" @click="handlerAppShow(scope.row)" v-if="scope.row.appShow==1">APP展示</el-button>
						 <el-button  class="el-button el-button--text el-button--small" style="color:#1d90e6;" size="small" @click="handlerAppShow(scope.row)" v-if="scope.row.appShow==0">APP不展示</el-button>
            <el-button  class="el-button el-button--text el-button--small" style="color:red;" size="small" @click="deleteHandler(scope.row)" v-if="vehicleTypeList_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>
    <!-- 车型编辑 -->
    <oneType v-if="oneTypeDialogVisible" :oneRow="oneRow" :vehicleTypeList_btn_edit="vehicleTypeList_btn_edit" :title="modalTitle" v-on:oneDialogEvent = "oneDialogEvent" :brandlist="brandlist" :numberList="numberList"></oneType>

    <!-- 排序 modal弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="rankDialogVisible">
      <el-form :model="labelForm" ref="labelForm" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="排序" prop="rank">
              <el-input v-model="labelForm.sort" placeholder="请输入排序值"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button type="primary" @click="updateParentLabelRank('labelForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import oneType from './modal/oneType'// 车型
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框

  import {
    formatDate
  } from 'utils/dateFormattor';

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

  import rsCode from '../../utils/rsCode';

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

  import {
    page,
    getOneGoodsById,
    delVehicleModel,
    getLabelList,
    getLabelByParentId,
    upStatusChange,
    updateVehicleModel,
		updateAppShow
  } from 'api/vehicleType';

  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,
      oneType
    },
    data() {
      return {
        brandlist: [],//全部品牌
        numberList: [],//全部乘卧数量
        modalTitle: "创建",
        BASE_API: process.env.BASE_API,
        oneTypeDialogVisible: false,//添加、编辑弹框
        showLoadingBody: false,
        form: {
          tagNames:"",//标签
          name: undefined,//旅游名称
          saleCount: undefined,//销量
          stock: undefined,//总数量
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          vehicleName: undefined,//房车名称
          vehicleType: undefined,//房车型号
          takeALieTheNumber: undefined,//乘卧数量
          pathType:1
        },
        inline: true,
        vehicleInfo_btn_apply: false,
        allCompanies: {},
        allCompaniesArr: [],
        textMap: {
          update: '编辑',
          create: '创建'
        },
        labelForm:{},
        tableKey: 0,
        departureDialogVisible: false,
        arrivalDialogVisible: false,
        vehicleTypeList_btn_add: false,//添加
        vehicleTypeList_btn_edit: false,//编辑
        vehicleTypeList_btn_del: false,//删除
        rankDialogVisible: false//排序
      }
    },
    created() {
      this.getList();
      this.getNumberList();//获取全部乘卧数量
      this.getLabels();//获取全部品牌标签
      this.vehicleTypeList_btn_add=this.elements['vehicleTypeList:btn_add'];//添加
      this.vehicleTypeList_btn_edit=this.elements['vehicleTypeList:btn_edit'];//编辑
      this.vehicleTypeList_btn_del=this.elements['vehicleTypeList:btn_del'];//删除
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ])
    },
    methods: {
      /**
       * 添加
       * */
      handleCreate() {
        this.modalTitle = '创建';
        this.oneRow = {};
        this.oneTypeDialogVisible = true;
      },
      /**
       * 上架、下架  参数 id status 1-上架；0-下架  post
       */
      upStatus(row){
        let params = {
          id: row.id,
          status: row.status==1?0:1
        };
        upStatusChange(params).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          } else {
            this.$notify({
              title: '失败',
              message: '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
			/**
			 * 是否在App展示
			 * @param {Object} row
			 */
			handlerAppShow(row) {
				var text = "";
				if (row.appShow == 0) {
					 text = "确定设置为在App展示吗?";
				} else {
					text = "确定设置为不在App展示吗?";
				}
				var status = row.appShow == 0 ? 1 : 0;
				var param = {
					"id" : row.id,
					"appShow" : status
				}
        this.$confirm(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateAppShow(param).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '设置成功',
                type: 'success',
                duration: 2000
              });
              this.bannerDialogVisible = false;
              this.getList();
            } else {
              this.$notify({
                title: '设置失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })
      },
      /**
       * 删除
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delVehicleModel(row.id).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.bannerDialogVisible = false;
              this.getList();
            } else {
              this.$notify({
                title: '删除失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })
      },
      /**
       * 弹框-取消
       * */
      cancelHandel(){
        this.rankDialogVisible = false;
      },
      /**
       * 编辑
       * */
      handleUpdate(row) {
        this.modalTitle = '编辑';
        this.oneRow = row;
        this.oneTypeDialogVisible = true;
      },
      /**
       * 排序点击事件
       * */
      clickRank(row){
        this.modalTitle = "编辑";
        this.labelForm = {sort: row.sort, id: row.id};
//        this.labelForm.rank = this.labelForm.rank + "";
        this.rankDialogVisible = true;
      },
      /**
       * 编辑一级标签排序
       * */
      updateParentLabelRank(formName){
        const set = this.$refs;
        let params = {id: this.labelForm.id, sort: this.labelForm.sort};
          updateVehicleModel(params).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              });
              this.rankDialogVisible = false;
              this.getList();
            } else {
              this.$notify({
                title: '编辑失败',
                message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
        });
      },
      /**
       * 下架
       * */
      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传递回来的数据
       * */
      oneDialogEvent(e){
        this.oneTypeDialogVisible = false;
        if(e){
          //编辑成功-重新加载列表
          this.getList();
        }
      },
      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;
      },
      /*
      * 获取全部品牌标签
      * */
      getLabels(){
        getLabelByParentId(1).then(response => {
          this.brandlist = response.data;
        });
      },
      /**
       * 获取全部乘卧数量
       * */
      getNumberList(){
        getLabelByParentId(14).then(response => {
          this.numberList = response.data;
        });
      },
      /**
       * 获取车型列表
       * */
      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)) {
            response.data.data.map(function(item){
              let arr = item.picture.split(",");
              item.picture = arr?arr[0]: "";
              item.keyword = item.keyword.replace(/\,/g,"|");
              item.brand = JSON.parse(item.brand);
              item.number = JSON.parse(item.number);
              item.visible2 = false;
            });
            listRs = response.data.data;
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })

      },
      getAddrStr(branchCompany) {
        let regions = getRegionByCodes([branchCompany.addrProvince, branchCompany.addrCity, branchCompany.addrTown]);
        return regions[0].name + ' ' + regions[1].name + ' ' + regions[2].name + ' ';
      },
      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
        };
      }
    }
  }
</script>
