<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card class="box-card custom-card">
                    <div slot="header" class="clearfix">
                        <span>选择客户</span>
                        <el-button type="primary" style="float: right" plain icon="el-icon-plus" @click="handleAdd" v-if="userInfoVO.userType == '02'">新建客户 </el-button>
                    </div>
                    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px" @submit.native.prevent>
                        <el-form-item label="手机号" prop="phoneNumber">
                            <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable maxlength="11" @change="searchUser" @keyup.enter.native="searchUser" />
                        </el-form-item>
                        <el-form-item>
                            <!--                            <el-button type="primary" icon="el-icon-full-screen" @click="qrcodeSearchUser">扫码</el-button>-->
                            <el-button type="primary" icon="el-icon-search" @click="searchUser">查询</el-button>
                        </el-form-item>
                    </el-form>

                    <el-descriptions title="用户信息" v-if="appUserInfo" :column="2">
                        <el-descriptions-item label="用户名" span="2">{{ appUserInfo.realName }}</el-descriptions-item>
                        <el-descriptions-item label="手机号" span="2">{{ appUserInfo.phoneNumber }} </el-descriptions-item>
                        <el-descriptions-item label="现金余额">
                            {{ (appUserInfo.rechargeBalance * 100) / 100 }}
                        </el-descriptions-item>
                        <el-descriptions-item label="赠送余额">
                            {{ (appUserInfo.giveBalance * 100) / 100 }}
                        </el-descriptions-item>
                        <el-descriptions-item label="福利金">
                            {{ (appUserInfo.welfareBalance * 100) / 100 }}
                        </el-descriptions-item>

                        <el-descriptions-item label="积分">
                            {{ appUserInfo.pointBalance }}
                        </el-descriptions-item>
                        <el-descriptions-item label="等级">{{ appUserInfo.level }}</el-descriptions-item>
                    </el-descriptions>

                    <Page uri="/mapi/recharge/card/list" :request-params="cardParams" ref="pagination" v-if="appUserInfo" :page-size="5">
                        <el-table-column label="卡号" align="center" prop="cardNo" width="100" />
                        <el-table-column label="储值门店" align="center" prop="rechargeStoreName" width="100">
                            <template slot-scope="scope">
                                {{ scope.row.useBindStoreName == null ? '--' : scope.row.useBindStoreName }}
                            </template>
                        </el-table-column>
                        <el-table-column label="充值金额(元)" align="center" prop="rechargeAmount" width="120" />
                        <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="rechargeTime" width="100">
                            <template slot-scope="scope">
                                {{ scope.row.rechargeTime == null ? '--' : scope.row.rechargeTime }}
                            </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>
                    </Page>
                </el-card>
            </el-col>

            <!-- 充值类型 -->
            <el-col :span="12">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>充值信息</span>
                    </div>
                    <el-form ref="rechargeFrom" :model="rechargeFrom" :rules="rules" label-width="160px" @submit.native.prevent>
                        <el-col :span="24">
                            <el-form-item label="请选择充值类型" label-width="120px" prop="rechargeType">
                                <el-col :span="18">
                                    <el-radio-group v-model="rechargeFrom.rechargeType" style="width: 500px" @input="clearData">
                                        <el-radio-button label="3">自定义充值</el-radio-button>
                                        <el-radio-button label="0">套餐充值</el-radio-button>
                                        <el-radio-button label="1">福利金额充值</el-radio-button>
                                        <!--                                        <el-radio-button label="2">卡密充值</el-radio-button>-->
                                    </el-radio-group>
                                </el-col>
                            </el-form-item>

                            <el-form-item label="请选择充值套餐" label-width="120px" prop="rechargeMealId" v-if="rechargeFrom.rechargeType == 0">
                                <el-col :span="18">
                                    <el-select v-model="rechargeFrom.rechargeMealId" placeholder="请选择充值套餐" style="width: 300px" clearable @input="getActivityInfo(rechargeFrom.rechargeMealId)">
                                        <el-option v-for="recharge in rechargeList" :key="recharge.id" :label="recharge.title" :value="recharge.id" />
                                    </el-select>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="自定义金额" label-width="120px" prop="customAmount" v-if="rechargeFrom.rechargeType == 3">
                                <el-col :span="18">
                                    <el-input-number v-model="rechargeFrom.customAmount" :controls="false" :min="0" :max="10000" style="width: 300px"></el-input-number>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="福利金额（元）" label-width="120px" prop="welfareAmount" v-if="rechargeFrom.rechargeType == 1">
                                <el-col :span="18">
                                    <el-input-number v-model="rechargeFrom.welfareAmount" :controls="false" :min="0" :max="999999" style="width: 300px"></el-input-number>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="卡号" label-width="120px" v-if="rechargeFrom.rechargeType == 2" required>
                                <el-col :span="18">
                                    <el-input v-model="rechargeFrom.rechargeCardNo" style="width: 300px"></el-input>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="密码" label-width="120px" v-if="rechargeFrom.rechargeType == 2" required>
                                <el-col :span="18">
                                    <el-input v-model="rechargeFrom.rechargeCardPassword" style="width: 300px"></el-input>
                                </el-col>
                            </el-form-item>
                            <el-form-item label="充值备注" label-width="120px" prop="remark">
                                <el-col :span="18">
                                    <el-input type="textarea" placeholder="请输入充值备注" v-model="rechargeFrom.remark" style="width: 300px"></el-input>
                                </el-col>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-card style="width: 430px" v-if="rechargeFrom.rechargeType == 0">
                                <el-descriptions title="充值活动信息" :column="1" :label-style="{ 'text-align': 'center' }" :contentStyle="{ 'text-align': 'center' }">
                                    <el-descriptions-item label="本次充值金额" style="width: 100px" v-if="activityAmount != null && activityAmount != ''">
                                        {{ getRechargeTypeInfo == '' ? '--' : getRechargeTypeInfo.rechargeAmount }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="原赠送金额" v-if="activityAmount != null && activityAmount != ''">
                                        {{ getRechargeTypeInfo == '' ? '--' : getRechargeTypeInfo.giveAmount }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="活动赠送金额" v-if="activityAmount != null && activityAmount != ''">
                                        {{ activityAmount }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="参与活动" v-if="activityAmount == null || activityAmount == ''"> 此套餐暂未参与活动 </el-descriptions-item>
                                </el-descriptions>
                            </el-card>
                        </el-col>
                        <!--            <el-col :span="24">-->
                        <!--              <el-card class="box-card" shadow="hover" style="width: 150px" @click.native="clickRecharge">-->
                        <!--                <div slot="header" class="clearfix">-->
                        <!--                  <span></span>-->
                        <!--                  <span style="float: right">赠送500元</span>-->
                        <!--                </div>-->
                        <!--                <div class="text item">-->
                        <!--                  <span>{{'充值金额 ' + "1" }}</span>-->
                        <!--                  <span>{{'充值金额 ' + "1" }}</span>-->
                        <!--                </div>-->
                        <!--              </el-card>-->
                        <!--            </el-col>-->
                    </el-form>
                    <div>
                        <el-button type="primary" @click="submitCash" style="margin-left: 3%; margin-top: 20px">收银 </el-button>
                    </div>
                </el-card>
            </el-col>
        </el-row>
      <el-dialog title="确认充值" :visible.sync="openWelfareRecharge" width="400px">
        <el-form ref="payFrom" :model="rechargeInfo" label-width="100px" style="margin-top: 20px" @submit.native.prevent>
          <el-form-item label="充值金额：">
            <span style="font-size: 16px;font-weight: bold">￥{{rechargeInfo.welfareAmount}}</span>
          </el-form-item>
          <el-form-item label="备注：" >
            <span style="font-size: 16px;font-weight: bold">{{rechargeInfo.remark}}</span>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="submitSettlement" style="margin: 20px 80px 0; width: 200px; height: 40px">确认</el-button>
      </el-dialog>
        <!-- 支付方式 -->
        <el-dialog :title="rechargeTitle" :visible.sync="openRecharge" width="75%" :before-close="checkClosePay">
            <el-descriptions title="核对信息" v-if="rechargeInfo && appUserInfo" :column="4" border :contentStyle="{ 'text-align': 'center' }">
                <el-descriptions-item label="本次充值金额" :labelStyle="{ width: '14%' }">{{ rechargeInfo.rechargeAmount }} </el-descriptions-item>
                <el-descriptions-item label="本次赠送金额" :labelStyle="{ width: '14%' }">
                    {{ activityAmount != null && activityAmount != '' ? activityAmount : rechargeInfo.giveAmount }}
                </el-descriptions-item>
                <el-descriptions-item label="本次赠送积分" :labelStyle="{ width: '14%' }">
                    {{ rechargeInfo.givePointAmount }}
                </el-descriptions-item>
                <el-descriptions-item label="本次福利金额" :labelStyle="{ width: '14%' }">{{ rechargeInfo.welfareAmount }} </el-descriptions-item>

                <el-descriptions-item label="充值余额">{{ appUserInfo.rechargeBalance }}</el-descriptions-item>
                <el-descriptions-item label="赠送余额">{{ appUserInfo.giveBalance }}</el-descriptions-item>
                <el-descriptions-item label="现有积分">{{ appUserInfo.pointBalance }}</el-descriptions-item>
                <el-descriptions-item label="福利余额">{{ appUserInfo.welfareBalance }}</el-descriptions-item>

                <el-descriptions-item label="充值后余额">
                    {{ (rechargeInfo.rechargeAmount * 100 + appUserInfo.rechargeBalance * 100) / 100 }}
                </el-descriptions-item>
                <el-descriptions-item label="充值后赠送余额">
                    {{ activityAmount != null && activityAmount != '' ? (activityAmount * 100 + appUserInfo.giveBalance * 100) / 100 : (rechargeInfo.giveAmount * 100 + appUserInfo.giveBalance * 100) / 100 }}
                </el-descriptions-item>
                <el-descriptions-item label="充值后积分">
                    {{ (rechargeInfo.givePointAmount * 100 + appUserInfo.pointBalance * 100) / 100 }}
                </el-descriptions-item>
                <el-descriptions-item label="充值后福利余额">
                    {{ (rechargeInfo.welfareAmount * 100 + appUserInfo.welfareBalance * 100) / 100 }}
                </el-descriptions-item>
            </el-descriptions>

            <template v-if="rechargeInfo">
                <el-form ref="payFrom" :model="payFrom" label-width="80px" style="margin-top: 20px" @submit.native.prevent>
                    <el-card>
                        <!--                        <el-row :gutter="10" style="margin-top: 10px">-->
                        <!--                            <el-col :span="24">-->
                        <!--                                <el-checkbox v-model="payFrom.isUsedCoupon">是否使用优惠券</el-checkbox>-->
                        <!--                                <el-button style="margin-left: 10px" v-if="payFrom.isUsedCoupon" type="primary" @click="openCouponList">选择优惠券列表</el-button>-->
                        <!--                            </el-col>-->
                        <!--                        </el-row>-->
                        <el-row :gutter="10" style="margin-top: 10px">
                            <el-col :span="12" style="margin-top: 10px">
                                <el-form-item label="支付方式" label-width="150px" prop="payType">
                                    <el-radio-group v-model="payFrom.payType" @input="changePayType">
                                        <el-radio-button label="2">现金</el-radio-button>
                                        <el-radio-button label="0">微信/支付宝</el-radio-button>
<!--                                        <el-radio-button label="1">支付宝</el-radio-button>-->
                                        <el-radio-button label="9">组合支付</el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
<!--                            <el-col :span="12">-->
<!--                                <el-form-item label="是否分段支付" label-width="150px" prop="isInstalment">-->
<!--                                    <el-radio-group v-model="payFrom.isInstalment" :disabled="alreadyPayTotal > 0">-->
<!--                                        <el-radio-button label="Y">是</el-radio-button>-->
<!--                                        <el-radio-button label="N">否</el-radio-button>-->
<!--                                    </el-radio-group>-->
<!--                                </el-form-item>-->
<!--                            </el-col>-->
                        </el-row>
                        <el-row style="margin-top: 10px; margin-left: 20px">
                            <div class="clearfix">
                              <!--                                <span>已优惠<span style="color: #ff4949; font-size: 18px; font-weight: bold; margin: 0 4px">{{ getCouponAmount }}</span>元</span>-->
                                                              <span style="margin-left: 20px">需支付<span style="color: #ff4949; font-size: 18px; font-weight: bold; margin: 0 4px">{{ (getOrderNeedAmount * 100 - parseFloat(alreadyPayTotal * 100)) / 100 }}</span>元</span>
                                                          </div>
                                                      </el-row>
                                                      <el-row :gutter="10" style="margin-top: 10px">
                                                          <!--                            <el-col :span="8">-->
                            <!--                                <el-form-item label="已经支付：" label-width="90px" v-if="payFrom.isInstalment == 'Y'">-->
                            <!--                                    <span>{{ alreadyPayTotal }} 元</span>-->
                            <!--                                </el-form-item>-->
                            <!--                            </el-col>-->
                            <el-col :span="8">
                                <el-form-item label="本次收取金额（元）" label-width="150px" prop="thisPayMoney" v-if="payFrom.isInstalment == 'Y'">
                                    <el-input style="width: 250px" v-model="payFrom.thisPayMoney"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-button type="primary" @click="submitConfirm" v-if="(payFrom.payType == '0' || payFrom.payType == '1') && payFrom.isInstalment == 'Y' && payConfirm == false"> 确认 </el-button>
                            </el-col>
                        </el-row>

                        <el-row :gutter="10" style="margin-top: 10px">
                            <el-col :span="8">
                                <el-form-item label="付款条形码" label-width="150px" prop="wxBarcode" v-if="payFrom.payType == '0'">
                                    <el-input style="width: 250px" v-model="payFrom.wxBarcode" clearable placeholder="请输入付款码"></el-input>
                                </el-form-item>
                            </el-col>
<!--                            <el-col :span="8">-->
<!--                                <el-form-item label="实收现金（元）" label-width="150px" prop="thisPayMoney" v-if="payFrom.payType == '2'">-->
<!--                                    <el-input-number style="width: 250px" :controls="false" v-model="payFrom.thisPayMoney"></el-input-number>-->
<!--                                </el-form-item>-->
<!--                            </el-col>-->
                            <el-col :span="8">
                                <el-form-item label="实收现金（元）" label-width="150px" prop="cashPayAmount" v-if="payFrom.payType == '9'">
                                    <el-input style="width: 250px" :controls="false" v-model="payFrom.cashPayAmount" @input="changeCashPayAmount"></el-input>
                                </el-form-item>
                                <el-form-item label="微信/支付宝（元）" label-width="150px" prop="otherPayAmount" v-if="payFrom.payType == '9'">
                                    <!--                                    <el-input-number style="width: 250px" :controls="false" disabled v-model="payFrom.otherPayAmount"></el-input-number>-->
                                    <span style="font-size: 16px;font-weight: bold">￥{{payFrom.otherPayAmount || 0}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="" label-width="150px" prop="wxBarcode" v-if="payFrom.payType == '9'">
                                    <el-input-number style="width: 250px; opacity: 0" :controls="false" disabled v-model="payFrom.otherPayAmount"></el-input-number>
                                </el-form-item>
                                <el-form-item label="付款条形码" label-width="150px" prop="wxBarcode" v-if="payFrom.payType == '9'">
                                    <el-input style="width: 250px" v-model="payFrom.wxBarcode" clearable placeholder="请输入付款码"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">

                            </el-col>
                        </el-row>
                        <!--                        <el-row :gutter="10" style="margin-top: 10px">-->
                        <!--                            <el-card>-->
                        <!--                                <el-table :data="alreadySelectCouponList">-->
                        <!--                                    &lt;!&ndash;      <el-table-column label="编号" align="center" prop="id" />&ndash;&gt;-->
                        <!--                                    <el-table-column label="优惠券" align="center" prop="couponTypeTitle" />-->
                        <!--                                    <el-table-column label="优惠内容" align="center" prop="clothItemTypeName">-->
                        <!--                                        <template slot-scope="scope">-->
                        <!--                                            <span>抵扣充值金额：{{ scope.row.deductRechargeAmount }}元</span>-->
                        <!--                                        </template>-->
                        <!--                                    </el-table-column>-->
                        <!--                                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
                        <!--                                        <template slot-scope="scope">-->
                        <!--                                            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>-->
                        <!--                                        </template>-->
                        <!--                                    </el-table-column>-->
                        <!--                                </el-table>-->
                        <!--                            </el-card>-->
                        <!--                        </el-row>-->
                    </el-card>
                    <el-row :gutter="10">
                        <div>
                            <el-button type="primary" @click="submitSettlement" style="margin-left: 5px; margin-top: 20px">结算 </el-button>
                        </div>
                    </el-row>
                </el-form>
            </template>
        </el-dialog>

        <el-dialog title="选择优惠券" :visible.sync="openCoupon" width="60%">
            <template>
                <el-table :data="couponList" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" fixed="left" />
                    <el-table-column label="优惠券" align="center" prop="couponTypeTitle" />
                    <el-table-column label="优惠内容" align="center">
                        <template slot-scope="scope">
                            <span>抵扣充值金额：{{ scope.row.deductRechargeAmount }}元</span>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row>
                    <div style="margin-top: 30px">
                        <el-button @click="submitAlreadySelectCouponList" size="small" type="primary" style="float: right"> 确定 </el-button>
                    </div>
                </el-row>
            </template>
        </el-dialog>

        <!-- 添加用户对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="30%" append-to-body :before-close="checkCloseUserPage">
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="昵称" prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入昵称" maxlength="50" show-word-limit clearable />
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="realName">
                            <el-input v-model="form.realName" placeholder="请输入真实姓名" maxlength="5" show-word-limit clearable />
                        </el-form-item>
                        <el-form-item label="手机号" prop="phoneNumber">
                            <el-input v-model="form.phoneNumber" placeholder="请输入手机号" maxlength="11" show-word-limit clearable />
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择性别" clearable>
                                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="生日" prop="birthday" clearable>
                            <el-date-picker clearable v-model="form.birthday" type="date" value-format="yyyy-MM-dd" placeholder="请选择生日"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="头像地址" prop="avatarUrl">
                            <image-upload v-model="form.avatarUrl" :limit="1" />
                        </el-form-item>
                        <el-form-item label="客户等级" prop="level">
                            <el-input-number v-model="form.level" :min="1" :max="50" label="请输入客户等级"></el-input-number>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入备注" maxlength="50" show-word-limit />
                        </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 { listType } from '@/api/recharge/type'
import { addUser, findUserByPhoneNumber, getMemberCouponInfoByRecharge, updateUser } from '@/api/app/user'
import { addOrder, getOrderIsAllPayByOrderNo, getOrderStatusByOrderNo, morePay } from '@/api/recharge/order'
import { getRechargeTypeRelationActivityInfo } from '@/api/activity/rechargeItem'

export default {
    name: 'workRecharge',
    dicts: ['recharge_use_status', 'sys_user_sex'],
    data() {
        return {
            alreadyPayTotal: 0,
            orderNeedPayAmount: 0,
            couponAmount: 0,
            alreadyPayInfo: {},
            payConfirm: false,
            payFrom: {},
            userInfoVO: null,
            orderNo: null,
            // 优惠卷
            // couponInfo:null,
            couponList: [],
            // 客户信息
            appUserInfo: null,
            rechargeList: null,
            rechargeInfo: {},
            // 充值类型参数
            rechargeFrom: {
                rechargeType: '3',
                // 充值套餐id
                rechargeMealId: null,
                // 自定义金额
                customAmount: null,
                remark: '',
                // 福利金额
                welfareAmount: null,
                // 卡号
                rechargeCardNo: null,
                // 密码
                rechargeCardPassword: null
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            // 弹出层标题
            title: '',
            rechargeTitle: '',
            // 是否显示弹出层
            open: false,
            openRecharge: false,
          openWelfareRecharge: false,
            openCoupon: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            cardParams: {
                rechargeUserId: 0
            },
            couponParams: {
                pageNum: 1,
                pageSize: 999,
                appUserId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                rechargeCardNo: [
                    {
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                        required: true,
                        message: '请输入正整数类型',
                        trigger: 'blur'
                    }
                ],
                rechargeCardPassword: [
                    {
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                        required: true,
                        message: '请输入正整数类型',
                        trigger: 'blur'
                    }
                ],
                nickName: [
                    {
                        required: true,
                        message: '昵称不能为空',
                        trigger: 'blur'
                    }
                ],
                realName: [
                    {
                        required: true,
                        message: '真实姓名不能为空',
                        trigger: 'blur'
                    }
                ],
                phoneNumber: [
                    {
                        required: true,
                        message: '手机号不能为空',
                        trigger: 'blur'
                    },
                    {
                        pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                        required: true,
                        message: '请输入数量，且为正整数类型',
                        trigger: 'blur'
                    },
                    { min: 11, max: 11, message: '手机号至少11位', trigger: 'blur' }
                ],
                sex: [
                    {
                        required: true,
                        message: '性别不能为空',
                        trigger: 'blur'
                    }
                ],
                birthday: [
                    {
                        required: true,
                        message: '生日不能为空',
                        trigger: 'blur'
                    }
                ]
            },
            authCode: null,
            activityAmount: null,
            alreadySelectCouponList: [],
            //支付检测
            isPaying: false
        }
    },
    created() {
        this.handleUser()
        this.getRechargeList()
    },
    computed: {
        getRechargeTypeInfo() {
            if (this.rechargeFrom.rechargeMealId != null) {
                return this.rechargeList.find((item) => item.id == this.rechargeFrom.rechargeMealId)
            } else {
                return ''
            }
        },
        getCouponAmount() {
            this.couponAmount = 0
            if (this.alreadySelectCouponList.length == 0) {
                return this.couponAmount
            }
            if (this.alreadySelectCouponList.length > 0) {
                this.alreadySelectCouponList.forEach((coupon) => {
                    this.couponAmount = this.couponAmount + parseFloat(coupon.deductRechargeAmount)
                })
            }
            return this.couponAmount
        },
        getOrderNeedAmount() {
            this.orderNeedPayAmount = parseFloat(this.rechargeInfo.rechargeAmount) - parseFloat(this.couponAmount) > 0 ? parseFloat(this.rechargeInfo.rechargeAmount) - parseFloat(this.couponAmount) : 0
            return this.orderNeedPayAmount
        }
    },
    methods: {
        changeCashPayAmount(value) {
          this.payFrom.cashPayAmount = value.replace(/[^\d]/g,'')
            this.payFrom.otherPayAmount = Number(this.orderNeedPayAmount) - Number(this.payFrom.cashPayAmount)
        },
        clickRecharge(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        getActivityInfo(rechargeTypeId) {
            if (rechargeTypeId != null && rechargeTypeId != '') {
                getRechargeTypeRelationActivityInfo(rechargeTypeId, this.userInfoVO.storeId).then((response) => {
                    this.activityAmount = response.data
                })
            } else {
                this.activityAmount = null
            }
        },
        clearData() {
            this.rechargeFrom.rechargeMealId = null
            this.rechargeFrom.customAmount = null
            this.rechargeFrom.welfareAmount = null
            this.rechargeFrom.rechargeCardNo = null
            this.rechargeFrom.rechargeCardPassword = null
            this.activityAmount = null
        },
        openCouponList() {
            this.getCouponList()
            this.openCoupon = true
        },
        // 获取优惠券集合
        getCouponList() {
            if (this.appUserInfo == null) {
                this.couponList = []
                return
            }
            this.couponParams.appUserId = this.appUserInfo.id
            getMemberCouponInfoByRecharge(this.couponParams).then((response) => {
                this.couponList = response.data.records
            })
        },
        // 获取登录人信息
        handleUser() {
            this.userInfoVO = this.getUserInfo()
        },
        //搜索用户
        searchUser() {
            this.$refs['queryForm'].validate((valid) => {
                if (valid) {
                    findUserByPhoneNumber(this.queryParams).then((res) => {
                        this.appUserInfo = res.data
                        if (this.appUserInfo) {
                            this.cardParams.rechargeUserId = this.appUserInfo.id
                            this.$nextTick(() => {
                                this.$refs.pagination.handleSearch(true)
                            })
                        }
                    })
                }
            })
        },
        //条码搜索用户
        qrcodeSearchUser() {},
        // 获取 充值套餐集合
        getRechargeList() {
            listType().then((response) => {
                this.rechargeList = response.rows
            })
        },
        // 关闭用户新建页面 二次确认
        checkCloseUserPage(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        // 关闭支付页面 二次确认
        checkClosePay(done) {
            this.$confirm('退单金额如下:现金:' + this.alreadyPayInfo.alreadyPayCash + '，微信:' + this.alreadyPayInfo.alreadyPayWX + ',支付宝:' + this.alreadyPayInfo.alreadyPayAli + '  是否暂停支付?')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        // 创建用户
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateUser(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                        })
                    } else {
                        addUser(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                        })
                    }
                }
            })
        },
        // 收银
        submitCash() {
            if (this.appUserInfo == null) {
                this.$message.error('请选择客户')
                return
            }
            // 重置
            this.resetPayInfo()
            this.rechargeInfo.remark = this.rechargeFrom.remark
            // 自定义充值
            if (this.rechargeFrom.rechargeType == '3') {
                if (this.rechargeFrom.customAmount == '0') {
                    this.$message.error('充值金额不能为0元')
                    return
                }
                this.rechargeInfo.rechargeAmount = this.rechargeFrom.customAmount
                this.rechargeInfo.giveAmount = 0
                this.rechargeInfo.givePointAmount = 0
                this.rechargeInfo.welfareAmount = 0
                this.rechargeInfo.rechargeType = this.rechargeFrom.rechargeType
                this.rechargeInfo.rechargeTypeId = null
            }
            // 套餐充值
            if (!this.rechargeFrom.rechargeType || this.rechargeFrom.rechargeType == '0') {
                if (this.rechargeFrom.rechargeMealId == null) {
                    this.$message.error('充值套餐不能为空')
                    return
                }
                let recharge
                recharge = this.rechargeList.find((item) => item.id == this.rechargeFrom.rechargeMealId)
                this.rechargeInfo.rechargeAmount = recharge.rechargeAmount
                this.rechargeInfo.giveAmount = recharge.giveAmount
                this.rechargeInfo.givePointAmount = recharge.givePointAmount
                this.rechargeInfo.welfareAmount = 0
                this.rechargeInfo.rechargeType = this.rechargeFrom.rechargeType
                this.rechargeInfo.rechargeTypeId = recharge.id
            }
            // 福利金额充值
            if (this.rechargeFrom.rechargeType == '1') {
                if (!this.rechargeFrom.rechargeType ||  this.rechargeFrom.welfareAmount == '0') {
                    this.$message.error('充值金额不能为0元')
                    return
                }
                if (!this.rechargeFrom.remark) {
                  this.$message.error('请输入备注')
                  return
                }

                this.rechargeInfo.rechargeAmount = 0
                this.rechargeInfo.giveAmount = 0
                this.rechargeInfo.givePointAmount = 0
                this.rechargeInfo.welfareAmount = this.rechargeFrom.welfareAmount
                this.rechargeInfo.rechargeType = this.rechargeFrom.rechargeType
                this.rechargeInfo.rechargeTypeId = null
              this.rechargeInfo.remark = this.rechargeFrom.remark
              this.openWelfareRecharge = true
              this.orderNo = null
              return;
            }
            // 卡密充值
            if (this.rechargeFrom.rechargeType == '2') {
                if (this.rechargeFrom.rechargeCardNo == null || this.rechargeFrom.rechargeCardPassword == null) {
                    this.$message.error('卡号/密码，不能为空')
                    return
                }
                const orderRechargePayDTO = {
                    appUserId: this.appUserInfo.id,
                    rechargeType: this.rechargeFrom.rechargeType,
                    cardNo: this.rechargeFrom.rechargeCardNo,
                    password: this.rechargeFrom.rechargeCardPassword,
                    remark: this.rechargeFrom.remark
                }
                addOrder(orderRechargePayDTO).then((response) => {
                    if (response.data.isAllPayEnd == true) {
                        this.$modal.msgSuccess('充值成功')
                        this.searchUser()
                        this.clearData()
                    }
                })
                return
            }

            this.rechargeTitle = '支付方式选择'
            this.openRecharge = true
            this.orderNo = null
        },
        // 结算
        submitSettlement() {
            // if (this.payFrom.payType == '2' && this.payFrom.isInstalment == 'N' && this.payFrom.thisPayMoney < this.orderNeedPayAmount) {
            //     this.$message.error('支付金额小于需支付金额')
            //     return
            // }
            // if (this.payFrom.payType == '2' && this.payFrom.isInstalment == 'N' && this.payFrom.thisPayMoney > this.orderNeedPayAmount) {
            //     this.$message.error('支付金额大于需支付金额')
            //     return
            // }
            const orderRechargePayDTO = {
                orderNo: this.orderNo,
                appUserId: this.appUserInfo.id,
                payType: this.payFrom.payType,
                isInstalment: this.payFrom.isInstalment,
                couponIds: [],
                remark: this.rechargeInfo.remark,
                rechargeAmount: this.rechargeInfo.rechargeAmount,
                giveAmount: this.rechargeInfo.giveAmount,
                givePointAmount: this.rechargeInfo.givePointAmount,
                rechargeTypeId: this.rechargeInfo.rechargeTypeId,
                welfareAmount: this.rechargeInfo.welfareAmount,
                rechargeType: this.rechargeInfo.rechargeType,
                payAmount: this.orderNeedPayAmount,
            }
            if (this.alreadySelectCouponList.length > 0) {
                this.alreadySelectCouponList.forEach((vo) => {
                    orderRechargePayDTO.couponIds.push(vo.id)
                })
            } else {
                orderRechargePayDTO.couponIds = []
            }
            if (this.payFrom.isInstalment == 'N') {
                orderRechargePayDTO.thisPayAmount = this.orderNeedPayAmount
            }
            if (this.payFrom.isInstalment == 'Y') {
                orderRechargePayDTO.thisPayAmount = this.payFrom.thisPayMoney
            }
            // 现金支付
            if (this.payFrom.payType == 2) {
                orderRechargePayDTO.thisPayAmount = this.orderNeedPayAmount
            }
            // 微信支付
            if (this.payFrom.payType == 0) {
                orderRechargePayDTO.authCode = this.payFrom.wxBarcode
            }
            // 支付宝支付
            if (this.payFrom.payType == 1) {
                orderRechargePayDTO.authCode = this.payFrom.aliPayBarcode
            }

            if (this.payFrom.payType == 9) {
                if (!this.payFrom.cashPayAmount) {
                    this.$message.error('请输入现金支付金额')
                    return
                }
                if (Number(this.payFrom.cashPayAmount) >= Number(this.orderNeedPayAmount)) {
                    this.$message.error('现金支付金额必须小于还需支付金额')
                    return
                }
                orderRechargePayDTO.cashPayAmount = this.payFrom.cashPayAmount || 0
                orderRechargePayDTO.otherPayAmount = this.payFrom.otherPayAmount || 0
            }

            this.$confirm('确定进行支付结算吗？')
                .then(() => {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    })
                    if (this.orderNo == null) {
                        // 首次支付
                        addOrder(orderRechargePayDTO).then((response) => {
                            loading.close()
                            this.orderNo = response.data.orderNo
                            // 第三方支付
                            if (this.payFrom.payType == '0' || this.payFrom.payType == '1' || (this.payFrom.payType == '9' && this.payFrom.otherPayAmount)) {
                                this.isPaying = true
                                var intervalId = setInterval(() => {
                                    this.intervalCheckOrderStatus(intervalId, this.orderNo)
                                }, 4000)
                            } else {
                                this.checkIsAllPay(this.orderNo)
                            }
                            if (orderRechargePayDTO.isInstalment == 'Y') {
                                this.$confirm('本次支付完成，是否继续支付')
                                    .then(() => {
                                        this.alreadyPayTotal = this.alreadyPayTotal + parseFloat(this.payFrom.thisPayMoney)
                                        this.saveAlreadyPayAmount()
                                    })
                                    .catch(() => {
                                        this.openRecharge = false
                                        this.orderNo = null
                                        this.$modal.msgWarning('确定关闭本次充值吗？关闭后如需完成支付请前往订单管理继续支付')
                                    })
                            }
                        }, err => {
                          loading.close()
                        })
                    } else {
                        // 多次支付
                        morePay(orderRechargePayDTO).then((response) => {
                            loading.close()
                            if (response.data.payResult != 200) {
                                this.$message.error(response.data.payMsg)
                                return
                            }
                            if (this.payFrom.payType == '0' || this.payFrom.payType == '1') {
                                //第三方支付
                                console.log('第三方支付')
                                this.isPaying = true
                                var intervalId = setInterval(() => {
                                    this.intervalCheckOrderStatus(intervalId, response.data.orderNo)
                                }, 4000)
                            } else {
                                this.checkIsAllPay(this.orderNo)
                            }
                            if (orderRechargePayDTO.isInstalment == 'Y') {
                                this.$confirm('本次支付完成，是否继续支付')
                                    .then(() => {
                                        this.alreadyPayTotal = this.alreadyPayTotal + parseFloat(this.payFrom.thisPayMoney)
                                        this.saveAlreadyPayAmount()
                                    })
                                    .catch(() => {
                                        this.openRecharge = false
                                        this.orderNo = null
                                        this.$modal.msgWarning('确定关闭本次充值吗？关闭后如需完成支付请前往订单管理继续支付')
                                    })
                            }
                        })
                    }
                })
                .catch(() => {})
        },
        intervalCheckOrderStatus(intervalId, orderNo) {
            getOrderStatusByOrderNo({ orderNo: orderNo }).then((response) => {
                if (response.data == '0') {
                    return
                }
                this.isPaying = false
                if (response.data == '100') {
                    //已取消
                    this.$notify.error({
                        title: '支付失败',
                        message: '支付超时或客户已取消支付'
                    })
                    clearInterval(intervalId)
                    return
                }
                this.$notify({
                    title: '支付成功',
                    message: '客户已成功支付订单',
                    type: 'success'
                })
                this.openRecharge = false
                this.searchUser()
                clearInterval(intervalId)
            })
        },
        checkIsAllPay(orderNo) {
            // getOrderIsAllPayByOrderNo({ orderNo: orderNo }).then((response) => {
            //     if (response.data == true) {
                    this.$modal.msgSuccess('支付成功')
                    this.openRecharge = false
          this.openWelfareRecharge = false
                    this.searchUser()
                // }
            // })
        },
        // 保存临时的  支付金额 用于取消支付提示信息
        saveAlreadyPayAmount() {
            // 微信
            if (this.payFrom.payType == '0') {
                this.alreadyPayInfo.alreadyPayWX = this.alreadyPayInfo.alreadyPayWX + parseFloat(this.payFrom.thisPayMoney)
            }
            // 支付宝
            if (this.payFrom.payType == '1') {
                this.alreadyPayInfo.alreadyPayAli = this.alreadyPayInfo.alreadyPayAli + parseFloat(this.payFrom.thisPayMoney)
            }
            // 现金
            if (this.payFrom.payType == '2') {
                this.alreadyPayInfo.alreadyPayCash = this.alreadyPayInfo.alreadyPayCash + parseFloat(this.payFrom.thisPayMoney)
            }
        },
        // 支付页面 确认按钮
        submitConfirm() {
            this.payConfirm = true
        },
        // 切换支付方式
        changePayType() {
            this.payConfirm = false
            this.payFrom.thisPayMoney = null
            this.payFrom.aliPayBarcode = null
            this.payFrom.wxBarcode = null
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                phoneNumber: null,
                nickName: null,
                realName: null,
                sex: null,
                birthday: null,
                avatarUrl: null,
                unionId: null,
                createTime: null,
                payPassword: null,
                isUsePayPassword: null,
                status: '0',
                level: null
            }
            this.resetForm('form')
        },
        resetPayInfo() {
            this.alreadyPayTotal = 0
            this.couponAmount = 0
            this.payConfirm = false
            this.rechargeInfo = {}
            this.alreadySelectCouponList = []
            this.payFrom = {
                payType: '2',
                isInstalment: 'N',
                wxBarcode: null,
                aliPayBarcode: null,
                thisPayMoney: 0,
                isUsedCoupon: false
            }
            this.alreadyPayInfo = {
                alreadyPayWX: 0,
                alreadyPayCash: 0,
                alreadyPayAli: 0
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加用户'
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        submitAlreadySelectCouponList() {
            this.alreadySelectCouponList = []
            this.ids.forEach((id) => {
                const vo = this.couponList.find((item) => item.id == id)
                this.alreadySelectCouponList.push(vo)
            })
            this.openCoupon = false
        },
        handleDelete(row) {
            this.alreadySelectCouponList = this.alreadySelectCouponList.filter((item) => item.id != row.id)
            this.$forceUpdate()
        }
    }
}
</script>
<style></style>
