<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="bstType">
        <el-select v-model="queryParams.bstType" placeholder="请选择业务类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.bonus_bst_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.bonus_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分成方" prop="arrivalName">
        <el-input
          v-model="queryParams.arrivalName"
          placeholder="请输入分成方名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分成类型" prop="arrivalType">
        <el-select v-model="queryParams.arrivalType" placeholder="请选择分成类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.bonus_arrival_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="原因" prop="reason">
        <el-input
          v-model="queryParams.reason"
          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-has-permi="['bst:bonus:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bonusList" @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 === 'reason'">
              {{d.row.reason | dv}}
              <dict-tag :options="dict.type.bonus_bst_type" :value="d.row.bstType" size="mini" style="margin-right: 4px;"/>
              <dict-tag :options="dict.type.bonus_status" :value="d.row.status" size="mini" style="margin-right: 4px;"/>
            </template>
            <template v-else-if="column.key === 'arrivalName'">
              {{d.row.arrivalName | dv}}
              <dict-tag :options="dict.type.bonus_arrival_type" :value="d.row.arrivalType" size="mini" style="margin-right: 4px;"/>
            </template>
            <template v-else-if="column.key === 'toBalance'">
              <boolean-tag :value="d.row.toBalance" size="mini"/>
            </template>
            <template v-else-if="['invalidAmount', 'amount', 'waitAmount', 'payedAmount', 'refundAmount'].includes(column.key)">
              <span :style="{color: amountColor[column.key]}">
                {{d.row[column.key] | fix2 | dv}} 元
              </span>
            </template>
            <template v-else-if="column.key === 'point'">
              {{d.row[column.key] | fix2 | dv}} %
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="d">
          <el-button
            type="text"
            size="mini"
            @click="handlePay(d.row)"
            icon="el-icon-wallet"
            v-has-permi="['bst:bonus:pay']"
            v-show="BonusStatus.canPay().includes(d.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"
    />

  </div>
</template>

<script>
import { listBonus, getBonus, delBonus, addBonus, updateBonus, payBonus } from "@/api/bst/bonus";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import BooleanTag from "@/components/BooleanTag/index.vue";
import { BonusStatus } from "@/utils/enums";

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

export default {
  name: "Bonus",
  mixins: [$showColumns],
  dicts: ['bonus_status', 'bonus_arrival_type', 'bonus_bst_type'],
  components: {FormCol, BooleanTag},
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      BonusStatus,
      // 金额颜色
      amountColor: {
        amount: null,
        invalidAmount: null,
        waitAmount: 'orange',
        payedAmount: 'green',
        refundAmount: 'red',
      },
      span: 24,
      // 字段列表
      columns: [
        {key: 'id', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'bstId', visible: false, label: '业务ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'reason', visible: true, label: '原因', minWidth: "230", sortable: true, overflow: false, align: 'left', width: null},
        {key: 'arrivalName', visible: true, label: '分成方', minWidth: "100", sortable: true, overflow: false, align: 'left', width: null},
        {key: 'arrivalId', visible: false, label: '分成方ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'point', visible: true, label: '比例', 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: 'invalidAmount', visible: true, label: '未出账', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'waitAmount', visible: true, label: '待分成', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'payedAmount', 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: 'prePayTime', visible: true, label: '预计分成', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
        {key: 'payTime', visible: true, label: '实际分成', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
        {key: 'toBalance', visible: false, label: '余额变动', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'createTime', visible: true, label: '创建时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分成表格数据
      bonusList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        id: null,
        bstId: null,
        bstType: null,
        status: null,
        arrivalId: null,
        arrivalName: null,
        arrivalType: null,
        toBalance: null,
        reason: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    Object.assign(this.queryParams, this.query);
    this.getList();
  },
  methods: {
    handlePay(row) {
      this.$confirm(`是否确认打款该分成：${row.reason}？`).then(() => {
        payBonus(row.id).then(res => {
          this.$modal.msgSuccess("打款成功");
          this.getList();
        });
      })
    },
    /** 当排序按钮被点击时触发 **/
    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;
      listBonus(this.queryParams).then(response => {
        this.bonusList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bstId: null,
        bstType: null,
        status: null,
        arrivalId: null,
        arrivalName: null,
        arrivalType: null,
        point: null,
        amount: null,
        waitAmount: null,
        payedAmount: null,
        refundAmount: null,
        prePayTime: null,
        payTime: null,
        toBalance: null,
        reason: 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.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分成";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBonus(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分成";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBonus(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBonus(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除分成编号为"' + ids + '"的数据项？').then(function() {
        return delBonus(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/bonus/export', {
        ...this.queryParams
      }, `bonus_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
