<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="areaId">
        <area-remote-select
          v-model="queryParams.areaId"
          clearable
          @change="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="statusList">
        <el-checkbox-group v-model="queryParams.statusList" placeholder="请选择状态" @change="handleQuery">
          <el-checkbox-button
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}</el-checkbox-button>
        </el-checkbox-group>
      </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 === 'no'">
              <order-link :id="d.row.id" :text="d.row.no" size="mini"/>
            </template>
            <template v-else-if="column.key === 'suitName'">
              <dict-tag :options="dict.type.order_status" :value="d.row.status" size="mini"/>
              {{d.row.suitName | dv}}
              <br/>
              <dict-tag :options="dict.type.suit_type" :value="d.row.suitType" size="mini"/>
              <dict-tag :options="dict.type.suit_riding_rule" :value="d.row.suitRidingRule" size="mini" style="margin-left: 4px;"/>
              <el-tag v-if="d.row.suitDepositDeduction" type="success" size="mini">自动抵扣</el-tag>
            </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"/>
              <dict-tag :options="dict.type.order_pay_type" :value="d.row.payType" 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.ridingFee != null">骑行：{{d.row.ridingFee | fix2 | dv}} 元</el-col>
                  <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">
                    <el-popover
                      placement="bottom"
                      width="200"
                      trigger="hover"
                    >
                      <div>
                        <div>骑行费：{{d.row.ridingFee | fix2 | dv}} 元</div>
                        <div>调度费：{{d.row.dispatchFee | fix2 | dv}} 元</div>
                        <div>管理费：{{d.row.manageFee | fix2 | dv}} 元</div>
                        <div>车损费：{{d.row.deductionFee | fix2 | dv}} 元</div>
                      </div>
                      <div slot="reference">结算：{{d.row.totalFee | fix2 | dv}} 元 <i class="el-icon-info" /></div>
                    </el-popover>
                  </el-col>
                  <el-col :span="12" v-if="d.row.actualAmount != null && OrderStatus.finishedList().includes(d.row.status)" style="color: green;font-weight: bold;">
                    实收：{{d.row.actualAmount | 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-row>
              </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>
            </template>
            <template v-else-if="column.key === 'device'">
              <div>
                SN：<device-link :id="d.row.deviceId" :text="d.row.deviceSn"  size="mini"/>
                <dict-tag :options="dict.type.device_status" :value="d.row.deviceStatus" size="mini" style="margin-left: 4px;"/>
              </div>
              <div v-if="d.row.deviceMac != null">MAC：<device-link :id="d.row.deviceId" :text="d.row.deviceMac"  size="mini"/></div>
              <div v-if="d.row.deviceVehicleNum != null">车牌：<device-link :id="d.row.deviceId" :text="d.row.deviceVehicleNum"  size="mini"/></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 === 'use'">
              <div v-if="d.row.duration != null">
                <i class="el-icon-timer" />
                {{toDescriptionFromSecond(getOrderDuration(d.row)).text | dv}}
              </div>
              <div v-if="d.row.distance != null">
                <i class="el-icon-position" />
                {{d.row.distance / 1000 | fix2 | dv}} 公里
              </div>
              <div v-if="d.row.endReason != null">{{d.row.endReason | dv}}</div>
            </template>
            <template v-else-if="column.key === 'userName'">
              <div v-if="d.row.userName != null">
                <i class="el-icon-user" />
                <user-link :id="d.row.userId" :text="d.row.userName" size="mini"/>
              </div>
              <div v-if="d.row.userPhone != null">
                <i class="el-icon-phone" />
                <user-link :id="d.row.userId" :text="d.row.userPhone" size="mini"/>
              </div>
              <div v-if="d.row.areaName != null">
                <i class="el-icon-location"/>
                <area-link :id="d.row.areaId" :text="d.row.areaName" size="mini"/>
              </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>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="handleVerify(scope.row)"
            v-has-permi="['bst:order:verify']"
            v-show="OrderStatus.canVerify().includes(scope.row.status)"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="handleDeduct(scope.row)"
            v-has-permi="['bst:order:deduct']"
            v-show="OrderStatus.canDeduct().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" />

    <order-verify-dialog :id="row.id" :visible.sync="showVerifyDialog" @success="getList" />

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

<script>
import { appCalcOrderFee } from "@/api/app/order";
import { endOrder, listOrder } from "@/api/bst/order";
import AreaLink from '@/components/Business/Area/AreaLink.vue';
import AreaRemoteSelect from '@/components/Business/Area/AreaRemoteSelect.vue';
import DeviceLink from '@/components/Business/Device/DeviceLink.vue';
import OrderLink from '@/components/Business/Order/OrderLink.vue';
import UserLink from '@/components/Business/User/UserLink.vue';
import FormCol from "@/components/FormCol/index.vue";
import { toDescriptionFromSecond } from '@/utils/date';
import { OrderStatus } from "@/utils/enums";
import { $showColumns } from '@/utils/mixins';
import OrderDeductDialog from "@/views/bst/order/components/OrderDeductDialog.vue";
import OrderRefundDialog from "@/views/bst/order/components/OrderRefundDialog.vue";
import OrderVerifyDialog from "@/views/bst/order/components/OrderVerifyDialog.vue";
import { getOrderDuration } from '@/views/bst/order/util.js';

// 默认排序字段
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', 'device_status', 'order_pay_type'],
  components: {FormCol, OrderRefundDialog, OrderVerifyDialog, OrderDeductDialog, UserLink, DeviceLink, OrderLink, AreaLink, AreaRemoteSelect},
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  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: 'userName', visible: true, label: '用户', minWidth: "150", 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: 'time', visible: true, label: '时间', minWidth: "180", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'payNo', visible: false, label: '支付', minWidth: "180", sortable: false, overflow: false, align: 'left', width: null},
        {key: 'use', visible: true, label: '使用', minWidth: "180", sortable: false, overflow: false, align: 'left', 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,
        statusList: OrderStatus.valid(),
        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,
      showVerifyDialog: false,
      showDeductDialog: false,
    };
  },
  created() {
    Object.assign(this.queryParams, this.query, this.$route.query);
    this.getList();
  },
  methods: {
    getOrderDuration,
    toDescriptionFromSecond,
    handleDeduct(row) {
      this.row = row;
      this.showDeductDialog = true;
    },
    handleVerify(row) {
      this.row = row;
      this.showVerifyDialog = true;
    },
    handleView(row) {
      this.$router.push(`/view/order/${row.id}`)
    },
    async handleEnd(row) {
      const calcRes = await appCalcOrderFee({orderId: row.id, checkLocation: false})
      let fee = {}
      if (calcRes.code === 200 && calcRes.data) {
        fee = calcRes.data
      }
      
      if (fee.manageFee || fee.dispatchFee) {
        this.$confirm(`订单${row.no}存在${fee.dispatchFee ? '调度费' + fee.dispatchFee + '元' : ''}${fee.manageFee ? '管理费' + fee.manageFee + '元' : ''}，是否收取？`, '提示', {
          confirmButtonText: '收取',
          cancelButtonText: '不收取',
          type: 'warning'
        }).then(() => {
          this.doEndOrder(row.id, true);
        }).catch(() => {
          this.doEndOrder(row.id, false);
        });
      } else {
        this.$confirm(`确定结束订单${row.no}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doEndOrder(row.id, false);
        });
      }
    },
    doEndOrder(id, needDispatchFee) {
      endOrder(id, needDispatchFee).then(res => {
        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>
