<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="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SN" prop="deviceSn">
        <el-input
          v-model="queryParams.deviceSn"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="MAC" prop="deviceMac">
        <el-input
          v-model="queryParams.deviceMac"
          placeholder="请输入设备MAC"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="deviceVehicleNum">
        <el-input
          v-model="queryParams.deviceVehicleNum"
          placeholder="请输入设备车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐类型" prop="suitType">
        <el-select v-model="queryParams.suitType" placeholder="请选择套餐类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.suit_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运营区" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          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="支付单号" prop="payNo">
        <el-input
          v-model="queryParams.payNo"
          placeholder="请输入支付单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="还车类型" prop="returnType">
        <el-select v-model="queryParams.returnType" placeholder="请选择还车类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.order_return_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐名称" prop="suitName">
        <el-input
          v-model="queryParams.suitName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="还车定位方式" prop="returnMode" label-width="7em">
        <el-select v-model="queryParams.returnMode" placeholder="请选择还车定位方式" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.order_return_mode"
            :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-has-permi="['bst:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table size="mini" v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
            :key="column.key"
            :label="column.label"
            :prop="column.key"
            :align="column.align"
            :min-width="column.minWidth"
            :sort-orders="orderSorts"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.overflow"
            :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'id'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'suitName'">
              {{d.row.suitName | dv}}<br/>
              <dict-tag :options="dict.type.suit_type" :value="d.row.suitType" size="mini"/>
              <dict-tag :options="dict.type.order_status" :value="d.row.status" size="mini" style="margin-left: 4px;"/>
              <dict-tag :options="dict.type.suit_riding_rule" :value="d.row.suitRidingRule" size="mini" style="margin-left: 4px;"/>
            </template>
            <template v-else-if="column.key === 'returnType'">
              <dict-tag :options="dict.type.order_return_type" :value="d.row.returnType" size="mini"/>
              <dict-tag :options="dict.type.order_return_mode" :value="d.row.returnMode" size="mini"/>
            </template>
            <template v-else-if="column.key === 'suitRentalUnit'">
              <dict-tag :options="dict.type.suit_rental_unit" :value="d.row[column.key]" size="mini"/>
            </template>
            <template v-else-if="column.key === 'totalFee'">
              <div>
                <el-row :gutter="8">
                  <el-col :span="12" v-if="d.row.depositFee != null">押金：{{d.row.depositFee | fix2 | dv}} 元</el-col>
                  <el-col :span="12" v-if="d.row.totalFee != null">总额：{{d.row.totalFee | fix2 | dv}} 元</el-col>
                  <el-col :span="12" v-if="d.row.ridingFee != null">骑行：{{d.row.ridingFee | fix2 | dv}} 元</el-col>
                  <el-col :span="12" v-if="d.row.dispatchFee">调度：{{d.row.dispatchFee | fix2 | dv}} 元</el-col>
                  <el-col :span="12" v-if="d.row.manageFee">管理：{{d.row.manageFee | fix2 | dv}} 元</el-col>
                  <el-col :span="12" v-if="d.row.deductionFee">车损：{{d.row.deductionFee | fix2 | dv}} 元</el-col>
                  <el-col :span="24" v-if="d.row.payRefunded || d.row.payRefunding" style="color: red;">
                    退款：{{d.row.payRefunded | fix2 | dv}} 元
                    <template v-if="d.row.payRefunding">(退款中：{{d.row.payRefunding | fix2 | dv}} 元)</template>
                  </el-col>
                  <el-col :span="24" v-if="d.row.payAmount" style="color: green;font-weight: bold;">实收：{{d.row.payAmount - d.row.payRefunded - d.row.payRefunding | fix2 | dv}} 元</el-col>
                </el-row>
              </div>
            </template>
            <template v-else-if="column.key === 'useInfo'">
              <div v-if="d.row.duration != null">时长：{{d.row.duration | dv}} 秒</div>
              <div v-if="d.row.distance != null">距离：{{d.row.distance | fix2 | dv}} 米</div>
            </template>
            <template v-else-if="column.key === 'time'">
              <div v-if="d.row.createTime != null">创建：{{d.row.createTime | dv}}</div>
              <div v-if="d.row.startTime != null">开始：{{d.row.startTime | dv}}</div>
              <div v-if="d.row.endTime != null">结束：{{d.row.endTime | dv}}</div>
              <div v-if="d.row.maxTime != null">超时：{{d.row.maxTime | dv}}</div>
            </template>

            <template v-else-if="column.key === 'device'">
              <div v-if="d.row.deviceSn != null">SN：{{d.row.deviceSn | dv}}</div>
              <div v-if="d.row.deviceMac != null">MAC：{{d.row.deviceMac | dv}}</div>
              <div v-if="d.row.deviceVehicleNum != null">车牌：{{d.row.deviceVehicleNum | dv}}</div>
            </template>
            <template v-else-if="column.key === 'payNo'">
              <div v-if="d.row.payNo != null">单号：{{d.row.payNo | dv}}</div>
              <div v-if="d.row.payTime != null">时间：{{d.row.payTime | dv}}</div>
              <div v-if="d.row.payChannelName != null">渠道：{{d.row.payChannelName | dv}}</div>
            </template>
            <template v-else-if="column.key === 'area'">
              <div v-if="d.row.areaName != null">运营：{{d.row.areaName | dv}}</div>
              <div v-if="d.row.startAreaSubName != null">借车：{{d.row.startAreaSubName | dv}}</div>
              <div v-if="d.row.endAreaSubName != null">还车：{{d.row.endAreaSubName | dv}}</div>
              <div v-if="d.row.endReason != null">还车原因：{{d.row.endReason | dv}}</div>
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-has-permi="['bst:order:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleEnd(scope.row)"
            v-has-permi="['bst:order:end']"
            v-show="OrderStatus.canEnd().includes(scope.row.status)"
          >结束</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="handleRefund(scope.row)"
            v-has-permi="['bst:order:refund']"
            v-show="OrderStatus.canRefund().includes(scope.row.status)"
          >退款</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"
    />

    <order-refund-dialog :id="row.id" :visible.sync="showRefundDialog" @success="getList" />
  </div>
