<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" ref="filter-container">
      <el-form ref="queryForm" :model="listQuery" label-width="100px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="所属地区" prop="zoneId">
              <el-select class="filter-item" v-model="listQuery.zoneId" placeholder="请选择" @change="getProvinceRegions">
                <el-option :key="undefined" label="无" :value="undefined"></el-option>
                <el-option v-for="val in getAllZoneList" :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="所属公司" prop="startCompanyId">
              <el-select class="filter-item" v-model="listQuery.startCompanyId" placeholder="请选择"
                         @change="getAllBranchCompanyChange">
                <el-option :key="undefined" label="无" :value="undefined"></el-option>
                <el-option v-for="val in allBranchCompany" :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-input v-model="listQuery.phone" type="text" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="订单号">
              <el-input v-model="listQuery.no" type="text" placeholder="请输入订单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select class="filter-item" v-model="listQuery.status" placeholder="请选择状态">
                <el-option :key="null" label="无" :value="null"></el-option>
                <el-option :key="2" label="取消" :value="2"></el-option>
                <el-option :key="3" label="待付款" :value="3"></el-option>
                <el-option :key="4" label="待出行" :value="4"></el-option>
                <el-option :key="5" label="出行中" :value="5"></el-option>
                <el-option :key="6" label="已完成" :value="6"></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" type="primary" v-waves icon="delete" @click="clearSearch">清除搜索</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading.body="listLoading"
              border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="ID" width="70">
        <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="订单号/创建时间">
        <template scope="scope">
          <span>{{scope.row.no}}</span><br/>
          <span>{{scope.row.crtTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称">
        <template scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户ID/用户名">
        <template scope="scope">
          <span>{{scope.row.username}}</span>/<span>{{scope.row.telephone}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="报名人数">
        <template scope="scope">
          <span>成人{{scope.row.orderTourDetail.adultNum}}  儿童{{scope.row.orderTourDetail.childNum}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="活动日期">
        <template scope="scope">
          <span>{{dateFormat(scope.row.orderTourDetail.startTime)}}</span>
          -
          <span>{{dateFormat(scope.row.orderTourDetail.endTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="出发公司">
        <template scope="scope">
          <span>{{scope.row.startCompanyName}}</span>
        </template>
      </el-table-column>

      <el-table-column width="110" align="center" label="订单价格">
        <template scope="scope">
          <span>{{scope.row.orderAmount}}</span>
        </template>
      </el-table-column>

      <el-table-column width="110" align="center" label="状态">
        <template scope="scope">
          <span v-if="scope.row.status == '2'">取消</span>
          <span v-if="scope.row.status == '3'">待付款</span>
          <span v-if="scope.row.status == '4'">待出行</span>
          <span v-if="scope.row.status == '5'">出行中</span>
          <span v-if="scope.row.status == '6'">已完成</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="订单详情" fixed="right">
        <template scope="scope">
          <span style="color: #13CE66;cursor: pointer;" @click="handleBuy(scope.row)">订单详情</span>
					<el-button
						size="small"
						v-if="scope.row.status == 3 || scope.row.status == 4"
						class="el-button el-button--text el-button--small"
						@click="handleViolatePrice(scope.row)"
					>取消订单</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>
    <!--订单详情-->
    <tourOrderDetailModal :tourRow="tourRow" :insureDetail="insureDetail" v-if="tourDialogVisible"
                          :tourCostDetail="tourCostDetail"
                          v-on:tourOrderDetailDialogEvent="tourOrderDetailDialogEvent"></tourOrderDetailModal>
  
		<el-dialog title="取消订单" :visible.sync="showDialog">
		  <el-form>
			<el-form-item label="违约金金额:" >
			  <el-input v-model="violateAmount" type="number" @blur="checkViolateAmount()" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item>
				<span class="label-text">实际违约金是{{changeViolateAmount}}元</span>
			</el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
			<el-button @click = "handleCancelDialog()">取 消</el-button>
			<el-button type="primary" @click = "handleConfirm()">确 定</el-button>
		  </div>
		</el-dialog>
	</div>
	
	
		
</template>

<script>
  import Detail from "./detail";//违章查询
  import tourOrderDetailModal from "../modal/tourOrderDetailModal";//租车订单详情
  import {
    page,
		getOrderList,
    getAllBranchCompany,
    getAllBranchCompanyByZoneId,
		calculate,
		getViolatePrice
  } from 'api/order/rentVehicle';
  import {mapGetters} from 'vuex';
  import rsCode from '../../../utils/rsCode';
  import {
    timestamp2Date
  } from 'utils/dateUtils';
  import {
    getAllZone
  } from 'api/base_info/constant/';
  import {
    formatDate
  } from '../../../utils/dateFormattor';

import {getAllCompany } from 'api/base_info/branch_company'
  export default {
    name: 'branchCompanyStock',
    components: {
      Detail,
      tourOrderDetailModal
    },
    data() {
      return {
				showDialog:false,
				changeViolateAmount:null,
				violateAmount: null,
				row:null,
				topAmount: null,
        form: {
          couponAmount: undefined,
          crtHost: undefined,
          crtName: undefined,
          crtTime: undefined,
          crtUser: undefined,
          detailId: undefined,
          endCompanyName: undefined,
          goodsAmount: undefined,
          hasDiscount: undefined,
          hasMemberRight: undefined,
          hasPay: undefined,
          id: undefined,
          name: undefined,
          no: undefined,
          orderAmount: undefined,
          orderOrigin: undefined,
          orderTourDetail: {
            adultNum: undefined,
            childNum: undefined,
            contactEmail: undefined,
            contactMan: undefined,
            contactPhone: undefined,
            costDetail: undefined,
            crtTime: undefined,
            dayNum: undefined,
            endAddr: undefined,
            endTime: undefined,
            goodId: undefined,
            hasInsure: undefined,
            id: undefined,
            isOutside: undefined,
            orderId: undefined,
            siteId: undefined,
            spePriceId: undefined,
            startAddr: undefined,
            startCity: undefined,
            startCityName: undefined,
            startCompanyId: undefined,
            startTime: undefined,
            totalNumber: undefined,
            tourUserIds: undefined,
            updTime: undefined,
            verificationId: undefined
          },
          payOrigin: undefined,
          picture: undefined,
          realAmount: undefined,
          refundStatus: undefined,
          startCompanyName: undefined,
          status: undefined,
          ststusName: undefined,
          telephone: undefined,
          type: undefined,
          updTime: undefined,
          userId: undefined,
          username: undefined,
          vehicleNumberPlat: undefined,
          version: undefined,
        },
        detailVisible: false,
        bannerDialogVisible: false,//添加、编辑弹框
        modalTitle: '订单详情',
        rules: {
          // companyName: [
          //   {
          //     required: true,
          //     message: '请输入用户',
          //     trigger: 'blur'
          //   }
          // ],
        },
        applyState: {
          '-1': {
            key: -1,
            label: '放弃购买'
          },
          0: {
            key: 0,
            label: '申请中'
          },
          1: {
            key: 1,
            label: '确认购买'
          }
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          type: 2,
          no: undefined,
          phone: undefined,
          status: null,
          startTime: undefined,
          endTime: undefined,
          zoneId: undefined,
          startCompanyId: undefined
        },
        tourRow: {},//旅游订单详情-当前行
        //"{"key":"费用明细","val":"","children":[{"key":"成人价格","detail":"￥13800.00/人×1人","val":"￥13800.00"}]}"
        costDetail: {
          key: undefined,
          val: undefined,
          children: [
            {
              key: undefined,
              detail: undefined,
              val: undefined
            }
          ]
        },

        baranchQuery: {
          zoneId: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        btn_del: true,
        btn_buy: true,
        btn_cancel: true,
        allBranchCompany: [],
        tourCostDetail: '',
        insureDetail: '',//保险
        tableKey: 0,
        tourDialogVisible: false,//旅游详情
      }
    },
    created() {
      let t = this;
      let query =  localStorage.getItem("tourOrderInfo");
      this.listQuery.no = this.$route.query.id || null
      if(query !="null" && query){
        let queryJson = JSON.parse(query);
        if(queryJson.page){
          t.listQuery.page = queryJson.page;
        }
        if(queryJson.limit){
          t.listQuery.limit = queryJson.limit;
        }
        if(queryJson.no){
          t.listQuery.no = queryJson.no;
        }
        if(queryJson.type){
          t.listQuery.type = queryJson.type;
        }
        if(queryJson.startTime){
          t.listQuery.startTime = queryJson.startTime;
        }
        if(queryJson.endTime){
          t.listQuery.endTime = queryJson.endTime;
        }
        if(queryJson.status){
          t.listQuery.status = queryJson.status;
        }
        if(queryJson.phone){
          t.listQuery.phone = queryJson.phone;
        }
      }
      this.getList();
      getAllCompany(codeAndBranchCompany => {
        this.allBranchCompany = codeAndBranchCompany;
      });
      this.btn_del = this.elements['branchCompany/stockApply:btn_delete'];
    },
    computed: {
      ...mapGetters([
        'elements'
      ]),
      provinceRegions() {
        return getSonRegionByCodes(1);
      },
      //获取大区列表
      getAllZoneList() {
        return getAllZone();
      },
      cityRegions() {
        if (!this.$utils.isInteger(this.form.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrProvince);
      }
    },
    methods: {
      /**
       * 操作-查看详情按钮，显示详情弹框
       */
      detailInquiry(row) {
        this.currentRow = row;
        this.detailVisible = true;
      },
      /**
       * 关闭违章查询弹框
       * */
      detailEvent(params) {
        this.detailVisible = false;
        if (params) {
          console.log(params);
        }
      },
      /**
       * 旅游订单详情弹框关闭
       * */
      tourOrderDetailDialogEvent(e) {
        this.tourDialogVisible = false;
      },
      /**
       * 旅游订单详情
       * @param row
       */
      handleBuy(row) {
        this.tourRow = row;
        this.tourDialogVisible = true;
      },
			/**
			 * 取消订单
			 */
			//取消订单
			cancel(row, changeViolateAmount) {
				let that = this;
				if (changeViolateAmount == null || changeViolateAmount == 0) {
					this.$confirm('此操作将取消该订单, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						let params = {
							cancelReason: '后台取消',
							appUserId: row.userId,
							changeViolateAmount: null
						}
						calculate(row.no, params).then(data => {
							if (data.status == 200) {
								this.$notify({
									title: '成功',
									message: '取消订单成功',
									type: 'success',
									duration: 2000
								})
								this.getList()
							} else {
								this.$notify({
									title: '失败',
									message: '取消订单失败',
									type: 'fail',
									duration: 2000
								})
							}
						})
					})
				} else {
					//   this.$prompt('请输入违约金', '提示', {
					// 	  confirmButtonText: '确定',
					// 	  cancelButtonText: '取消',
					// 	  inputPattern: /^[0-9]*$/,
					// 	  inputErrorMessage: '只能输入数字'
					// }).then(({ value }) => {
					//   this.$message({
					// 	type: 'success',
					// 	message: '你的邮箱是: ' + value
					//   });
					// }).catch(() => {
					//   this.$message({
					// 	type: 'info',
					// 	message: '取消输入'
					//   });       
					// });
					that.showDialog = true
					that.changeViolateAmount = changeViolateAmount
					that.violateAmount = changeViolateAmount
					that.row = row
				}
				
			},
			checkViolateAmount() {
				console.log(this.topAmount)
				console.log(this.violateAmount)
				if(this.topAmount < this.violateAmount) {
					this.$notify({
						title: '失败',
						message: '违约金额不能大于最高限制金额' + this.topAmount,
						type: 'fail',
						duration: 2000
					})
				}
			},
			handleConfirm() {
				let params = {
					cancelReason: '后台取消',
					appUserId: this.row.userId,
					changeViolateAmount: this.violateAmount
				}
				calculate(this.row.no, params).then(data => {
					if (data.status == 200) {
						this.$notify({
							title: '成功',
							message: '取消订单成功',
							type: 'success',
							duration: 2000
						})
						this.showDialog = false
						this.getList()
					} else {
						this.$notify({
							title: '失败',
							message: '取消订单失败',
							type: 'fail',
							duration: 2000
						})
					}
				})
			},
			handleCancelDialog() {
				this.showDialog = false
			},
			handleViolatePrice(row) {
				let that = this;
				let params = {
					cancelReason: '后台取消',
					appUserId: row.userId
				}
				getViolatePrice(row.no).then(data => {
					if (data.status == 200) {
						that.topAmount = data.data.topAmount;
						that.cancel(row, data.data.cutAmount);
					} else {
						this.$notify({
							title: '失败',
							message: '获取违约金失败',
							type: 'success',
							duration: 2000
						})
					}
				})
			},
			
      getProvinceRegions(item) {
        this.listQuery.zoneId = item
        this.baranchQuery.zoneId = item
        // this.listQuery.startCompanyId = undefined;
        // getAllBranchCompanyByZoneId(this.baranchQuery)
        //   .then(response => {
        //     this.allBranchCompany = response.data;
        //   })
      },
      getAllBranchCompanyChange(item) {
        this.listQuery.startCompanyId = item
      },
      handleCancel(row) {
        this.$confirm('此操作将放弃购买, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            cancelApply(row.id)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '操作成功',
                  type: 'success',
                  duration: 2000
                });
                this.getList();
              });
          });
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delObj(row.id)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                });
                const index = this.list.indexOf(row);
                this.list.splice(index, 1);
              });
          });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.$refs.queryForm.validate(valid => {
          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      clearSearch() {
        this.listQuery = {
          page: 1,
          limit: 20,
          type: 2,
          no: null,
          phone: null,
          status: null,
          startTime: undefined,
          endTime: undefined,
          zoneId: undefined,
          startCompanyId: undefined

        }
        this.getList()
      },
      getList() {
        this.listLoading = true;
        console.log(this.listQuery)
        // if(this.listQuery.startTime){
        //   this.listQuery.startTime = this.listQuery.startTime.getTime();
        // }
        // if(this.listQuery.endTime){
        //   this.listQuery.endTime = this.listQuery.endTime.getTime();
        // }
        if(this.listQuery){
          localStorage.setItem("tourOrderInfo", JSON.stringify(this.listQuery));
        }
        getOrderList(this.listQuery)
          .then(response => {
            this.list = response.data.data;
            this.total = response.data.totalCount;
            this.listLoading = false;
          })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      dateFormat(timestamp) {
        let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        return formatDate(date, 'yyyy-MM-dd');
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      }
    }
  }
</script>
<style>
  .label-text {
    margin-left: 10px;
    margin-right: 20px;
  }

  .label-title {
    margin-top: 10px;
  }

  .orderDetail tr td {
    width: 500px;
    text-align: center;
    border: 0.0625rem solid;
    margin-left: 100px;
    margin-right: 100px;
  }

  .label-value {
    margin-left: 80px;
    margin-right: 100px;
  }
</style>
