<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代理商" prop="deptId" v-if="userName == 'admin' && !deptId">
        <el-select
          v-model="queryParams.deptId"
          filterable
          placeholder="选择代理商"
          style="width: 120px"
          clearable>
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="运营区" prop="areaId" v-if="userName == 'admin'  && !deptId">
        <el-select v-model="queryParams.areaId" filterable placeholder="请选择运营区" clearable>
          <el-option
            v-for="item in areaOptions"
            :key="item.areaId"
            :label="item.areaName"
            :value="item.areaId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备SN" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="vehicleNum">
        <el-input
          v-model="queryParams.vehicleNum"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.et_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.et_pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="订单id" align="center" prop="orderId" />-->
      <el-table-column label="区域" align="center" prop="area" />
      <el-table-column label="订单信息" align="center" width="270">
        <template slot-scope="scope">
          <div>
            <span>订单号: {{ scope.row.orderNo }}</span> <!-- 显示订单号 -->
            <br> <!-- 换行 -->
            <router-link :to="'/user/user/userName/index/' + scope.row.userName" class="link-type">
              <span >{{scope.row.realName? scope.row.realName+':':''}}{{ scope.row.userName }}</span>
            </router-link>
            <br> <!-- 换行 -->
            <span>时长: {{ formatDuration(scope.row) }}</span>
            <br> <!-- 换行 -->
            <span>距离: {{ formatDistance(scope.row) }}</span>
          </div>
        </template>
      </el-table-column>

      <!--      <el-table-column label="订单信息" align="center" width="150">-->
<!--        <template slot-scope="scope">-->
<!--          <div>-->
<!--            <span>{{ scope.row.orderNo }}</span> &lt;!&ndash; 显示订单号 &ndash;&gt;-->
<!--            <br> &lt;!&ndash; 换行 &ndash;&gt;-->
<!--            <router-link :to="'/user/user/userName/index/' + scope.row.userName" class="link-type">-->
<!--              <span>{{ scope.row.userName }}</span> &lt;!&ndash; 显示用户名 &ndash;&gt;-->
<!--            </router-link>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="订单号" align="center" prop="orderNo" width="120"/>-->
<!--      <el-table-column label="用户" align="center" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <router-link :to="'/user/user/userName/index/' + scope.row.userName" class="link-type">-->
<!--            <span>{{ scope.row.userName }}</span>-->
<!--          </router-link>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="设备信息" align="center" width="120">
        <template slot-scope="scope">
          <div>
            <router-link :to="'/system/device/sn/index/' + scope.row.sn" class="link-type">
              <span>SN: {{ scope.row.sn }}</span>
            </router-link>
            <br />
            <router-link :to="'/system/device/vehicleNum/index/' + (scope.row.vehicleNum || '无')" class="link-type">
              <span>车牌号: {{ scope.row.vehicleNum || '无' }}</span> <!-- 车牌号为空时显示“无” -->
            </router-link>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column label="设备SN" align="center" prop="sn" >-->
