`<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="payNo">
        <el-input
          v-model="queryParams.payNo"
          placeholder="请输入支付订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务类型" prop="bstType">
        <el-select v-model="queryParams.bstType" placeholder="请选择业务类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.pay_bill_bst_type"
            :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" placeholder="请选择支付状态" clearable @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 label="支付状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择支付状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.pay_bill_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入支付账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['ss:payBill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payBillList" @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 === 'payId'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'bstType'">
              <dict-tag :options="dict.type.pay_bill_bst_type" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :options="dict.type.pay_bill_status" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'channelId'">
              <dict-tag :options="dict.type.channel_type" :value="d.row.channelId"/>
            </template>
            <template v-else-if="['channelCost', 'amount', 'refundingAmount', 'refundAmount'].includes(column.key)">
              {{d.row[column.key] | money}} 元
            </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">-->
<!--        <template slot-scope="d">-->
<!--          <el-button-->
<!--            icon="el-icon-refresh"-->
<!--            type="text"-->
<!--            @click="handleRefund(d.row)"-->
<!--            v-show="canRefund(d.row)"-->
<!--            v-has-permi="['ss:payBill:refund']"-->
<!--          >-->
<!--            退款-->
<!--          </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 :visible.sync="showRefund" title="退款申请" center width="500px">
      <el-form :model="refundForm" :rules="refundRules" label-width="6em">
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number v-model="refundForm.refundAmount" :precision="2" :min="0.01" controls-position="right" style="calc(100% - 3em)"/> 元
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReason">
          <el-input v-model="refundForm.refundReason" placeholder="请输入退款原因" maxlength="200" show-word-limit :rows="3" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSubmitRefund">申请退款</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { listPayBill, getPayBill, delPayBill, addPayBill, updatePayBill, refundPayBill } from '@/api/ss/payBill'
import { $showColumns, $view } from '@/utils/mixins'
import { PayBillStatus } from '@/utils/constants'

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

export default {
  name: "PayBill",
  mixins: [$showColumns, $view],
  dicts: ['pay_bill_status', 'pay_bill_bst_type', 'channel_type'],
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    canRefund() {
      return (row) => {
        return row != null && row.status === PayBillStatus.PAY_SUCCESS;
      }
    },
    canRefresh() {
      return (row) => {
        return row != null && row.status === PayBillStatus.PAYING;
      }
    }
  },
  data() {
    return {
      showRefund: false,
      refundForm: [],
      refundRules: [],
      // 字段列表
      columns: [
        {key: 'payId', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'payNo', visible: true, label: '支付订单编号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "180"},
        {key: 'bstType', visible: true, label: '业务类型', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'bstId', visible: false, label: '业务ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'amount', visible: true, label: '支付金额', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'channelId', visible: true, label: '支付渠道', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'status', visible: true, label: '支付状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'payTime', visible: true, label: '支付时间', minWidth: "120", sortable: false, overflow: false, align: 'center', width: null},
        {key: 'description', visible: true, label: '描述', minWidth: "200", sortable: true, overflow: true, align: 'center', width: null},
        {key: 'account', visible: true, label: '支付账号', minWidth: "100", sortable: true, overflow: true, align: 'center', width: null},
        {key: 'channelCost', visible: true, label: '渠道成本', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'refundAmount', visible: true, label: '已退款金额', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'refundingAmount', visible: true, 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,
      // 支付订单表格数据
      payBillList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        payId: null,
        payNo: null,
        bstType: null,
        bstId: null,
        amount: null,
        channelId: null,
        status: null,
        payTime: null,
        description: null,
        account: null,
        channelCost: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        payNo: [
          { required: true, message: "支付订单编号不能为空", trigger: "blur" }
        ],
        bstType: [
          { required: true, message: "业务类型：1-月费账单；2-电量充值订单；3-计时收费订单不能为空", trigger: "change" }
        ],
        bstId: [
          { required: true, message: "业务ID不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "订单金额不能为空", trigger: "blur" }
        ],
        channelId: [
          { required: true, message: "支付渠道ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "支付状态：1-待支付；2-支付中；3-支付成功；4-已取消；不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        account: [
          { required: true, message: "支付账号不能为空", trigger: "blur" }
        ],
        channelCost: [
          { required: true, message: "渠道成本不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }

    if (this.view != null) {
      this.showSearch = false;
    }

    this.getList();
  },
  methods: {
    handleSubmitRefund() {
      refundPayBill(this.refundForm).then(res => {
        if (res.code === 200) {
          this.$message.success("申请成功，退款中");
          this.showRefund = false;
        }
      }).finally(() => {
        this.getList();
      })
    },
    handleRefund(row) {
      this.refundForm = {
        payId: row.payId,
        refundAmount: row.amount,
        refundReason: `支付订单${row.payNo}退款`
      }
      this.showRefund = 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;
      listPayBill(this.queryParams).then(response => {
        this.payBillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        payId: null,
        payNo: null,
        bstType: null,
        bstId: null,
        amount: null,
        channelId: null,
        status: null,
        payTime: null,
        createTime: null,
        description: null,
        account: null,
        channelCost: 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.payId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加支付订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const payId = row.payId || this.ids
      getPayBill(payId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改支付订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.payId != null) {
            updatePayBill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPayBill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const payIds = row.payId || this.ids;
      this.$modal.confirm('是否确认删除支付订单编号为"' + payIds + '"的数据项？').then(function() {
        return delPayBill(payIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ss/payBill/export', {
        ...this.queryParams
      }, `payBill_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
