<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="cardNo">
                <el-input v-model="queryParams.cardNo" placeholder="请输入卡号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="batchNo">
                <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入充值订单号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="rechargeStatus">
                <el-select v-model="queryParams.rechargeStatus" placeholder="请选择使用状态" clearable>
                    <el-option v-for="dict in dict.type.recharge_use_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="daterangeRechargeTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label-width="130px">
                <el-date-picker v-model="daterangeGiveActiveTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="daterangeExpireTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" @click="handleImport(1)" v-hasPermi="['system:user:import']">充值卡导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" @click="handleImport(2)" v-hasPermi="['system:user:import']">用户直充导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPermi="['recharge:card:export']">导出</el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <Page uri="/mapi/recharge/card/list" :request-params="queryParams" ref="pagination">
            <el-table-column label="卡号" align="center" prop="cardNo" width="180" fixed="left" />
            <el-table-column label="批次号" align="center" prop="batchNo" width="150">
                <template slot-scope="scope">
                    {{ scope.row.batchNo == null || scope.row.batchNo == '' ? '--' : scope.row.batchNo }}
                </template>
            </el-table-column>
            <!-- <el-table-column label="密码卡版本" align="center" prop="cardVersionTitle" width="150">
                <template slot-scope="scope">
                    {{ scope.row.cardVersionTitle == null || scope.row.cardVersionTitle == '' ? '--' : scope.row.cardVersionTitle }}
                </template>
            </el-table-column> -->
            <!--      <el-table-column label="密码卡版本编号" align="center" prop="cardVersionCode" width="150" >-->
            <!--        <template>-->
            <!--          <template slot-scope="scope">-->
            <!--            {{ scope.row.cardVersionCode == null || scope.row.cardVersionCode == '' ? '&#45;&#45;' : scope.row.cardVersionCode}}-->
            <!--          </template>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <el-table-column label="归属门店" align="center" prop="rechargeStoreName" width="150" />
            <el-table-column label="充值金额(元)" align="center" prop="rechargeAmount" width="150" />
            <el-table-column label="卡内金额（元）" align="center" prop="rechargeAmount" width="120">
                <template slot-scope="scope">
                    <span style="display: block; text-align: left">现金金额: {{ scope.row.rechargeAmount }}</span>
                    <span style="display: block; text-align: left">赠送金额: {{ scope.row.giveAmount }}</span>
                    <span style="display: block; text-align: left">福利金额: {{ scope.row.welfareAmount }}</span>
                </template>
            </el-table-column>
            <el-table-column label="卡内余额（元）" align="center" prop="rechargeAmount" width="120">
                <template slot-scope="scope">
                    <span style="display: block; text-align: left">现金金额: {{ scope.row.rechargeBalance }}</span>
                    <span style="display: block; text-align: left">赠送金额: {{ scope.row.giveBalance }}</span>
                    <span style="display: block; text-align: left">福利金额: {{ scope.row.welfareBalance }}</span>
                </template>
            </el-table-column>
            <el-table-column label="赠送积分" align="center" prop="givePointAmount" width="150">
                <template slot-scope="scope">
                    {{ scope.row.givePointAmount == null || scope.row.givePointAmount == '' ? '0' : scope.row.givePointAmount }}
                </template>
            </el-table-column>
            <el-table-column label="使用状态" align="center" prop="rechargeStatus">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.recharge_use_status" :value="scope.row.rechargeStatus" />
                </template>
            </el-table-column>
            <el-table-column label="充值用户" align="center" prop="rechargeUserName" width="150">
                <template slot-scope="scope">
                    {{ scope.row.rechargeUserName == null ? '未激活' : scope.row.rechargeUserName }}
                </template>
            </el-table-column>
            <el-table-column label="充值时间" align="center" prop="rechargeTime" width="150">
                <template slot-scope="scope">
                    {{ scope.row.rechargeTime == null ? '--' : scope.row.rechargeTime }}
                </template>
            </el-table-column>
            <el-table-column label="储值门店" align="center" prop="rechargeStoreName" width="150">
                <template slot-scope="scope">
                    {{ scope.row.useBindStoreName == null ? '--' : scope.row.useBindStoreName }}
                </template>
            </el-table-column>
            <!--            <el-table-column label="到期时间" align="center" prop="expireTime" width="150">-->
            <!--                <template slot-scope="scope">-->
            <!--                    {{ scope.row.expireTime == null ? '&#45;&#45;' : scope.row.expireTime }}-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="赠送金额激活时间" align="center" prop="giveActiveTime" width="150">
                <template slot-scope="scope">
                    {{ scope.row.giveActiveTime == null ? '未激活' : scope.row.giveActiveTime }}
                </template>
            </el-table-column>
            <el-table-column label="制卡人" align="center" prop="createBy" />
            <el-table-column label="制卡时间" align="center" prop="createTime" width="150"> </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleDetail(scope.row)" v-if="scope.row.rechargeStatus == 1">消费明细</el-button>
                </template>
            </el-table-column>
        </Page>

        <!-- 充值卡导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-card>
                <el-form ref="importForm" :model="importForm" :rules="rules" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="批次名称" prop="batchName">
                            <el-input v-model="importForm.batchName" placeholder="请输入批次名称" />
                        </el-form-item>
                        <el-form-item label="批次备注" prop="remark">
                            <el-input type="textarea" v-model="importForm.remark" placeholder="请输入批次备注" />
                        </el-form-item>
                        <el-form-item label="过期时间">
                            <el-date-picker v-model="importForm.expireTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"> </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-card>

            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="num == 1 ? upload.url + '?batchName=' + importForm.batchName + '&expireTime=' + importForm.expireTime + '&remark=' + importForm.remark : upload.url2 + '?batchName=' + importForm.batchName + '&expireTime=' + importForm.expireTime + '&remark=' + importForm.remark"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="title" :visible.sync="open" size="50%">
            <el-timeline v-for="detail in billMstrDataList" :key="detail.id">
                <el-timeline-item :timestamp="handleTitle(detail)" placement="top">
                    <el-card style="width: 90%">
                        <el-descriptions :column="4">
                            <el-descriptions-item label="订单类型" span="2">
                                <dict-tag :options="dict.type.order_type" :value="detail.orderType" />
                            </el-descriptions-item>
                            <el-descriptions-item label="支付方式" span="2">
                                <dict-tag :options="dict.type.recharge_pay_type" :value="detail.payType" />
                            </el-descriptions-item>
                            <el-descriptions-item label="消费类型" span="2"> {{ detail.billType == 0 ? '支出' : '充值' }} </el-descriptions-item>
                            <el-descriptions-item label="消费来源" span="2"> {{ detail.orgName ? detail.orgName : 'APP' }} </el-descriptions-item>

                            <el-descriptions-item label="现金支付金额" span="2"> {{ detail.isRefund == 'Y' && detail.cashPayAmount.toString() != '0' ? '退款：' + detail.cashPayAmount.toString().replace('-', '') : detail.cashPayAmount.toString().replace('-', '') }} 元 </el-descriptions-item>
                            <el-descriptions-item label="充值余额支付金额" span="2"> {{ detail.isRefund == 'Y' && detail.rechargePayAmount.toString() != '0' ? '退款：' + detail.rechargePayAmount.toString().replace('-', '') : detail.rechargePayAmount.toString().replace('-', '') }} 元 </el-descriptions-item>
                            <el-descriptions-item label="赠送余额支付金额" span="2"> {{ detail.isRefund == 'Y' && detail.givePayAmount.toString() != '0' ? '退款：' + detail.givePayAmount.toString().replace('-', '') : detail.givePayAmount.toString().replace('-', '') }} 元 </el-descriptions-item>
                            <el-descriptions-item label="福利金余额支付金额" span="2"> {{ detail.isRefund == 'Y' && detail.welfarePayAmount.toString() != '0' ? '退款：' + detail.welfarePayAmount.toString().replace('-', '') : detail.welfarePayAmount.toString().replace('-', '') }} 元 </el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-timeline-item>
            </el-timeline>
        </el-dialog>
    </div>