<!--        <template slot-scope="scope">-->
<!--          <router-link :to="'/system/device/sn/index/' + scope.row.sn" class="link-type">-->
<!--            <span>{{ scope.row.sn }}</span>-->
<!--          </router-link>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="车牌号" align="center" prop="vehicleNum" >-->
<!--        <template slot-scope="scope">-->
<!--          <router-link :to="'/system/device/vehicleNum/index/' + scope.row.vehicleNum" class="link-type">-->
<!--            <span>{{ scope.row.vehicleNum }}</span>-->
<!--          </router-link>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态/支付方式" align="center" width="150">
        <template slot-scope="scope">
          <div>
            <dict-tag :options="dict.type.et_order_status" :value="scope.row.status" /> <!-- 显示状态 -->
            <dict-tag :options="dict.type.et_pay_type" :value="scope.row.payType" /> <!-- 显示支付方式 -->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="时间详情" header-align="center" align="left" width="200">
        <template slot-scope="scope">
          <div>
            <span>创建时间：{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span><br />
            <span>开始骑行：{{ parseTime(scope.row.unlockTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span><br />
            <span>结束骑行：{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span><br />
            <span>支付时间：{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>
        </template>
      </el-table-column>

      <!--      <el-table-column label="创建时间/开始骑行" align="center" width="135">-->
<!--        <template slot-scope="scope">-->
<!--          <div>-->
<!--            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span><br />-->
<!--            <span>{{ parseTime(scope.row.unlockTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="结束骑行" align="center" prop="returnTime" width="90">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="支付时间" align="center" prop="payTime" width="90">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="支付方式" align="center" prop="payType" width="80">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.et_pay_type" :value="scope.row.payType"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="金额(元)" align="center" prop="totalFee" width="70"/>-->
      <el-table-column label="费用详情" header-align="center" align="left" width="200">
        <template slot-scope="scope">
<!--          {{scope.row.status}}-->
<!--          <div v-if="scope.row.status == '2'"> &lt;!&ndash; 如果状态是骑行中 &ndash;&gt;-->
<!--            <span>预估金额：{{ calculateEstimateFee(scope.row) }}</span><br />-->
<!--          </div>-->
          <div> <!-- 其他状态下显示费用详情 -->
            <template>
              <span>结算金额：{{ formatFee(calculateSettlementAmount(scope.row)) }}</span><br />
            </template>
            <template v-if="scope.row.appointmentFee > 0">
              <span>预约费：{{ formatFee(scope.row.appointmentFee) }}</span><br />
            </template>
            <template v-if="scope.row.ridingFee > 0">
              <span>骑行费：{{ formatFee(scope.row.ridingFee) }}</span><br />
            </template>
            <template v-if="scope.row.dispatchFee > 0">
              <span>运营区外调度费：{{ formatFee(scope.row.dispatchFee) }}</span><br />
            </template>
            <template v-if="scope.row.manageFee > 0">
              <span>停车点外调度费：{{ formatFee(scope.row.manageFee) }}</span><br />
            </template>
            <template v-if="scope.row.payFee > 0">
              <span>订单金额：{{ formatFee(scope.row.payFee) }}</span><br />
            </template>
            <template v-if="scope.row.totalRefundFee > 0">
        <span>退款金额：
          <span style="font-weight: bold;color: red">{{ formatFee(scope.row.totalRefundFee) }}</span>
        </span><br />
            </template>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="mark" width="140"/>
<!--      <el-table-column label="交易金额" align="center" prop="amount" :formatter="formatAmount"/>-->
      <el-table-column label="手续费" align="center" prop="handlingCharge" :formatter="formatAmount"/>
      <el-table-column label="成本" align="center" prop="cost" :formatter="formatAmount"/>
      <el-table-column label="服务费" align="center" prop="platformServiceFee" :formatter="formatAmount"/>
<!--      <el-table-column label="到账金额" align="center" prop="platformServiceFee" :formatter="formatAmount"/>-->
<!--      <el-table-column label="订单时长" align="center" prop="duration" :formatter="formatDuration"/>-->
<!--      <el-table-column label="距离" align="center" prop="distance" :formatter="formatDistance"/>-->
<!--      <el-table-column label="订单信息" align="center" width="120">-->
<!--        <template slot-scope="scope">-->
<!--          <div>-->
<!--            <span>时长: {{ formatDuration(scope.row) }}</span><br />-->
<!--            <span>距离: {{ formatDistance(scope.row) }}</span>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 1 || scope.row.status == 3"
            icon="el-icon-edit"
            @click="changePrice(scope.row)"
            v-hasPermi="['system:order:edit']"
          >改价</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.status == '5'"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:order:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == '6'"
            icon="el-icon-money"
            @click="toCommunicate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >去沟通</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 1 || scope.row.status == 3"
            icon="el-icon-wallet"
            @click="deduction(scope.row)"
            v-hasPermi="['system:order:edit']"
          >押金抵扣</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 4"
            icon="el-icon-money"
            @click="refund(scope.row)"
            v-hasPermi="['system:order:edit']"
          >退款</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 2"
            icon="el-icon-refresh-left"
            @click="returnVehicle(scope.row)"
            v-hasPermi="['system:order:edit']"
          >辅助还车</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="toLog(scope.row)"
            v-hasPermi="['system:order:log']"
          >日志</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :close-on-click-modal="true" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付订单编号：">{{ form.orderNo }}</el-form-item>
            <el-form-item label="租赁时长：">{{ formatDuration(form) }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁用户：" >{{ form.phonenumber }}</el-form-item>
            <el-form-item label="行驶距离：" >{{ formatDistance(form) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单状态：">{{ formatStatus(form.status) }}</el-form-item>
          </el-col>
        </el-row>
        <h2 style="font-weight: bold;font-size: 18px">设备信息</h2>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号：">{{ form.device.vehicleNum }}</el-form-item>
            <el-form-item label="SN：">{{ form.sn }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MAC：">{{ form.device.mac }}</el-form-item>
            <el-form-item label="运营区域：" >{{ form.area }}</el-form-item>
          </el-col>
        </el-row>
        <h2 style="font-weight: bold;font-size: 18px">行程记录</h2>
        <el-row v-if="form.tripLogs">
          <template v-for="(log, index) in form.tripLogs" >
            <el-row :key="index">
              <el-col :span="12">
                <el-form-item :label="getTypeText(log.type)+'时间：'">
                  {{ log.createTime }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="getTypeText(log.type)+'地点：'">
                  {{ log.longitude }}, {{ log.latitude }}
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-row>
        <!--    显示路径    -->
        <el-row>
          <el-col :span="24">
            <trajectory-map
              v-if="showPlaceSearchMap"
              ref="map"
              :key="key"
              :areaId="form.areaId"
              height="400px"
              :trip-route-str="form.tripRouteStr"
            />
          </el-col>
        </el-row>
        <h2 style="font-weight: bold;font-size: 18px;padding-top: 10px">费用明细</h2>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预约费用：">{{ formatFee(form.appointmentFee) }}</el-form-item>
            <el-form-item label="运营区外调度费：">{{ formatFee(form.dispatchFee) }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="骑行费用：" >{{ formatFee(form.ridingFee) }}</el-form-item>
            <el-form-item label="停车点外调度费：" >{{ formatFee(form.manageFee) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实收：">{{ formatFee(form.payFee) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付方式：">{{ formatType(form.payType) }}</el-form-item>
            <el-form-item label="支付时间：">{{ form.payTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费模板：" >
              <span>
                {{ form.rule.name }}
              </span><br />
                <span>
                {{ form.description }}
              </span><br />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.etRefunds && form.etRefunds.length > 0">
          <el-col :span="24">
            <el-card v-for="(refund, index) in form.etRefunds" :key="index" class="refund-card">
              <span style="font-weight: 700">退款{{index+1}}</span>
              <div class="refund-content">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="预约费退款：">{{ formatFee(refund.appointmentFee) }}</el-form-item>
                    <el-form-item label="运营区外调度费退款：" label-width="100">{{ formatFee(refund.dispatchFee) }}</el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="骑行费用退款：">{{ formatFee(refund.ridingFee) }}</el-form-item>
                    <el-form-item label="停车点外调度费退款：" label-width="100">{{ formatFee(refund.manageFee) }}</el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="退款原因：">{{ refund.reason }}</el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="退款时间：">{{ refund.createTime }}</el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row v-if="form.etRefunds && form.etRefunds.length > 0">
          <el-col :span="12">
            <el-form-item label="结算总费用：">
              {{ formatFee(calculateNetFee()) }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 改价、退款 -->
    <el-dialog :title="title2" :visible.sync="open2" width="600px" append-to-body>
      <el-form ref="form2" :model="form2" label-width="110px">
        <el-col>
          <el-col :span="24">
            <el-form-item label="预约费(元)" prop="appointmentFee">
              <el-input v-model="form2.appointmentFee" placeholder="请输入预约费"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="骑行费(元)" prop="ridingFee">
              <el-input v-model="form2.ridingFee" placeholder="请输入骑行费"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调度费(元)" prop="dispatchFee">
              <el-input v-model="form2.dispatchFee" placeholder="请输入调度费"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="停车点外调度费(元)" prop="manageFee">
              <el-input v-model="form2.manageFee" placeholder="请输入停车点外调度费"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="title2 === '退款'">
            <el-form-item label="原因" prop="reason">
              <el-input v-model="form2.reason" placeholder="请输入停车点外调度费"/>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="title2 === '改价'" type="success" @click="submitChangePrice">确 定</el-button>
        <el-button v-if="title2 === '退款'" type="success" @click="submitRefund">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核" :visible.sync="open3" width="700px" append-to-body>
      <el-form :model="form3" ref="form3" label-width="100px" size="mini">
        <video v-if="form3.videoUrl" :src="form3.videoUrl" controls width="70%" height="auto"></video>
        <p v-else>暂无视频</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="view == true" @click="open3 = false">关 闭</el-button>
        <el-button v-show="view == false" type="success" @click="pass">通 过</el-button>
        <el-button v-show="view == false" type="danger" @click="reject">车辆有损坏</el-button>
      </div>
    </el-dialog>

    <!-- 沟通录音弹窗 -->
    <el-dialog style="margin-top: 10vh !important;" title="沟通" :visible.sync="open4" width="700px" append-to-body>
      <el-form :model="form4" :rules="rules" ref="form4" label-width="100px" size="mini">
        <!--    录音文件    soundRecording -->
        <el-col :span="24">
          <el-form-item label="上传录音" prop="soundRecording" >
            <audio-upload v-model="form4.audioFiles" :limit="5" :file-size="10" :file-type="['mp3', 'wav', 'ogg', 'aac','m4a']" />
          </el-form-item>
        </el-col>
        <!--    扣款金额    确定扣款  deduction -->
        <el-col :span="24">
          <el-form-item label="扣款金额" prop="deductionAmount">
            <el-input v-model="form4.deductionAmount" placeholder="请输入扣款金额" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open4 = false">关 闭</el-button>
        <el-button type="success" @click="confirmDeduction">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listOrder,
    getOrder,
    delOrder,
    addOrder,
    updateOrder,
    changePrice,
    refund,
    returnVehicle,
    deduction, passAudit
  } from '@/api/system/order'
import TrajectoryMap from '@/components/Map/TrajectoryMap'
  import { getArea, optionselect as getAreaOptionselect } from '@/api/system/area'
  import { getFee } from '@/api/system/fee'
  import { listDept2 } from '@/api/system/dept'

export default {
  name: "Order",
  dicts: ['et_order_type', 'et_pay_type', 'et_order_status'],
  components: {TrajectoryMap },
  props: {
    // 用户id
    deptId: {
      type: Number,
      default: null,
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      userName: undefined,
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 通过key重新渲染area-map组件
      key: 0,
      areaOptions: [],
      deptOptions: [],
      // 总条数
      total: 0,
      view: false,
      // 订单表格数据
      orderList: [],
      area: null,
      // 弹出层标题
      title: "",
      title2: "",
      showPlaceSearchMap: false,
      // 是否显示弹出层
      open: false,
      open2: false,
      open3: false,
      open4: false,
      vehicleNum: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        areaId: null,
        area: null,
        orderNo: null,
        type: "1",
        userId: null,
        userName: null,
        deviceMac: null,
        deptId:this.deptId
      },
      // 表单参数
      form: {
        device: {
          vehicleNum: null,
          mac: null
        },
        etRefund: {
          appointmentFee: null,
          ridingFee: null,
          dispatchFee: null,
          manageFee: null,
          reason: null,
          createTime: null
        },
        rule: {
          name: null
        },
        status: null,
        payType: null,
        payFee: null,
        appointmentFee: null,
        tripRouteStr: null,
        vehicleNum: null,
      },
      form2: {
        orderNo: null,
        appointmentFee: null,
        ridingFee: null,
        dispatchFee: null,
        manageFee: null,
        reason: null,
        createTime: null
      },
      form3: {
        orderNo: null,
        appointmentFee: null,
        ridingFee: null,
        dispatchFee: null,
        manageFee: null,
        reason: null,
        createTime: null
      },
      form4: {
        orderNo: null,
        deductionAmount: null,
        audioFiles: []
      },
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户不能为空", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "支付方式不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    console.log("当前用户信息：",this.$store.state.user.name)
    this.userName = this.$store.state.user.name;
    const orderNo = this.$route.params && this.$route.params.orderNo;
    if (orderNo != null) {
      this.queryParams.orderNo = orderNo;
    }
    this.reset();
    this.reset2();
    this.getList();
    this.getAreaList();
    if(this.userName === 'admin'){
      this.getDeptList();
    }
  },
  watch: {
    open(val) {
      if (!val) {
        console.log("========关闭轨迹地图=============")
        this.showPlaceSearchMap = false; // 关闭地图
      } else {
        console.log("========打开轨迹地图=============")
        this.showPlaceSearchMap = true; // 打开地图
      }
    }
  },
  methods: {
    getDeptList() {
      listDept2({ status: "0", pageNum: 1, pageSize: 999 }).then((response) => {
        this.deptOptions = response.rows;
      });
    },
    formatAmount(row, column) {
      const key = column.property;
      return parseFloat(row[key] || 0).toFixed(2);
    },
    confirmDeduction(){
      // 扣款金额 1. 退剩余押金
      this.$refs["form4"].validate(valid => {
        if (valid) {
          console.log("------44444---")
          if (this.form4.orderId != null) {
            this.form4.status = "7";
            updateOrder({
              orderId:this.form4.orderId,
              status:this.form4.status,
              deductionAmount:this.form4.deductionAmount,
              audioFiles: this.form4.audioFiles
            }).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open4 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 通过  */
    pass(){
      this.$refs["form3"].validate(valid => {
        if (valid) {
          if (this.form3.orderNo != null) {
            console.log("---------"+JSON.stringify(this.form3))
            passAudit(this.form3.orderNo).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open3 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 拒绝  拒绝 提供押金抵扣*/
    reject(){
      console.log("---------")
      this.$refs["form3"].validate(valid => {
        if (valid) {
          console.log("------222---")
          if (this.form3.orderId != null) {
            this.form3.status = "6";
            updateOrder({orderId:this.form3.orderId,status:this.form3.status}).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open3 = false;
              this.getList();
            });
          }
        }
      });
    },
    // 去沟通
    toCommunicate: function(row) {
      this.$modal.confirm2('请确保与客户进行沟通并通过用户同意后方可扣款，并做好录音上传审核通过后方可扣押金,客户电话：'+row.userName,"车损押金扣款","去沟通").then(function() {
        console.log("-----去沟通----")
        // 打开上传录音弹窗，输入扣款金额
      }).then(() => {
        this.form4 = row;
        this.open4 = true;
      }).catch(() => {
      })
    },
    handleAudit(row){
      this.open3 = true;
      this.form3 = row;
      console.log("this.form3============="+JSON.stringify(this.form3))
      this.view = false;
    },
    toLog(row){
      this.$router.push(`/system/commandLog/orderNo/index/${row.orderNo}`);
    },
    getTypeText(type) {
      switch (type) {
        case '1':
          return '开锁';
        case '2':
          return '临时锁车';
        case '3':
          return '解锁';
        case '4':
          return '关锁';
        default:
          return ''; // 或者根据实际情况返回其他默认值
      }
    },
    /** 查询字典类型列表 */
    getAreaList() {
      getAreaOptionselect().then(response => {
        this.areaOptions = response.data;
      });
    },
    changePrice(row){
      // console.log('changePrice')
      const orderId = row.orderId || this.ids
      this.reset2();
      getOrder(orderId).then(response => {
        this.form2 = response.data;
        // console.log("this.form2============="+JSON.stringify(this.form2));
        this.open2 = true;
        this.title2 = "改价";
      });
    },
    // 押金抵扣
    deduction: function(row) {
      getArea(row.areaId).then(response => {
        let area = response.data
        let deposit = parseFloat(area.deposit);
        if(row.totalFee > deposit ){//订单金额大于押金
          this.$modal.confirm('订单金额【'+row.totalFee+'】大于押金【'+deposit+'】,是否确认押金抵扣,并结束订单？').then(function() {
            return deduction({ orderNo: row.orderNo })
          }).then(() => {
            this.getList()
            this.$modal.msgSuccess('操作成功')
          }).catch(() => {
          })
        }else{
          this.$modal.confirm('是否确认用押金抵扣？').then(function() {
            return deduction({ orderNo: row.orderNo })
          }).then(() => {
            this.getList()
            this.$modal.msgSuccess('操作成功')
          }).catch(() => {
          })
        }

      })
    },
    refund(row){
      // console.log('changePrice')
      const orderId = row.orderId || this.ids
      this.reset2();
      getOrder(orderId).then(response => {
        this.form2 = response.data;
        // console.log("this.form2============="+JSON.stringify(this.form2));
        this.open2 = true;
        this.title2 = "退款";
      });
    },
    returnVehicle(row){
      // console.log('returnVehicle--------------'+JSON.stringify(row))
      this.$modal.confirm('是否确认辅助还车MAC为：' + row.sn + '的设备吗？').then(() => {
        // 显示加载中状态
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'custom-loading-spinner',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        return returnVehicle({ orderNo: row.orderNo, returnType: "2" })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("操作成功");
          }).finally(() => {
            // 关闭加载中状态
            loading.close();
          });
      }).catch(() => {
        // 如果用户取消了确认框
      });
    },
    formatDistance(row){
      // console.log("============"+JSON.stringify(row))
      // console.log("============"+row.distance)
      if(row == undefined || row.distance == null){
        return "";
      }
      return (row.distance / 1000).toFixed(1) + ' 公里';
    },
    //金额格式化，如果金额是null，则返回0.00，如果本来就是两位小数则直接返回，否则保留两位小数
    formatFee(fee){
      console.log("formatFee:"+fee)
      if (!fee) return '0.00元';
      const feeStr = fee.toString();
      const twoDecimalPattern = /^\d+(\.\d{2})?$/;
      if (twoDecimalPattern.test(feeStr)) {
        return `${feeStr}元`;
      }
      const formattedFee = parseFloat(fee).toFixed(2);
      return `${formattedFee}元`;
    },

    calculateEstimateFee(row) {
      const ridingRule = JSON.parse( row.ridingRuleJson);
      console.log("ridingRule",ridingRule)
      const startingPrice = parseFloat(ridingRule.startingPrice);
      const startingTime = parseInt(ridingRule.startingTime);
      const timeoutPrice = parseFloat(ridingRule.timeoutPrice);
      const timeoutTime = parseInt(ridingRule.timeoutTime);

      console.log("ridingRule:" + JSON.stringify(ridingRule));

      const createTime = new Date(row.createTime);
      const currentTime = new Date();
      const durationMinutes = Math.floor((currentTime - createTime) / (1000 * 60)); // 骑行时长（分钟）

      // 计算预估费用
      let estimatedFee = startingPrice;
      if (durationMinutes > startingTime) {
        const extraTime = durationMinutes - startingTime;
        const extraCharges = Math.ceil(extraTime / timeoutTime) * timeoutPrice;
        estimatedFee += extraCharges;
      }
      console.log("durationMinutes:" + durationMinutes);
      console.log("estimatedFee:" + estimatedFee);
      // 格式化费用
      if (!estimatedFee) return '0.00元';
      const feeStr = estimatedFee.toString();
      const twoDecimalPattern = /^\d+(\.\d{2})?$/;
      console.log("feeStr:" + feeStr)
      if (twoDecimalPattern.test(feeStr)) {
        return `${feeStr}元`;
      }
      const formattedFee = parseFloat(estimatedFee).toFixed(2);
      console.log("formattedFee:" + formattedFee)
      return `${formattedFee}元`;
    },
    calculateSettlementAmount(row) {
      // 计算结算金额 = 总费用 - 退款金额
      const payFee = row.payFee || 0;
      const totalRefundFee = row.totalRefundFee || 0;
      return payFee - totalRefundFee;
    },
    calculateNetFee() {
      // 计算总退款
      let totalRefund = this.form.etRefunds.reduce((total, refund) => {
        return total + refund.appointmentFee + refund.dispatchFee + refund.ridingFee + refund.manageFee;
      }, 0);
      // 计算结算总费用
      return this.form.payFee - totalRefund;
    },
    formatStatus(status) {
      //状态：0-预约中，1-取消预约，2-开始骑行，3-骑行结束，4-订单结束
      if (!status) return '未知';
      switch (status) {
        case '0':
          return '预约中';
        case '1':
          return '取消预约';
        case '2':
          return '开始骑行';
        case '3':
          return '骑行结束';
        case '4':
          return '订单结束';
        default:
          return '未知';
      }
    },
    formatType(payType) {
      switch (payType) {
        case 'ali':
          return '支付宝';
        case 'wx':
          return '微信';
        case 'sys':
          return '系统自动';
        default:
          return '无';
      }
    },
    formatDuration(row) {
      const createTime = new Date(row.createTime);
      const endTime = row.returnTime ? new Date(row.returnTime) : new Date(); // 如果未结束，则使用当前时间
      const durationMilliseconds = endTime - createTime;
      // 计算小时、分钟和秒
      const hours = Math.floor(durationMilliseconds / (1000 * 60 * 60));
      const minutes = Math.floor((durationMilliseconds % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((durationMilliseconds % (1000 * 60)) / 1000); // 取整秒数
      // 格式化输出
      const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      return formattedTime;
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      this.reset2();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        areaId: null,
        orderNo: null,
        userId: null,
        deviceMac: null,
        payTime: null,
        payType: null,
        type: null,
        totalFee: null,
        mark: null,
        duration: null,
        distance: null,
        status: null,
        createTime: null,
        device: {
          vehicleNum: null,
          mac: null
        },
        etRefunds: [],
        etRefund: {
          appointmentFee: null,
          ridingFee: null,
          dispatchFee: null,
          manageFee: null,
          reason: null,
          createTime: null
        },
        appointmentFee: null,
        ridingFee: null,
        dispatchFee: null,
        manageFee: null,
        returnTime: null,
        user: {
          nickName: null
        },
        rule: {
          name: null
        }
      };
      this.resetForm("form");
    },
    reset2() {
      this.form2 = {
        orderId: null,
        orderNo: null,
        payTime: null,
        appointmentFee: null,
        ridingFee: null,
        dispatchFee: null,
        manageFee: null,
        reason: null,
        createTime: null
      };
      this.resetForm("form2");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        // console.log("=====getOrder======="+JSON.stringify(response))
        this.form = response.data;
        if (response.data.etRefund) {
          this.form.etRefund = response.data.etRefund;
        }
        this.showPlaceSearchMap = true;
        this.open = true;
        this.title = "订单详情";
        this.key++;
      });
    },
    /** 提交改价 */
    submitChangePrice(){
      // console.log("=====submitChangePrice======="+this.form2)
      changePrice(this.form2).then(response => {
        this.$modal.msgSuccess("改价成功");
        this.open2 = false;
        this.getList();
      });
    },
    /** 提交退款 */
    submitRefund(){
      // console.log("=====submitRefund======="+this.form2)
      refund(this.form2).then(response => {
        this.$modal.msgSuccess("退款成功");
        this.open2 = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
  .el-dialog__body{
    padding: 0px 20px !important;
  }
  .el-form-item--mini.el-form-item {
    margin-bottom: 10px !important;
  }
  .el-dialog:not(.is-fullscreen) {
    margin-top: 1vh !important;
  }
  .refund-card {
    margin-bottom: 10px; /* 卡片之间的间距 */
    border: 1px solid #dcdfe6; /* 边框颜色 */
    border-radius: 4px; /* 边角圆润 */
    /*padding: 10px; !* 内边距 *!*/
  }

  .refund-content {
    padding: 10px;
  }

  .el-card__body {
    padding: 10px !important;
  }

  .custom-loading-spinner {
    border: 6px solid rgba(0, 0, 0, 0.1);
    border-left-color: #409EFF;
    border-radius: 50%;
    display: inline-block;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }


</style>
