<template>
    <div class="app-container">
        <el-card class="box-card" shadow="never">
            <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="100px">
                <el-form-item label="充值卡号" prop="cardNo">
                    <el-input
                        v-model="queryParams.cardNo"
                        placeholder="请输入充值卡号"
                        clearable
                        prefix-icon="el-icon-document"
                        style="width: 240px"
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="使用状态" prop="rechargeStatus">
                    <el-select v-model="queryParams.rechargeStatus" placeholder="请选择使用状态" clearable style="width: 240px">
                        <el-option key="0" label="未使用" value="0" />
                        <el-option key="1" label="已使用" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属门店" prop="orgIndex" v-if="userInfoVO.userType == '00'">
                    <el-select v-model="queryParams.orgIndex" placeholder="请选择门店" clearable style="width: 240px">
                        <el-option-group label="客户端">
                            <el-option label="一七总部" value="03" />
                        </el-option-group>
                        <el-option-group label="门店">
                            <el-option v-for="store in storeList" :key="store.id + store.sourceType" :label="store.name" :value="store.id + ',' + store.sourceType" />
                        </el-option-group>
                    </el-select>
                </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-card>

        <el-card class="box-card table-card" shadow="never">
            <div slot="header" class="clearfix">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPermi="['recharge:batchRecord:export']">导出</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </div>

            <el-table v-loading="loading" fit highlight-current-row border stripe :data="recordList" @selection-change="handleSelectionChange">
                <el-table-column label="充值卡号" align="center" prop="cardNo" min-width="190" :show-overflow-tooltip="true" />
                <el-table-column label="所属门店" align="center" min-width="140">
                    <template slot-scope="scope">
                        <span>{{ getStoreName(scope.row) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户名称" align="center" min-width="120">
                    <template slot-scope="scope">
                        <span>{{ scope.row.appUserName || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值金额" align="center" min-width="120">
                    <template slot-scope="scope">
                        <span class="amount">¥{{ scope.row.rechargeAmount }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="赠送信息" align="center" min-width="200">
                    <template slot-scope="scope">
                        <div class="give-info">
                            <el-tag size="mini" type="success" v-if="scope.row.giveAmount > 0">赠送金额：¥{{ scope.row.giveAmount }}</el-tag>
                            <el-tag size="mini" type="warning" v-if="scope.row.givePointAmount > 0">赠送积分：{{ scope.row.givePointAmount }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="剩余金额" align="center" min-width="120">
                    <template slot-scope="scope">
                        <span class="amount">¥{{ scope.row.rechargeBalance }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="剩余赠送" align="center" min-width="120">
                    <template slot-scope="scope">
                        <span class="amount">¥{{ scope.row.giveBalance }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="权限信息" align="center" min-width="400">
                    <template slot-scope="scope">
                        <div class="permission-info">
                            <el-tag size="mini" :type="scope.row.isSupportCloth === 'Y' ? 'success' : 'info'">
                                {{ scope.row.isSupportCloth === 'Y' ? '支持洗衣' : '不支持洗衣' }}
                            </el-tag>
                            <el-tag size="mini" :type="scope.row.isSupportGoods === 'Y' ? 'success' : 'info'">
                                {{ scope.row.isSupportGoods === 'Y' ? '支持商品' : '不支持商品' }}
                            </el-tag>
                            <el-tag size="mini" :type="scope.row.isSupportLife === 'Y' ? 'success' : 'info'">
                                {{ scope.row.isSupportLife === 'Y' ? '支持生活服务' : '不支持生活服务' }}
                            </el-tag>
                            <el-tag size="mini" :type="scope.row.isSupportCar === 'Y' ? 'success' : 'info'">
                                {{ scope.row.isSupportCar === 'Y' ? '支持汽车美容' : '不支持汽车美容' }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="到期时间" align="center" width="160">
                    <template slot-scope="scope">
                        <span>{{ scope.row.expireTime || '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-refresh"
                            @click="handleRefundOrderCard(scope.row)"
                            v-hasPermi="['recharge:batchRecord:edit']"
                            v-if="scope.row.rechargeStatus == '1'"
                        >撤单</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['recharge:batchRecord:edit']"
                            v-if="scope.row.rechargeStatus == '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-card>
    </div>
</template>

<script>
import { allOrg } from '@/api/system/store'
import { listCardDetailByBatchNo, deleteCardByCardId, refundCardByCardId, getOneByBatchNo, addOneCard } from '@/api/recharge/batchRecord'
import { addCard, updateCard } from '@/api/recharge/card'

export default {
    name: 'cardDetail',
    dicts: ['recharge_pay_type', 'recharge_order_status', 'sys_yes_no'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 充值订单表格数据
            recordList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                rechargeCardId: null,
                rechargeStatus: null,
                orgIndex: null,
                cardNo: null,
                rechargeCardIds: []
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                rechargeAmount: [{ required: true, message: '充值金额不能为空', trigger: 'blur' }],
                giveAmount: [{ required: true, message: '赠送金额不能为空', trigger: 'blur' }],
                givePointAmount: [{ required: true, message: '赠送积分不能为空', trigger: 'blur' }],
                welfareAmount: [{ required: true, message: '福利金额不能为空', trigger: 'blur' }],
                storeOrgId: [{ required: true, message: '门店不能为空', trigger: 'blur' }]
            },
            userInfoVO: null,
            storeList: [],
            factoryList: [],
            batchNo: null,
            orgList: [],
            isDirectRecharge: null
        }
    },
    created() {
        this.batchNo = this.$route.params.batchNo
        allOrg().then((res) => {
            this.orgList = res.data
            this.orgList.forEach((org) => {
                if (org.sourceType == '01') {
                    this.factoryList.push(org)
                } else {
                    this.storeList.push(org)
                }
            })
        })
        this.handleUser()
        this.getList()
    },
    computed: {},
    methods: {
        getStoreName(row) {
            let name = '--'
            if (row.rechargeSourceType == '00') {
                name = '一七总部'
            }
            if (row.rechargeSourceType == '03') {
                name = '一七总部'
            }
            if (row.rechargeSourceType == '01') {
                this.factoryList.forEach((org) => {
                    if (org.id == row.rechargeOrgId) {
                        name = '工厂：' + org.name
                    }
                })
            }
            if (row.rechargeSourceType == '02') {
                this.storeList.forEach((org) => {
                    if (org.id == row.rechargeOrgId) {
                        name = '门店：' + org.name
                    }
                })
            }
            return name
        },
        handleUser() {
            this.userInfoVO = this.getUserInfo()
        },
        /** 查询充值订单列表 */
        getList() {
            this.loading = true
            this.queryParams.batchNo = this.batchNo
            if (this.queryParams.orgIndex != null) {
                if (this.queryParams.orgIndex.includes(',')) {
                    this.queryParams.orgId = this.queryParams.orgIndex.split(',')[0]
                    this.queryParams.sourceType = this.queryParams.orgIndex.split(',')[1]
                } else {
                    delete this.queryParams.orgId
                    this.queryParams.sourceType = this.queryParams.orgIndex
                }
            } else {
                delete this.queryParams.orgId
                delete this.queryParams.sourceType
            }
            listCardDetailByBatchNo(this.queryParams).then((response) => {
                this.recordList = response.data.records
                this.total = response.data.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {}
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.rechargeUserId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const id = row.rechargeCardId
            this.$modal
                .confirm('该充值卡未使用，是否确认删除？')
                .then(function () {
                    return deleteCardByCardId(id)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        handleRefundOrderCard(row) {
            const id = row.rechargeCardId
            this.$modal
                .confirm('是否确认撤单？该订单充值金额为"' + row.rechargeAmount + '元"，余额为"' + row.rechargeBalance + '元"')
                .then(function () {
                    return refundCardByCardId(id)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            if (this.ids.length > 0) {
                this.queryParams.rechargeCardIds = this.ids
            } else {
                delete this.queryParams.rechargeCardIds
            }
            this.queryParams.batchNo = this.batchNo
            if (this.queryParams.orgIndex != null) {
                if (this.queryParams.orgIndex.includes(',')) {
                    this.queryParams.orgId = this.queryParams.orgIndex.split(',')[0]
                    this.queryParams.sourceType = this.queryParams.orgIndex.split(',')[1]
                } else {
                    delete this.queryParams.orgId
                    this.queryParams.sourceType = this.queryParams.orgIndex
                }
            } else {
                delete this.queryParams.orgId
                delete this.queryParams.sourceType
            }
            this.downloadJson(
                'mapi/recharge/card/batchRecord/exportCardDetailByBatchNo',
                {
                    ...this.queryParams
                },
                `card_detail_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加充值卡管理'
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.form.batchNo = this.batchNo
                    addOneCard(this.form).then((response) => {
                        this.$modal.msgSuccess('新增成功')
                        this.open = false
                        this.getList()
                    })
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
    background-color: #f5f7fa;

    .box-card {
        margin-bottom: 20px;

        &.table-card {
            margin-bottom: 0;
        }
    }

    :deep(.el-card__header) {
        padding: 15px 20px;
        border-bottom: 1px solid #ebeef5;
    }

    :deep(.el-card__body) {
        padding: 20px;
    }

    .amount {
        color: #f56c6c;
        font-weight: 500;
    }

    .give-info,
    .permission-info {
        .el-tag {
            margin: 0 4px;
            
            &:first-child {
                margin-left: 0;
            }
            
            &:last-child {
                margin-right: 0;
            }
        }
    }
}
</style>