</template>

<script>
import { listCard, getCard, delCard, addCard, updateCard, updateCardStatus, getCardBillMstrInfo } from '@/api/recharge/card'
import { getToken } from '@/utils/auth'
import { getRechargeRecordByUserId } from '@/api/recharge/order'

export default {
    name: 'Card',
    dicts: ['recharge_use_status', 'recharge_pay_type', 'order_type'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 密码充值卡管理表格数据
            cardList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 赠送积分时间范围
            daterangeRechargeTime: [],
            // 赠送积分时间范围
            daterangeExpireTime: [],
            // 赠送积分时间范围
            daterangeCreateTime: [],
            // 赠送积分时间范围
            daterangeGiveActiveTime: [],
            // 查询参数
            queryParams: {
                cardNo: null,
                rechargeStatus: null,
                rechargeTime: null,
                expireTime: null,
                createTime: null
            },
            // 表单参数
            form: {},
            importForm: {},
            importRechargeForm: {},
            // 表单校验
            rules: {
                cardNo: [{ required: true, message: '卡号不能为空', trigger: 'blur' }],
                password: [{ required: true, message: '卡密不能为空', trigger: 'blur' }],
                rechargeAmount: [{ required: true, message: '充值金额不能为空', trigger: 'blur' }],
                giveAmount: [{ required: true, message: '赠送金额不能为空', trigger: 'blur' }],
                givePointAmount: [{ required: true, message: '赠送积分不能为空', trigger: 'blur' }],
                rechargeStatus: [{ required: true, message: '使用状态不能为空', trigger: 'blur' }],
                batchName: [{ required: true, message: '请输入批次名称', trigger: 'blur' }]
            },
            // 充值卡导入参数
            upload: {
                // 是否显示弹出层（充值卡导入）
                open: false,
                // 弹出层标题（充值卡导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的充值卡数据
                // updateSupport: 0,
                batchName: '',
                expireTime: null,
                level: 0,
                starLevel: 0,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/mapi/recharge/card/importData',
                url2: process.env.VUE_APP_BASE_API + '/mapi/recharge/card/directChargingImportData'
            },
            num: null,
            billMstrDataList: [] // 消费记录
        }
    },
    created() {
        this.getList()
    },
    methods: {
        handleTitle(detail) {
            let tOrder = '订单编号:' + detail.orderNo
            let tPay = detail.isRefund == 'Y' && detail.payTotalAmount.toString() != '0' ? '退款总金额：' + detail.payTotalAmount.toString().replace('-', '') + '元' : '\u00a0\u00a0\u00a0\u00a0\u00a0 总支付金额：' + detail.payTotalAmount.toString().replace('-', '') + '元'
            let tTime = '\u00a0\u00a0\u00a0\u00a0\u00a0消费时间：' + detail.createTime

            return tOrder + tPay + tTime
        },
        /** 查询密码充值卡管理列表 */
        getList() {
            this.loading = true
            this.queryParams.params = {}
            if (null != this.daterangeRechargeTime && '' != this.daterangeRechargeTime) {
                this.queryParams['beginRechargeTime'] = this.daterangeRechargeTime[0]
                this.queryParams['endRechargeTime'] = this.daterangeRechargeTime[1]
            } else {
                delete this.queryParams.beginRechargeTime
                delete this.queryParams.endRechargeTime
            }
            if (null != this.daterangeGiveActiveTime && '' != this.daterangeGiveActiveTime) {
                this.queryParams['beginGiveActiveTime'] = this.daterangeGiveActiveTime[0]
                this.queryParams['endGiveActiveTime'] = this.daterangeGiveActiveTime[1]
            } else {
                delete this.queryParams.beginGiveActiveTime
                delete this.queryParams.endGiveActiveTime
            }
            if (null != this.daterangeExpireTime && '' != this.daterangeExpireTime) {
                this.queryParams['beginExpireTime'] = this.daterangeExpireTime[0]
                this.queryParams['endExpireTime'] = this.daterangeExpireTime[1]
            } else {
                delete this.queryParams.beginExpireTime
                delete this.queryParams.endExpireTime
            }
            if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
                this.queryParams['beginCreateTime'] = this.daterangeCreateTime[0]
                this.queryParams['endCreateTime'] = this.daterangeCreateTime[1]
            } else {
                delete this.queryParams.beginCreateTime
                delete this.queryParams.endCreateTime
            }
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                cardNo: null,
                password: null,
                cardVersionId: null,
                rechargeAmount: null,
                giveAmount: null,
                givePointAmount: null,
                rechargeBalance: null,
                giveBalance: null,
                pointBalance: null,
                rechargeStatus: '0',
                rechargeTime: null,
                rechargeStoreId: null,
                rechargeUserId: null,
                expireTime: null,
                orderNo: null,
                createById: null,
                createBy: null,
                createTime: null,
                updateById: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeRechargeTime = []
            this.daterangeExpireTime = []
            this.daterangeCreateTime = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'mapi/recharge/card/export',
                {
                    ...this.queryParams
                },
                `card_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        /** 导入按钮操作 */
        handleImport(num) {
            this.num = num
            this.importForm = {
                level: 0,
                starLevel: 1
            }
            this.upload.title = '充值卡导入'
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            if (this.num == 1) {
                this.download('mapi/recharge/card/importTemplate', {}, `recharge_card_template_${new Date().getTime()}.xlsx`)
            } else {
                this.download('mapi/recharge/card/importDirectChargingTemplate', {}, `direct_recharge_template_${new Date().getTime()}.xlsx`)
            }
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            var respMsg = response.code == '200' ? '' : '导入失败！'
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + respMsg + '<br/>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
            this.getList()
        },
        // 提交上传文件
        submitFileForm() {
            if (!this.importForm.batchName) {
                this.$modal.msgError('请输入批次名称')
                return false
            }
            this.$refs.upload.submit()
        },
        /** 消费明细详情 */
        handleDetail(row) {
            this.reset()
            getCardBillMstrInfo(row.id).then((response) => {
                this.billMstrDataList = response.data
                this.open = true
                this.title = '消费明细详情'
            })
        }
    }
}
</script>
