<template>
  <div>
    <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="deviceName" v-if="notHasView(views.device)">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备SN" prop="deviceNo" v-if="notHasView(views.device)">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userName" v-if="notHasView(views.user)">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入充值用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户" label-width="120" prop="mchName" v-if="notHasView(views.mch)">
        <el-input
          v-model="queryParams.mchName"
          placeholder="请输入收款商户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" label-width="120" prop="storeName" v-if="notHasView(views.store)">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单金额" label-width="120" prop="money">
        <el-input
          v-model="queryParams.money"
          placeholder="请输入订单金额（元）"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="channelIds">
        <el-checkbox-group v-model="queryParams.channelIds" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.channel_type" :label="dict.value" :key="dict.value">
            {{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="收费模式" prop="suitFeeModes">
        <el-checkbox-group v-model="queryParams.suitFeeModes" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.suit_fee_mode" :label="dict.value" :key="dict.value">
            {{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="收费方式" prop="suitFeeTypes">
        <el-checkbox-group v-model="queryParams.suitFeeTypes" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.suit_fee_type" :label="dict.value" :key="dict.value">
            {{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="设备充值状态" prop="deviceRechargeStatusList" label-width="7em">
        <el-checkbox-group v-model="queryParams.deviceRechargeStatusList" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.sm_transaction_bill_device_recharge_status" :label="dict.value" :key="dict.value">
            {{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="订单时间" prop="createDateRange" >
        <el-date-picker
          v-model="queryParams.createDateRange"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易状态" prop="statusList">
        <el-checkbox-group v-model="queryParams.statusList" @change="handleQuery" size="mini">
          <el-checkbox-button v-for="dict in dict.type.sm_transaction_bill_status" :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:bill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="billList" @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"
          :fixed="column.fixed"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'billId'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'billNo'">
              <recharge-link :bill-id="d.row.billId" :text="d.row.billNo"/>
            </template>
            <template v-else-if="column.key === 'userName'">
              <user-link :id="d.row.userId" :name="d.row.userName"/><br/>
              <user-link :id="d.row.userId" :name="d.row.userMobile"/>
            </template>
            <template v-else-if="column.key === 'deviceName'">
              <device-link :id="d.row.deviceId" :text="d.row.deviceName"/><br/>
              <device-link :id="d.row.deviceId" :text="d.row.deviceNo"/>
            </template>
            <template v-else-if="column.key === 'mchName'">
              <user-link :id="d.row.mchId" :name="d.row.mchName"/><br/>
              <user-link :id="d.row.mchId" :name="d.row.mchMobile"/>
            </template>
            <template v-else-if="column.key === 'storeId'">
              <store-link :id="d.row.storeId" :name="d.row.storeName"/>
            </template>
            <template v-else-if="column.key === 'suitFeeMode'">
              <dict-tag :value="d.row.suitFeeMode" :options="dict.type.suit_fee_mode"/>
            </template>
            <template v-else-if="column.key === 'suitFeeType'">
              <dict-tag :value="d.row.suitFeeType" :options="dict.type.suit_fee_type"/>
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :value="d.row.status" :options="dict.type.sm_transaction_bill_status"/>
            </template>
            <template v-else-if="column.key === 'isUsing'">
              <el-tag type="warning" v-if="d.row.isUsing">使用中</el-tag>
              <el-tag type="success" v-else-if="d.row.isFinished">已结束</el-tag>
              <el-tag type="info" v-else>未开始</el-tag>
            </template>
            <template v-else-if="column.key === 'deviceRechargeStatus'">
              <dict-tag :value="d.row.deviceRechargeStatus" :options="dict.type.sm_transaction_bill_device_recharge_status"/>
            </template>
            <template v-else-if="column.key === 'suitDeviceInfo'">
              <div>开始时间:{{d.row.suitStartTime | defaultValue}}</div>
              <div>结束时间:{{d.row.suitEndTime | defaultValue}}</div>
              <div>失效时间:{{d.row.suitExpireTime | defaultValue}}</div>
              <div>起始总用电量:{{d.row.suitStartEle | defaultValue}} 度</div>
              <div>结束总用电量:{{d.row.suitEndEle | defaultValue}} 度</div>
            </template>
            <template v-else-if="['channelCost'].includes(column.key)">
              {{d.row[column.key] | money | defaultValue}} 元
            </template>
            <template v-else-if="column.key === 'money'">
              <span style="color: green;">{{d.row.money | money | defaultValue}} 元</span>
              <!--              <div v-if="d.row.refundAmount">退款 {{d.row.refundAmount | money | defaultValue}} 元</div>-->
            </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 === 'arrivalAmount'">
              {{d.row.arrivalAmount | money | defaultValue}} 元
              <div v-if="d.row.refundMchAmount">退款 {{d.row.refundMchAmount | money | defaultValue}} 元</div>
            </template>
            <template v-else-if="column.key === 'serviceCharge'">
              {{d.row.serviceCharge | money | defaultValue}} 元
              <div v-if="d.row.refundServiceAmount">退款 {{d.row.refundServiceAmount | money | defaultValue}} 元</div>
            </template>
            <template v-else>
              {{d.row[column.key] | defaultValue}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="d">
          <slot :row="d.row" name="row-operator"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--退款对话框-->
    <refund-dialog :show.sync="showRefund" :bill-id="row.billId" :amount="row.money" @success="getList"/>

  </div>
</template>

<script>
import {
  listBill,
  getBill,
  delBill,
  addBill,
  updateBill
} 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'
import { $recharge, $showColumns, $view } from '@/utils/mixins'
import StoreLink from '@/components/Business/Store/StoreLink.vue'
import RefundDialog from '@/views/system/recharge/components/RefundDialog.vue'
import { UserType } from '@/utils/constants'
import { mapGetters } from 'vuex'

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

export default {
  name: "RechargeTable",
  mixins: [$showColumns, $view, $recharge],
  components: { RefundDialog, StoreLink, RechargeLink, DeviceLink, UserLink },
  dicts: ['channel_type','sm_transaction_bill_status', 'sm_transaction_bill_device_recharge_status', 'suit_fee_mode', 'suit_fee_type'],
  props: {
    query: {
      type: Object,
      default: () => {}
    },
    listApi: {
      type: Function,
      default: listBill
    }
  },
  computed: {
    ...mapGetters(['userType'])
  },
  data() {
    return {
      // 当前选中行
      row: {},
      defaultSort,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 字段列表
      columns: [
        {key: 'billId', visible: false, label: '订单ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80", fixed: null},
        {key: 'createTime', visible: true, label: '时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'billNo', visible: true, label: '订单编号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'deviceName', visible: true, label: '设备/SN', minWidth: null, sortable: false, overflow: false, align: 'center', width: "120", fixed: null},
        {key: 'userName', visible: true, label: '用户', minWidth: null, sortable: false, overflow: false, align: 'center', width: null, fixed: null},
        {key: 'mchName', visible: true, label: '商户', minWidth: null, sortable: false, overflow: false, align: 'center', width: null, fixed: null},
        {key: 'storeId', visible: false, label: '店铺', minWidth: null, sortable: false, overflow: false, align: 'center', width: null, fixed: null},
        {key: 'money', visible: true, label: '金额', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'refundAmount', visible: true, label: '退款', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'channelCost', visible: true, label: '渠道成本', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'channelName', visible: true, label: '支付方式', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100", fixed: null},
        {key: 'suitFeeMode', visible: true, label: '收费模式', minWidth: null, sortable: false, overflow: false, align: 'center', width: "80", fixed: null},
        {key: 'suitFeeType', visible: true, label: '收费方式', minWidth: null, sortable: false, overflow: false, align: 'center', width: "120", fixed: null},
        {key: 'status', visible: true, label: '交易状态', minWidth: null, sortable: false, overflow: false, align: 'center', width: "80", fixed: null},
        {key: 'isUsing', visible: true, label: '使用状态', minWidth: null, sortable: false, overflow: false, align: 'center', width: "80", fixed: null},
        {key: 'deviceRechargeStatus', visible: true, label: '设备状态', minWidth: null, sortable: false, overflow: false, align: 'center', width: null, fixed: null},
        {key: 'suitDeviceInfo', visible: false, label: '设备套餐详情', minWidth: null, sortable: false, overflow: false, align: 'center', width: "250", fixed: null},
        {key: 'version', visible: false, label: '订单版本', minWidth: null, sortable: false, overflow: false, align: 'center', width: null, fixed: null},
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充值记录表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        userName: null,
        deviceName: null,
        landlordName: null,
        type: "1",  // 充值
        statusList: ['1','2','3','6','7','8','9'],
        channelIds: [],
        suitFeeTypes: [],
        suitFeeModes: [],
        deviceRechargeStatusList: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      showRefund: false,
      refundForm: {},
      refundLoading: false,
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }

    // 隐藏搜索
    if (this.view != null) {
      this.showSearch = false;
    }

    // 根据当前视图隐藏部分列
    if (this.hasView(this.views.user)) {
      this.hideColumn(['userName'])
    } else if (this.hasView(this.views.mch)) {
      this.hideColumn(['mchName'])
    } else if (this.hasView(this.views.store)) {
      this.hideColumn(['storeId'])
    } else if (this.hasView(this.views.device)) {
      this.hideColumn(['deviceName'])
    }

    if (this.userType === UserType.APP) {
      this.removeColumn(['channelCost'])
    }

    this.getList();
  },
  methods: {
    /** 当排序按钮被点击时触发 **/
    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();
    },
    handleView(row) {
      this.$router.push(`/transaction/recharge/${row.billId}`)
    },
    /** 查询充值记录列表 */
    getList() {
      this.loading = true;
      this.listApi(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>
