<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <!--      <el-form-item label="充值编号" prop="rechargeCardId">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.rechargeCardId"-->
            <!--          placeholder="请输入充值编号"-->
            <!--          clearable-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <el-form-item prop="cardNo">
                <el-input v-model="queryParams.cardNo" placeholder="请输入充值卡号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!--      <el-form-item label="客户名称" prop="appUserName">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.appUserName"-->
            <!--          placeholder="请输入客户名称"-->
            <!--          clearable-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <el-form-item prop="rechargeStatus" label-width="130">
                <el-select v-model="queryParams.rechargeStatus" placeholder="请选择使用状态" clearable>
                    <el-option key="0" label="未使用" value="0" />
                    <el-option key="1" label="已使用" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label-width="120px" prop="orgIndex" v-if="userInfoVO.userType == '00'">
                <el-select v-model="queryParams.orgIndex" placeholder="请选择门店" clearable>
                    <!-- <el-option-group label="工厂">
                        <template>
                            <el-option v-for="factory in factoryList" :key="factory.id + factory.sourceType" :label="factory.name" :value="factory.id + ',' + factory.sourceType"> </el-option>
                        </template>
                    </el-option-group> -->
                    <el-option-group label="客户端">
                        <template>
                            <el-option label="一七总部" value="03"> </el-option>
                        </template>
                    </el-option-group>
                    <el-option-group label="门店">
                        <template>
                            <el-option v-for="store in storeList" :key="store.id + store.sourceType" :label="store.name" :value="store.id + ',' + store.sourceType"> </el-option>
                        </template>
                    </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-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>
            <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['recharge:batchRecord:add']">新增充值卡</el-button>
            </el-col> -->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" fit highlight-current-row border stripe :data="recordList" @selection-change="handleSelectionChange">
            <el-table-column label="充值卡号" align="center" prop="cardNo" width="190" />
            <el-table-column label="所属门店" align="center" width="140">
                <template slot-scope="scope">
                    <span>
                        {{ getStoreName(scope.row) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="客户名称" align="center" prop="appUserName" width="120">
                <template slot-scope="scope">
                    {{ scope.row.appUserName == null ? '--' : scope.row.appUserName }}
                </template>
            </el-table-column>
            <el-table-column label="现金金额（元）" align="center" prop="rechargeAmount" width="120" />
            <el-table-column label="赠送金额（元）" align="center" prop="giveAmount" width="120" />
            <el-table-column label="剩余现金金额（元）" align="center" prop="rechargeBalance" width="140" />
            <el-table-column label="剩余赠送余额（元）" align="center" prop="giveBalance" width="140" />
            <el-table-column label="是否支持洗衣" align="center" prop="isSupportCloth" width="110">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSupportCloth" />
                </template>
            </el-table-column>
            <el-table-column label="是否支持商品" align="center" prop="isSupportGoods" width="110">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSupportGoods" />
                </template>
            </el-table-column>
            <el-table-column label="是否支持生活服务" align="center" prop="isSupportLife" width="130">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSupportLife" />
                </template>
            </el-table-column>
            <el-table-column label="是否支持汽车美容" align="center" prop="isSupportCar" width="130">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSupportCar" />
                </template>
            </el-table-column>
            <el-table-column label="到期时间" align="center" prop="expireTime" width="180">
                <template slot-scope="scope">
                    {{ scope.row.expireTime == null ? '--' : scope.row.expireTime }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" @click="handleRefundOrderCard(scope.row)" v-hasPermi="['recharge:batchRecord:edit']" v-if="scope.row.rechargeStatus == '1'">撤单</el-button>
                    <el-button type="text" icon="el-icon-edit" @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-dialog :title="title" :visible.sync="open" size="30%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="充值门店" prop="storeOrgId" label-width="130px">
                            <el-select v-model="form.storeOrgId" placeholder="充值门店" clearable>
                                <el-option v-for="store in storeList" :label="store.name" :value="store.id" :key="store.name"> </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="充值金额（元）" prop="rechargeAmount" label-width="130px">
                            <el-input-number :min="1" :max="9999999" :controls="false" v-model="form.rechargeAmount" />
                        </el-form-item>
                        <el-form-item label="赠送金额（元）" prop="giveAmount" label-width="130px">
                            <el-input-number :min="1" :max="9999999" :controls="false" v-model="form.giveAmount" />
                        </el-form-item>
                        <el-form-item label="福利金额（元）" prop="welfareAmount" label-width="130px">
                            <el-input-number :min="1" :max="9999999" :controls="false" style="width: 200px" v-model="form.welfareAmount" />
                        </el-form-item>
                        <el-form-item label="赠送积分（元）" prop="givePointAmount" label-width="130px">
                            <el-input-number :min="1" :max="9999999" :controls="false" style="width: 200px" v-model="form.givePointAmount" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="appUserPhoneNumber" label-width="130px">
                            <el-input v-model="form.appUserPhoneNumber" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </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>
