<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" v-if="notHasView(views.recharge)">
        <el-input
          v-model="queryParams.billNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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" label-width="6em">
        <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>
        <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: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 === 'status'">
              <dict-tag :options="dict.type.bonus_status" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'arrivalType'">
              <dict-tag :options="dict.type.bonus_arrival_type" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'point'">
              {{d.row.point | money | defaultValue}} %
            </template>
            <template v-else-if="['amount'].includes(column.key)">
              {{d.row[column.key] | money | defaultValue}} 元
            </template>
            <template v-else-if="column.key === 'waitAmount'">
              <span style="color: orange">{{d.row.waitAmount | money | defaultValue}} 元</span>
            </template>
            <template v-else-if="column.key === 'payedAmount'">
              <span style="color: green">{{d.row.payedAmount | money | defaultValue}} 元</span>
            </template>
            <template v-else-if="column.key === 'refundAmount'">
              <span style="color: red">{{d.row.refundAmount | money | defaultValue}} 元</span>
            </template>
            <template v-else-if="column.key === 'toBalance'">
              <boolean-tag :value="d.row.toBalance"/>
            </template>
            <template v-else-if="column.key === 'arrivalName'">
              <user-link v-if="BonusArrivalType.userList().includes(d.row.arrivalType)" :id="d.row.arrivalId" :name="d.row.arrivalName"/>
              <template v-else> {{d.row.arrivalName | defaultValue}}</template>
            </template>
            <template v-else>
              {{d.row[column.key] | defaultValue}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-wallet"
            @click="handlePay(scope.row)"
            v-hasPermi="['ss:bonus:pay']"
            v-show="BonusStatus.canPay().includes(scope.row.status) && scope.row.waitAmount > 0"
          >立即分成</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-item label="订单ID" prop="billId">
          <el-input v-model="form.billId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="订单编号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.bonus_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款方ID" prop="arrivalId">
          <el-input v-model="form.arrivalId" placeholder="请输入收款方ID" />
        </el-form-item>
        <el-form-item label="分成方名称" prop="arrivalName">
          <el-input v-model="form.arrivalName" placeholder="请输入分成方名称" />
        </el-form-item>
        <el-form-item label="收款方类型" prop="arrivalType">
          <el-select v-model="form.arrivalType" placeholder="请选择收款方类型">
            <el-option
              v-for="dict in dict.type.bonus_arrival_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分成比例" prop="point">
          <el-input v-model="form.point" placeholder="请输入分成比例" />
        </el-form-item>
        <el-form-item label="分成金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入分成金额" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="分成时间" prop="payTime">
          <el-date-picker clearable
                          v-model="form.payTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择分成时间">
          </el-date-picker>
        </el-form-item>
      </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 { listBonus, getBonus, delBonus, addBonus, updateBonus, payBonus } from '@/api/ss/bonus'
import { $showColumns, $view } from '@/utils/mixins'
import { BonusArrivalType, BonusStatus, SmUserType, views } from '@/utils/constants'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import BooleanTag from '@/components/BooleanTag/index.vue'
// 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "Bonus",
  components: { UserLink, BooleanTag },
  mixins: [$showColumns, $view],
  dicts: ['bonus_status', 'bonus_arrival_type'],
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 字段列表
      columns: [
        {key: 'id', visible: false, label: '分成编号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'billNo', visible: true, label: '订单编号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "180"},
        {key: 'status', visible: true, label: '状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'arrivalName', visible: true, label: '收款方', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'arrivalType', visible: true, label: '类型', 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: '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: 'toBalance', visible: true, label: '变动余额', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'prePayTime', visible: true, label: '预计分成', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'payTime', visible: true, label: '实际分成', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {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,
        billId: null,
        billNo: null,
        status: null,
        arrivalId: null,
        arrivalName: null,
        arrivalType: null,
        point: null,
        amount: null,
        refundAmount: null,
        ancestors: null,
        payTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billId: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
        billNo: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        arrivalId: [
          { required: true, message: "收款方ID不能为空", trigger: "blur" }
        ],
        arrivalName: [
          { required: true, message: "分成方名称不能为空", trigger: "blur" }
        ],
        arrivalType: [
          { required: true, message: "收款方类型不能为空", trigger: "change" }
        ],
        point: [
          { required: true, message: "分成比例不能为空", trigger: "blur" }
        ],
        ancestors: [
          { required: true, message: "收款方祖级列表不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    BonusStatus() {
      return BonusStatus
    },
    BonusArrivalType() {
      return BonusArrivalType
    },
    SmUserType() {
      return SmUserType
    }
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }

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

    if (this.view === views.recharge) {
      this.hideColumn(['billNo'])
    }

    this.getList();
  },
  methods: {
    handlePay(row) {
      this.$confirm(`是否确认支付【订单编号】${row.billNo}【收款方】${row.arrivalName}的分成？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        payBonus(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success("支付分成成功");
            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,
        billId: null,
        billNo: null,
        status: null,
        arrivalId: null,
        arrivalName: null,
        arrivalType: null,
        point: null,
        amount: null,
        refundAmount: null,
        ancestors: null,
        createTime: null,
        payTime: 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('ss/bonus/export', {
        ...this.queryParams
      }, `bonus_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
