<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="billNo">
        <el-input
          v-model="queryParams.billNo"
          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="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备SN" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款用户" label-width="120" prop="mchName">
        <el-input
          v-model="queryParams.mchName"
          placeholder="请输入收款用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择交易状态" @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sm_transaction_bill_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备充值状态" prop="deviceRechargeStatus" label-width="7em">
        <el-select v-model="queryParams.deviceRechargeStatus" clearable placeholder="请选择设备充值状态" @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sm_transaction_bill_device_recharge_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="channelId">
        <el-select v-model="queryParams.channelId" clearable placeholder="请选择支付方式" @change="handleQuery">
          <el-option
            v-for="dict in dict.type.channel_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:bill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="billId" width="80"/>
      <el-table-column label="订单编号" align="center" prop="billNo" min-width="130">
        <recharge-link slot-scope="d" :bill-id="d.row.billId" :text="d.row.billNo"/>
      </el-table-column>
      <el-table-column label="充值用户" align="center" prop="userName" >
        <user-link slot-scope="d" :id="d.row.userId" :name="d.row.userName"/>
      </el-table-column>
      <el-table-column label="设备名称/SN" align="center" prop="deviceName" width="180">
        <device-link slot-scope="d" :id="d.row.deviceId" :text="`${d.row.deviceName ? d.row.deviceName : '--'} (${d.row.deviceNo})`"/>
      </el-table-column>
      <el-table-column label="收款用户" align="center" prop="mchName" >
        <user-link slot-scope="d" :id="d.row.mchId" :name="d.row.mchName"/>
      </el-table-column>
      <el-table-column label="交易金额" align="center">
        <template slot-scope="d">
          {{d.row.money | money}} 元
        </template>
      </el-table-column>
      <el-table-column label="到账金额" align="center">
        <template slot-scope="d">
          {{d.row.arrivalAmount | money}} 元
        </template>
      </el-table-column>
      <el-table-column label="手续费" align="center">
        <template slot-scope="d">
          {{d.row.serviceCharge | money}} 元
        </template>
      </el-table-column>
      <el-table-column label="成本" align="center">
        <template slot-scope="d">
          {{d.row.channelCost | money}} 元
        </template>
      </el-table-column>
      <el-table-column label="利润" align="center">
        <template slot-scope="d">
          {{d.row.serviceCharge - d.row.channelCost | money}} 元
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center">
        <template slot-scope="d">
          <dict-tag :value="d.row.channelId" :options="dict.type.channel_type"/>
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center">
        <template slot-scope="d">
          <dict-tag :value="d.row.status" :options="dict.type.sm_transaction_bill_status"/>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center">
        <template slot-scope="d">
          <dict-tag :value="d.row.deviceRechargeStatus" :options="dict.type.sm_transaction_bill_device_recharge_status"/>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template slot-scope="d">
          <el-button
            size="small"
            type="text"
            icon="el-icon-view"
            @click="handleView(d.row)"
            v-has-permi="['system:bill:query']"
          >详情</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-refresh"
            @click="refreshPayResult([d.row.billId])"
            v-if="canRefresh(d.row)"
          >刷新支付结果</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-refresh"
            @click="rechargeDevice(d.row.billId)"
            v-if="canRechargeDevice(d.row)"
          >手动设备充值</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-refresh"
            @click="handleRefund(d.row)"
            v-has-permi="['system:bill:refund']"
            v-show="canRefund(d.row)"
          >订单退款</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>

    <!-- 退款 -->
    <el-dialog :visible.sync="showRefund" title="退款" width="400px">
      <el-form :model="refundForm" :rules="refundRules">
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number v-model="refundForm.refundAmount" placeholder="请输入退款金额" /> 元
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefund" :loading="refundLoading">确 定</el-button>
        <el-button @click="showRefund = false" >取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listBill,
  getBill,
  delBill,
  addBill,
  updateBill,
  refreshPayResult,
  rechargeDevice,
  refundBill
} from '@/api/system/recharge'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import DeviceLink from '@/components/Business/Device/DeviceLink.vue'
import RechargeLink from '@/components/Business/Transaction/RechargeLink.vue'

export default {
  name: "Bill",
  components: { RechargeLink, DeviceLink, UserLink },
  dicts: ['channel_type','sm_transaction_bill_status', 'sm_transaction_bill_device_recharge_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充值记录表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        deviceName: null,
        landlordName: null,
        type: "1",  // 充值
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      refundRules: {
        refundAmount: [
          { required: true, type: 'number', message: "退款金额不能为空", trigger: "blur" }
        ]
      },
      showRefund: false,
      refundForm: {},
      refundLoading: false,
    };
  },
  computed: {
    canRefresh() {
      return (row) => {
        return row.status === '0' || row.status === '6';
      }
    },
    canRechargeDevice() {
      return (row) => {
        return row.status === '2' && row.deviceRechargeStatus !== '1';
      }
    },
    canRefund() {
      return (row) => {
        return row.status === '2';
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    submitRefund() {
      this.refundLoading = true;
      refundBill(this.refundForm.billId, this.refundForm.refundAmount).then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.showRefund = false;
          this.getList();
        }
      }).finally(() => {
        this.refundLoading = false;
      })
    },
    handleView(row) {
      this.$router.push(`/transaction/recharge/${row.billId}`)
    },
    handleRefund(row) {
      this.refundForm = {
        billId: row.billId,
        refundAmount: row.money,
      }
      this.showRefund = true;
    },
    rechargeDevice(id) {
      rechargeDevice(id).then(res => {
        if (res.code === 200) {
          this.getList();
          this.$message.success("操作成功");
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    refreshPayResult(ids) {
      refreshPayResult(ids).then(res => {
        if (res.code === 200) {
          this.getList();
          this.$message.success("刷新成功");
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    /** 查询充值记录列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams).then(response => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billId: null,
        userId: null,
        type: null,
        deviceId: null,
        landlordId: null,
        money: null,
        arrivalAmount: null,
        serviceCharge: null,
        createTime: null,
        remark: 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.billId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加充值记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const billId = row.billId || this.ids
      getBill(billId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改充值记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.billId != null) {
            updateBill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billIds = row.billId || this.ids;
      this.$modal.confirm('是否确认删除充值记录编号为"' + billIds + '"的数据项？').then(function() {
        return delBill(billIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/bill/export', {
        ...this.queryParams
      }, `bill_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