</template>

<script>
import { listOrder, endOrder } from "@/api/bst/order";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import { OrderStatus } from "@/utils/enums";
import OrderRefundDialog from "./components/OrderRefundDialog.vue";

// 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "Order",
  mixins: [$showColumns],
  dicts: ['order_status', 'suit_type', 'order_return_type', 'order_return_mode', 'suit_rental_unit', 'suit_riding_rule'],
  components: {FormCol, OrderRefundDialog},
  data() {
    return {
      span: 24,
      OrderStatus,
      // 字段列表
      columns: [
        {key: 'id', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'no', visible: true, label: '订单号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'suitName', visible: true, label: '套餐', minWidth: "200", sortable: true, overflow: false, align: 'left', width: null},
        {key: 'device', visible: true, label: '设备', minWidth: "150", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'totalFee', visible: true, label: '费用', minWidth: "230", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'useInfo', visible: true, label: '使用', minWidth: "130", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'time', visible: true, label: '时间', minWidth: "180", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'payNo', visible: true, label: '支付', minWidth: "180", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'area', visible: true, label: '运营', minWidth: "180", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'userName', visible: true, label: '用户', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'returnType', visible: true, label: '还车', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
        {key: 'mark', visible: false, label: '备注', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        id: null,
        no: null,
        type: null,
        areaId: null,
        userId: null,
        deviceId: null,
        deviceMac: null,
        deviceSn: null,
        payId: null,
        mark: null,
        status: null,
        returnType: null,
        suitId: null,
        suitRentalUnit: null,
        suitRidingRule: null,
        returnMode: null,
      },
      row: {},
      showRefundDialog: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleView(row) {
      this.$router.push(`/view/order/${row.id}`)
    },
    handleEnd(row) {  
      this.$confirm(`确定结束订单${row.no}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        endOrder(row.id).then(response => {
          this.$message.success("结束成功");
          this.getList();
        });
      });
    },
    handleRefund(row) {
      this.row = row;
      this.showRefundDialog = true;
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
