<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="userName">
        <el-input
          v-model="queryParams.userName"
          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_recharge_status" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否退款" prop="isRefund">
        <el-checkbox-group v-model="queryParams.isRefund" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.et_is_refund" :label="dict.value" :key="dict.value">
            {{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </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="创建时间" align="center" prop="payTime" width="180">
        <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="userName" />
      <el-table-column label="类型" align="center" prop="rechargeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_order_type" :value="scope.row.rechargeType"/>
        </template>
      </el-table-column>
      <el-table-column label="押金金额" align="center" prop="totalFee" />
      <el-table-column label="流水号" align="center" prop="orderNo" width="280" :show-overflow-tooltip="true"/>
      <el-table-column label="充值状态" align="center" prop="rechargeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_recharge_status" :value="scope.row.rechargeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.rechargeType == '2' && !scope.row.isRefunded && scope.row.depositDeduction == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRefund(scope.row)"
            v-hasPermi="['system:order:edit']"
          >退款</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" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
 import { rechargeList, getOrder, delOrder, addOrder, updateOrder, handleRefund, deduction } from '@/api/system/order'
 import { listDept2 } from '@/api/system/dept'
export default {
  name: "Order",
  dicts: ['et_order_type', 'et_pay_type', 'et_recharge_status','et_is_refund'],
  props: {
    // 用户id
    deptId: {
      type: Number,
      default: null,
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      deptOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        areaId: null,
        orderNo: null,
        type: "2",
        userId: null,
        isRefund: ["0","1"],
        deviceMac: null,
        deptId: this.deptId,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户不能为空", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "支付方式不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.userName = this.$store.state.user.name;
    this.getDeptList()
  },
  methods: {
    getDeptList() {
      listDept2({ status: "0", pageNum: 1, pageSize: 999 }).then((response) => {
        this.deptOptions = response.rows;
      });
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      rechargeList(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRefund(row){
      this.$modal.confirm('是否确认押金退款？').then(function() {
        return handleRefund(row.orderNo)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('退款成功')
      }).catch(() => {
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    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
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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 => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    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>
