<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('会员设置')" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
<!--    <script src="../../../../static/js/remote-search-coupon.js"></script>-->
</head>
<style>
    .avatar_img {
        float: left;
    }
    .text_menber {
        width: 600px;
        height: 100px !important;
    }
    .price_item .col-sm-10{
        width: 200px;
    }
    .interests_column {
        width: 100%;
        float: left;
    }
    .interests_column:after {
        clear: both;
    }
    .modal-body { max-height: 70vh; overflow-y: auto; }
    #modalRightsArea .interests_item {
        width: 100%;
        height: auto;
        float: none;
        margin-left: 0 !important;
    }
    .interests_item {
        width: 500px;
        height: 950px;
        float: left;
        margin-left: 126px !important;
    }
    .interests_item .form-control {
        margin-bottom: 10px;
    }
    .interests_item .member-coupes {
        padding: 10px 0;
        border: 1px solid #e5e6e7;
        margin-bottom: 10px;
    }
    .interests_item .go-member-item {
        display: inline-block;
        width: 80px;
        padding: 5px 0;
        text-align: center;
        background: #0d8ddb;
        color: #fff;
    }
    .interests_item .go-member-item.del_mermber {
        background: #f00;
    }
    .coupe_pop, .cover_pop {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        /* 价格包 Bootstrap 弹窗已有遮罩，这里不再铺厚黑底，避免「黑影」叠两层 */
        background: rgba(0, 0, 0, .15);
        /* 默认隐藏，打开时再加 .is-open；避免 display:flex 与 hide() 打架留下黑影 */
        display: none;
        justify-content: center;
        align-items: center;
        /* 全局 .modal 为 2050 !important，必须更高才能盖住价格包弹窗 */
        z-index: 10000 !important;
    }
    .coupe_pop.is-open, .cover_pop.is-open {
        display: flex !important;
    }
    .pop_inner {
        width: 500px;
        height: 600px;
        padding: 10px;
        background: #fff;
    }
    .pop_inner .control-label{
        width: 100%;
    }
    .pop_inner .col-sm-10{
        width: 100%;
    }
    .pop_inner .form-group {
        float: left;
        width: 100%;
        padding-top: 20px;
    }
    .pop_inner .form-group .discount {
        padding-top: 10px;
    }
    .pop_btns {
        float: left;
        width: 100%;
        text-align: right;
    }
    .pop_btns .confirm_btn{
        display: inline-block;
        width: 80px;
        padding: 5px 0;
        text-align: center;
        background: #0d8ddb;
        color: #fff;
    }
    .member-coupes-item {
        max-height: 300px;
        overflow-y: auto;
    }
    .member-coupes-item ul{
        padding-left: 0;
        text-align: left;
        padding: 10px;
        border: 1px solid #e5e6e7;
        margin-bottom: 10px;
    }
    .member-coupes-item ul .member-coupes-inner{
        display: flex;
        justify-content: space-between;
    }
    .member-coupes-item ul .member-coupes-inner .member-coupes-detail{
        display: flex;
        align-items: center;
    }
    .member-coupes-item ul .member-coupes-inner .member-coupes-detail span{
        padding-right: 10px;
    }
    .member-coupes-item ul .member-coupes-inner .member-coupes-bth{

    }
    .member-coupes-bth span {
        display: inline-block;
        width: 40px;
        padding: 5px 0;
        text-align: center;
        background: #0d8ddb;
        color: #fff;
    }
    .member-coupes-bth .delCoupes{
        margin-left: 5px;
        background: #f00;
    }
    .radio-box {
        float: left;
    }
    .goods_track {
        display: none;
    }
    .user_rules {
        display: none;
    }
    /*误删   该样式是控制动态添加数据的*/
    .remote_search {
        padding-left: 0;
    }
    .interestsDesc_inner {
        height: 300px;
    }
    .coupe_pop .pop_inner {
        overflow-y: auto;
        height: auto;
        max-height: 90vh;
        position: relative;
        z-index: 10001;
    }
    .coupe_pop .form-control {
        pointer-events: auto;
    }
</style>
<body class="gray-bg" style="font: 14px Helvetica Neue, Helvetica, PingFang SC, 微软雅黑, Tahoma, Arial, sans-serif !important;">
<section class="section-content">
    <div class="row">
        <div class="col-sm-12 about">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="nav-tabs-custom">
                        <ul class="nav nav-tabs">
                            <li class="tabs_inner active" onclick="tabChange(0)"><a href="#memberinfo" data-toggle="tab" aria-expanded="true">基础信息</a></li>
                            <li class="tabs_inner" onclick="tabChange(1)"><a href="#membership" data-toggle="tab" aria-expanded="false">会员套餐</a></li>
<!--                            <li><a href="#membercode" data-toggle="tab" aria-expanded="false">会员码</a></li>-->
                        </ul>
                        <div class="tab-content">
                            <!--基础信息-->
                            <div class="tab-pane active" id="memberinfo" th:object="${member}">
                                <form class="form-horizontal" id="form-member-edit">
                                    <!--隐藏ID-->
                                    <input name="memberId" id="id" type="hidden" th:field="*{memberId}" readonly>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">会员标题：</label>
                                        <div class="col-sm-10">
                                            <input type="text" class="form-control" name="title" th:field="*{title}" placeholder="请输入标题">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">会员说明：</label>
                                        <div class="col-sm-10">
                                            <textarea class="form-control" name="subTitle" th:field="*{subTitle}" placeholder="简略描述会员功能"/>
                                            <!--                                        <input type="text" class="form-control" name="subTitle" th:field="*{subTitle}" placeholder="简略描述会员功能">-->
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">会员banner：</label>
                                        <div class="text-center">
                                            <p class="user-info-head avatar_img" onclick="icon(this, 1)">
                                                <img class="img-circle img-lg memberBanner" th:src="(${#strings.isEmpty(member.avatar)}) ? @{/img/profile.jpg} : @{${member.avatar}}" th:onerror="'this.src=\'' + @{'/img/profile.jpg'} + '\''">
                                            </p>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">会员小尾巴：</label>
                                        <div class="text-center">
                                            <p class="user-info-head avatar_img" onclick="icon(this ,2)" >
                                                <img class="img-circle img-lg memberLast" th:src="(${#strings.isEmpty(member.icon)}) ? @{/img/log.png} : @{${member.icon}}" th:onerror="'this.src=\'' + @{'/img/log.png'} + '\''">
                                            </p>
                                        </div>
                                    </div>
                                    <!--                                    <div class="form-group">-->
                                    <!--                                        <label class="col-sm-2 control-label">是否限购：</label>-->
                                    <!--                                        <div class="col-sm-10">-->
                                    <!--                                            <div class="radio-box">-->
                                    <!--                                                <input type="radio" id="radio1" th:field="*{limitation}" name="limitation" value="0">-->
                                    <!--                                                <label for="radio1">否</label>-->
                                    <!--                                            </div>-->
                                    <!--                                            <div class="radio-box">-->
                                    <!--                                                <input type="radio" id="radio2" th:field="*{limitation}" name="limitation" value="1">-->
                                    <!--                                                <label for="radio2">是</label>-->
                                    <!--                                            </div>-->
                                    <!--                                        </div>-->
                                    <!--                                    </div>-->
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">会员弹窗文案：</label>
                                        <div class="col-sm-10">
<!--                                            <textarea class="form-control text_menber" name="interestsDetail" size="10" th:field="*{interestsDetail}"/>-->
                                            <textarea class="form-control text_menber" name="noticeInfo" size="10" th:field="*{noticeInfo}"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">注意事项：</label>
                                        <div class="col-sm-10">
                                            <textarea class="form-control text_menber" name="notes" th:field="*{notes}"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">是否开售：</label>
                                        <div class="col-sm-10">
                                            <div class="radio-box">
                                                <input type="radio" id="radio1" th:checked="*{onsale==2}" name="onsale" value="2">
                                                <label for="radio1">否</label>
                                            </div>
                                            <div class="radio-box">
                                                <input type="radio" id="radio2" th:checked="*{onsale==1}" name="onsale" value="1">
                                                <label for="radio2">是</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">双倍积分：</label>
                                        <div class="col-sm-10">
                                            <div class="radio-box">
                                                <input type="radio" id="integral1" name="integralRate" value="1" th:attr="checked=${member.integralRate == null or member.integralRate.intValue() == 1}"/>
                                                <label for="integral1">否</label>
                                            </div>
                                            <div class="radio-box">
                                                <input type="radio" id="integral2" name="integralRate" value="2" th:attr="checked=${member.integralRate != null and member.integralRate.intValue() == 2}"/>
                                                <label for="integral2">是</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-sm-offset-2 col-sm-10">
                                            <button type="button" class="btn btn-sm btn-primary" onclick="submitMemberInfo()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                                            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <!--会员套餐-->
                            <div class="tab-pane" id="membership">
                                <div class="form-horizontal">
                                    <div class="form-group">
                                        <div class="col-sm-12" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                                            <label class="control-label" style="margin:0;">价格包列表</label>
                                            <button type="button" class="btn btn-sm btn-success" onclick="openPriceModal('add')"><i class="fa fa-plus"></i> 新增价格包</button>
                                        </div>
                                        <div class="col-sm-12">
                                            <table class="table table-bordered table-striped">
                                                <thead>
                                                <tr>
                                                    <th>价格包ID</th>
                                                    <th>名称</th>
                                                    <th>原价</th>
                                                    <th>购买价</th>
                                                    <th>首购特价</th>
                                                    <th>天数</th>
                                                    <th>状态</th>
                                                    <th>操作</th>
                                                </tr>
                                                </thead>
                                                <tbody>
                                                <tr th:each="mp : ${memberPriceList}">
                                                    <td th:text="${mp.memberPriceId}"></td>
                                                    <td th:text="${mp.name}"></td>
                                                    <td th:text="${mp.price}"></td>
                                                    <td th:text="${mp.priceFixed}"></td>
                                                    <td th:text="${mp.priceSpecial}"></td>
                                                    <td th:text="${mp.days}"></td>
                                                    <td>
                                                        <span class="badge badge-primary" th:if="${mp.state == 1}">上线中</span>
                                                        <span class="badge" th:if="${mp.state == 2}">已下线</span>
                                                    </td>
                                                    <td>
                                                        <a class="btn btn-xs btn-info" href="javascript:void(0)"
                                                           th:onclick="openPriceModal('edit', findPriceById([[${mp.memberPriceId}]]))">编辑</a>
                                                        <a class="btn btn-xs btn-danger" href="javascript:void(0)" th:if="${mp.state == 1}"
                                                           th:onclick="offlinePrice([[${mp.memberPriceId}]])">下线</a>
                                                        <a class="btn btn-xs btn-warning" href="javascript:void(0)" th:if="${mp.state == 2}"
                                                           th:onclick="onlinePrice([[${mp.memberPriceId}]])">重新上线</a>
                                                    </td>
                                                </tr>
                                                <tr th:if="${memberPriceList == null or #lists.isEmpty(memberPriceList)}">
                                                    <td colspan="8" class="text-center">暂无价格包，请点击右上角新增</td>
                                                </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>

                                <!-- 预渲染权益卡片仓库（按价格包过滤克隆进弹窗） -->
                                <div id="rights-store" style="display:none;">
                                    <div th:each="mr:${memberRightsList}" class="rights-store-item interests_inner"
                                         th:attr="data-price-id=${mr.memberPriceId}, data-mrights-id=${mr.mrightsId}">
                                        <div class="form-group interests_item" th:attr="data-mrights-id=${mr.mrightsId}">
                                            <input type="hidden" class="js-mrights-id" th:value="${mr.mrightsId}"/>
                                            <div class="text-center">
                                                <p class="user-info-head avatar_img vip_icon" onclick="icon(this)">
                                                    <img class="img-circle img-lg interestsIcon" id="interestsIcon" th:src="${mr.cover}"/>
                                                </p>
                                                <input type="text" class="form-control" id="interestsTitle" name="interestsTitle" placeholder="请输入标题" th:value="${mr.title}"/>
                                                <input type="text" class="form-control" id="interestsSubTitle" name="interestsSubTitle" placeholder="请输入副标题" th:value="${mr.subTitle}"/>
                                                <textarea class="form-control" id="interestsDesc" name="interestsDesc" placeholder="详情内容" th:text="${mr.detail}"></textarea>
                                                <div class="member-coupes-item">
                                                    <ul th:each="mrc:${couponMemberDtoListMap.get(mr.mrightsId)}">
                                                        <div class="member-coupes-inner">
                                                            <div class="member-coupes-detail">
                                                                <input type="hidden" id="mrcmcouponId" th:value="${mrc.mcouponId}"/>
                                                                <input type="hidden" id="mrccouponId" th:value="${mrc.couponId}"/>
                                                                <input type="hidden" id="mrcbusiType" th:value="${mrc.busiType}"/>
                                                                <input type="hidden" id="mrccouType" th:value="${mrc.couType}"/>
                                                                <input type="hidden" id="mrctitle" th:value="${mrc.title}"/>
                                                                <input type="hidden" id="mrceventAmt" th:value="${mrc.eventAmt}"/>
                                                                <input type="hidden" id="mrcdays" class="mrcdays" value=""/>
                                                                <input type="hidden" id="mrvalFace" th:value="${mrc.valFace}"/>
                                                                <input type="hidden" id="mrcoverlay" th:value="${mrc.overlay}"/>
                                                                <input type="hidden" id="mrcvalMinus" th:value="${mrc.valMinus}"/>
                                                                <input type="hidden" id="mrcvalOver" th:value="${mrc.valOver}"/>
                                                                <span class="member-coupes-mcouponId" th:text="${mrc.mcouponId}" hidden></span>
                                                                <span class="member-coupes-busiType" th:if="${mrc.busiType == 0}">全场</span>
                                                                <span class="member-coupes-busiType" th:if="${mrc.busiType == 1}">演出</span>
                                                                <span class="member-coupes-busiType" th:if="${mrc.busiType == 2}">商品</span>
                                                                <span class="member-coupes-busiType" th:if="${mrc.busiType == 3}">优先购</span>
                                                                <span class="member-coupes-type" th:if="${mrc.couType == 1}">代金券</span>
                                                                <span class="member-coupes-type" th:if="${mrc.couType == 2}">满减券</span>
                                                                <span class="member-coupes-type" th:if="${mrc.couType == 101}">优先券</span>
                                                                <span class="member-coupes-title" th:text="${mrc.title}"></span>
                                                                <span class="member-coupes-mark">通用</span>
                                                                <span class="member-coupes-num" th:text="${mrc.eventAmt} + '张'"></span>
                                                                <span class="member-coupes-time package-days-text">天</span>
                                                            </div>
                                                            <div class="member-coupes-bth">
                                                                <span th:onclick="editCoupes(this, [[${mrc}]]);">编辑</span>
                                                                <span class="delCoupes" onclick="delCoupes(this)">删除</span>
                                                            </div>
                                                        </div>
                                                    </ul>
                                                </div>
                                                <div class="member-coupes" onclick="addCoupes(this)">+添加券<br/>*全场券不需要重复添，需要先保存再添加券</div>
                                                <div class="go-member-item" onclick="addColumn(this)">继续添加</div>
                                                <div class="go-member-item save_mermber" onclick="saveColumn(this, 1)">保存</div>
                                                <div class="go-member-item del_mermber" onclick="saveColumn(this, 2)">删除</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="rights-empty-template" style="display:none;">
                                    <div class="interests_inner">
                                        <div class="form-group interests_item" data-mrights-id="">
                                            <input type="hidden" class="js-mrights-id" value=""/>
                                            <div class="text-center">
                                                <p class="user-info-head avatar_img vip_icon" onclick="icon(this)">
                                                    <img class="img-circle img-lg interestsIcon" id="interestsIcon"/>
                                                </p>
                                                <input type="text" class="form-control" id="interestsTitle" name="interestsTitle" placeholder="请输入标题"/>
                                                <input type="text" class="form-control" id="interestsSubTitle" name="interestsSubTitle" placeholder="请输入副标题"/>
                                                <textarea class="form-control interestsDesc_inner" id="interestsDesc" name="interestsDesc" placeholder="详情内容"></textarea>
                                                <div class="member-coupes-item"></div>
                                                <div class="member-coupes" onclick="addCoupes(this)">+添加券<br/>*全场券不需要重复添，需要先保存再添加券</div>
                                                <div class="go-member-item" onclick="addColumn(this)">继续添加</div>
                                                <div class="go-member-item save_mermber" onclick="saveColumn(this, 1)">保存</div>
                                                <div class="go-member-item del_mermber" onclick="saveColumn(this, 2)">删除</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!--会员码-->
<!--                            <div class="tab-pane" id="membercode">-->
<!--                                <form class="form-horizontal" id="form-user-resetPwd">-->

<!--                                </form>-->
<!--                            </div>-->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 价格包编辑弹窗 -->
    <div class="modal fade" id="pricePackageModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" style="width:720px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    <h4 class="modal-title" id="pricePackageModalTitle">编辑价格包</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="form-membership-edit">
                        <input type="hidden" name="memberPriceId" id="editMemberPriceId" value=""/>
                        <h5 style="margin-top:0;">价格信息</h5>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">名称</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="name" id="editPriceName" placeholder="如：年卡/月卡/体验3天"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">原价(元)</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="price" id="editPrice" placeholder="请输入原价"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">购买价格(元)</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="priceFixed" id="editPriceFixed" placeholder="请输入购买价格"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">首购特价(元)</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="priceSpecial" id="editPriceSpecial" placeholder="请输入优惠价格"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">有效时间(天)</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="days" id="editDays" placeholder="请输入有效时间"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-3 col-sm-8">
                                <button type="button" class="btn btn-sm btn-primary" onclick="submitMemberShip()">保存价格包</button>
                            </div>
                        </div>
                    </form>
                    <hr/>
                    <h5>本档权益 <small id="modalRightsHint" style="color:#999;"></small></h5>
                    <div id="modalRightsLockTip" class="text-muted" style="display:none;margin-bottom:10px;">请先保存价格包，再配置本档权益</div>
                    <form class="form-horizontal" id="form-membercoupe-edit">
                        <div class="interests_column" id="modalRightsArea"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <div class="cover_pop" style="display: none">
        <div class="pop_inner">
            <input type="hidden" class="coverFunNum"/>
            <input type="hidden" class="coverIndex"/>
            <input type="hidden" class="coverCon"/>
            <input type="hidden" class="mermberCon"/>
            <input type="hidden" class="bannerCon"/>
            <div class="wrapper wrapper-content animated fadeInRight ibox-content">
                <div class="file-loading">
                    <input id="fileinput-demo-1" type="file" name="file" data-browse-on-zone-click="true"
                           data-msg-placeholder="Select {files} for upload...">
                    <input hidden id="coverImg" name="coverImg">
                </div>
            </div>
            <div class="pop_btns">
                <div class="confirm_btn" onclick="popBtn(2)">确认</div>
                <div class="confirm_btn confirm_cancel" onclick="popBtn(0)">取消</div>
            </div>
        </div>
    </div>

    <div class="coupe_pop" style="display: none">
        <div class="pop_inner">
            <input type="hidden" class="parentsIndex"/>
            <input type="hidden" class="childIndex"/>
            <input type="hidden" class="pop_oper"/>
<!--            <div class="col-sm-10">-->
<!--                <input type="text" id="coupeAdd_title" name="coupeAdd_title" placeholder="券标题"/>-->
<!--            </div>-->
            <div class="form-group">
                <label class="col-sm-2 control-label">类别：</label>
                <div class="col-sm-10 coupenColumn">
                    <div class="radio-box">
                        <label for="radio2" onclick="radioType(this)">
                            <input type="radio" id="coupeAdd1" class="coupeAddVal" name="coupeAdd_type" value="0"/>全场
                        </label>
                    </div>
                    <div class="radio-box">
                        <label for="radio2" onclick="radioType(this)">
                            <input type="radio" id="coupeAdd2" class="coupeAddVal" name="coupeAdd_type" value="1"/>演出
                        </label>
                    </div>
                    <div class="radio-box">
                        <label for="radio2" onclick="radioType(this)">
                            <input type="radio" id="coupeAdd3" class="coupeAddVal" name="coupeAdd_type" value="2"/>商品
                        </label>
                    </div>
                    <div class="radio-box">
                        <label for="radio2" onclick="radioType(this)">
                            <input type="radio" id="coupeAdd4" class="coupeAddVal" name="coupeAdd_type" value="3"/>优先购买
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-group alltrack alltrack_type_row">
                <label class="col-sm-2 control-label">类型：</label>
                <div class="col-sm-10 alltrack_radio">
                    <div class="radio-box">
                        <label for="radio1" onclick="coupetType(this)">
                            <input type="radio" id="coupetypr2" class="coupeAddVal" name="coupe_type" value="2"/>满减券
                        </label>
                    </div>
                    <div class="radio-box">
                        <label for="radio2" onclick="coupetType(this)">
                            <input type="radio" id="coupetypr1" class="coupeAddVal" name="coupe_type" value="1"/>代金券
                        </label>
                    </div>
                    <!-- 会员套餐页暂不支持折扣券：后端 edit_coupon 商品类别仅允许 couType 1/2/3，选 4 会报「暂不支持所选券类型」；保留注释便于后续启用
                    <div class="radio-box goods_track">
                        <label for="radio2" onclick="coupetType(this)">
                            <input type="radio" id="coupetypr4" class="coupeAddVal" name="coupe_type" value="4"/>折扣券
                        </label>
                    </div>
                    -->
                </div>
            </div>
            <div class="form-group coupe-select-row">
                <label class="col-sm-2 control-label">选择券：</label>
                <div class="col-sm-10 discount">
                    <div class="coupetypr_search">
                        <div class="remote_wrapper" style="position: relative;">
                            <input name="ids" type="hidden">
                            <input type="text" id="remoteSearch" class="form-control" placeholder="请输入关键字选择券" autocomplete="off">
                        </div>
                    </div>
                </div>
                <div class="form-group user_rules" style="width:100%;">
                    <label class="col-sm-2 control-label">适用范围：</label>
                    <div class="col-sm-10 rules_inner"></div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">数量：</label>
                <div class="col-sm-10">
                    <input type="text" id="eventAmt" class="form-control" value="1" style="display:inline-block;width:120px;" autocomplete="off"/> 张
                </div>
            </div>
<!--            <div class="form-group alltrack_limit">-->
<!--                <label class="col-sm-2 control-label">使用限制：</label>-->
<!--                <div class="col-sm-10">-->
<!--                    <div class="radio-box">-->
<!--                        <label for="radio1" onclick="limitType(this)">-->
<!--                            <input type="radio" id="limittypr1" name="limit_type" value="0"/> 叠加-->
<!--                        </label>-->
<!--                    </div>-->
<!--                    <div class="radio-box">-->
<!--                        <label for="radio2" onclick="limitType(this)">-->
<!--                            <input type="radio" id="limittypr2" name="limit_type" value="1"/> 限制-->
<!--                        </label>-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->
            <div class="pop_btns">
                <div class="confirm_btn" onclick="popBtn(1)">确认</div>
                <div class="confirm_btn confirm_cancel" onclick="popBtn(0)">取消</div>
            </div>
        </div>
    </div>
</section>

<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-fileinput-js"/>
<script th:src="@{/js/remote-search-coupon.js}"></script>


<script th:inline="javascript">
    var member = [[${member}]];
    var platformUrl = [[${platformUrl}]];
    var memberRightsList = [[${memberRightsList}]];
    var couponMemberDtoListMap = [[${couponMemberDtoListMap}]];
    var memberPrice = [[${memberPrice}]];
    var memberPriceList = [[${memberPriceList}]];

    var typeRadio = '';

    var prefix = ctx + "adam/member";
    var candyfix = ctx + "candy/coupon";
    window.candyCouponApi = candyfix;

    console.log(memberRightsList);
    // 弹窗
    $(function () {
        $("#fileinput-demo-1").fileinput({
            'theme': 'explorer-fas',
            // 'uploadUrl': "/kylin/banners/upload3",
            // 'uploadUrl': "http://127.0.0.1:9003" + "/platform/basicServices/alOss/upload",
            // 'uploadUrl': "https://devplatform.zhengzai.tv/platform/basicServices/alOss/upload",
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload",
            "uploadExtraData": {
                "pathName" : "banner",
                "buckType" : 1
            },
            // overwriteInitial: false,
            // initialPreviewAsData: true,
            autoReplace: true,
            dropZoneTitle: "请上传文件",
            maxFileCount: 1
        });
        $("#fileinput-demo-1").on("fileuploaded", function (event, data, previewId, index) {
            $('.coverCon').val('https://img.zhengzai.tv/' + data.response.data.ossPath);
        });

        var tabActive = window.localStorage.getItem('tabActive');
        if (tabActive == '1' || tabActive == 1) {
            // 刷新后强制回到套餐 Tab（兼容 bootstrap tab 偶发不激活）
            $('.nav-tabs li').removeClass('active');
            $('.tab-content > .tab-pane').removeClass('active in');
            $('.nav-tabs a[href="#membership"]').parent().addClass('active');
            $('#membership').addClass('active in');
            $('.nav-tabs a[href="#membership"]').tab('show');
        }

        $('.coupenColumn .iCheck-helper').click(function () {
            radioType($(this).parent().parent());
        });

        $('.alltrack .iCheck-helper').click(function () {
            coupetType($(this).parent().parent());
        });
    });

    // 远程搜索券
    $('#remoteSearch').remoteSearchPerformance({
        ajax:{
            url: candyfix + "/list",
            type: "post"
        },
        chose: function(text,val){
            window.couponId = val;
            $('.user_rules').show();
            coupenDetail(val, 1);
            // document.getElementsByName("ids")[0].value = val;
        }
    });

    function tabChange (num) {
        window.localStorage.setItem('tabActive', num);
    }

    // 弹窗确认取消按钮
    function popBtn (num) {
        if (num == 0) {
            clearUiShade();
        } else if (num == 2) {
            if ($('.coverFunNum').val() == 1) {
                var bannerCon = $('.coverCon').val();
                $('.memberBanner').attr('src', bannerCon);
            } else if ($('.coverFunNum').val() == 2) {
                var mermberCon =  $('.coverCon').val();
                $('.memberLast').attr('src', mermberCon);
            } else {
                var coverIndex = $('.coverIndex').val();
                var coverCon = $('.coverCon').val();
                var $icons = $('#modalRightsArea .vip_icon').find('img');
                if (!$icons.length) {
                    $icons = $('.vip_icon').find('img');
                }
                $icons.eq(coverIndex).attr('src', coverCon);
            }
            hideCoverPop();
        } else {
            var coupeTitle = $('#coupeAdd_title').val() || $('#remoteSearch').val() || '';
            // 以勾选/已选券元数据为准，避免残留「优先购+101」污染其它券回显
            var typeMeta = resolveCoupeTypeMeta();
            var busiType = typeMeta.busiType;
            var couType = typeMeta.couType;
            if (busiType === '' || busiType == null || isNaN(Number(busiType))) {
                $.modal.msgWarning('请先选择券类别');
                return;
            }
            if (Number(busiType) !== 3 && (couType === '' || couType == null || isNaN(Number(couType)))) {
                $.modal.msgWarning('请先选择券类型');
                return;
            }
            busiType = Number(busiType);
            couType = Number(busiType) === 3 ? 101 : Number(couType);

            if (busiType == 0) {
                var couponRuleList = [{
                    useScope: 100,
                    busiName: '全场'
                }]
            } else if (busiType == 1) {
                var couponRuleList = [{
                    useScope: 90,
                    busiName: '演出'
                }]
            } else if (busiType == 2) {
                var couponRuleList = [{
                    useScope: 80,
                    busiName: '商品'
                }]
            } else {
                var couponRuleList =  [{
                    useScope: 90,
                    busiName: '优先购'
                }]
            }

            if (busiType == 3) {
                var eventAmt = $('#eventAmt').val();
                var overlay = this.overlay;
            } else {
                var valOver = $('#valOver').val();
                var valMinus = $('#valMinus').val();
                if (couType == 1) {
                    var valFace = $('#valFace').val();
                }
            }
            var itemIndex = $('.parentsIndex').val();
            var mrightsId = this.mrightsId;
            var couponId = this.couponId || window.couponId;

            var MembercoupenData = {
                busiType: busiType,
                couType: couType,
                couponId: couponId? couponId : '',
                couponRuleList: couponRuleList,
                eventAmt: $('#eventAmt').val(),
                label: "标注",
                memberId: member.memberId,
                mrightsId: mrightsId ? mrightsId : 'string',
                // overlay: overlay ? overlay : 0,
                overlay: 1,
                title: coupeTitle,
                valFace: valFace ? valFace : 1,
                valOver: valOver ? valOver : 1,
                valMinus: valMinus ? valMinus : 1,
                oper: $('.pop_oper').val()
            };
            if ($('.pop_oper').val() == 3) {
                MembercoupenData.operCouponId = this.operCouponId;
            }
            packageSave(prefix + "/edit_coupon", JSON.stringify(MembercoupenData), function (result) {
                // 无论成败先关弹层，避免半透明黑影残留
                hideCoupePop();
                hideCoverPop();
                if (!result || result.code != web_status.SUCCESS) {
                    return;
                }
                // 与价格包一致：不立刻整页刷新，关弹窗时再回套餐 Tab
                pricePackageNeedReload = true;
                refreshCouponRowAfterSave(MembercoupenData);
            }, true);
        }
    }

    function limitType (obj) {
        this.overlay = $(obj).find('input').val();
    }

    // 类别切换：优先购买无券类型选项，整行（含「类型：」）隐藏；搜索须带 couType=101
    function syncCoupeTypeRow(typeRadio) {
        window.typeRadio = typeRadio;
        $('.coupe-select-row').show();
        if (String(typeRadio) === '3') {
            // 优先券固定 101；隐藏类型行后必须覆盖，否则会沿用满减/代金导致搜不到
            window.typeCoupe = 101;
            this.typeCoupe = 101;
            $('.alltrack_type_row').hide();
            $('.alltrack_limit').show();
            // $('.goods_track').hide(); // 折扣券已注释隐藏
        } else {
            // 离开优先购时清掉 101，避免非优先类别被错误过滤
            if (String(window.typeCoupe) === '101') {
                window.typeCoupe = '';
                this.typeCoupe = '';
            }
            $('.alltrack_type_row').show();
            $('.alltrack_radio').show();
            $('.alltrack_limit').hide();
            // 商品类别下原展示折扣券(goods_track)，后端不支持 couType=4，已注释选项，此处不再切换显示
            // if (String(typeRadio) === '2') {
            //     $('.goods_track').show();
            // } else {
            //     $('.goods_track').hide();
            // }
            $('.goods_track').hide();
        }
    }

    function showCoupePop() {
        // Bootstrap 弹窗 enforceFocus 会抢走外层输入框焦点，导致选券/数量无法输入
        $(document).off('focusin.bs.modal');
        $('.coupe_pop').appendTo('body').css('display', '').addClass('is-open');
        setTimeout(function () {
            $('#remoteSearch').trigger('focus');
        }, 50);
    }

    function hideCoupePop() {
        $('.coupe_pop').removeClass('is-open').css('display', 'none');
        $('#remoteSearch_ul').remove();
    }

    function showCoverPop() {
        $(document).off('focusin.bs.modal');
        $('.cover_pop').appendTo('body').css('display', '').addClass('is-open');
    }

    function hideCoverPop() {
        $('.cover_pop').removeClass('is-open').css('display', 'none');
    }

    // 清掉 loading / layer / 自定义弹层残留黑影（价格包弹窗内最容易叠遮罩）
    function clearUiShade() {
        hideCoupePop();
        hideCoverPop();
        try { $.unblockUI(); } catch (e) {}
        try { $.modal.closeLoading(); } catch (e) {}
        $('body > .blockUI').remove();
        $('.blockUI').remove();
        // 无对话框时清掉孤儿 shade；有对话框时留给 layer 自己管
        if (!$('.layui-layer-dialog:visible, .layui-layer-page:visible, .layui-layer-iframe:visible').length) {
            $('.layui-layer-shade').remove();
        }
    }

    /**
     * 价格包弹窗内保存：用 msg 轻提示，避免 alertSuccess 黑遮罩叠在 Bootstrap modal 上关不掉
     * @param asJson true=JSON body（券），false=表单（权益/价格）
     */
    function packageSave(url, data, callback, asJson) {
        var config = {
            url: url,
            type: 'post',
            dataType: 'json',
            data: data,
            beforeSend: function () {
                $.modal.loading('正在处理中，请稍后...');
            },
            success: function (result) {
                clearUiShade();
                if (typeof callback === 'function') {
                    callback(result);
                }
                if (!result) {
                    $.modal.msgError('请求失败');
                    return;
                }
                if (result.code == web_status.SUCCESS) {
                    $.modal.msgSuccess(result.msg || '操作成功');
                } else if (result.code == web_status.WARNING) {
                    $.modal.msgWarning(result.msg);
                } else {
                    $.modal.msgError(result.msg || '操作失败');
                }
            },
            error: function () {
                clearUiShade();
                $.modal.msgError('请求失败');
            },
            complete: function () {
                clearUiShade();
            }
        };
        if (asJson) {
            config.contentType = 'application/json';
        }
        $.ajax(config);
    }

    // 类别
    function radioType (obj) {
        var typeRadio = $(obj).find('input').val();
        $(obj).parent().parent().find('input').removeAttr('checked');
        $(obj).find('input').attr('checked', true);

        this.typeRadio = typeRadio;
        window.typeRadio = typeRadio;
        $('#remoteSearch').val('');
        $('.user_rules').hide();
        syncCoupeTypeRow(typeRadio);
    }

    // 类型
    function coupetType (obj) {
        var typeCoupe = $(obj).find('input').val();
        this.typeCoupe = typeCoupe;
        window.typeCoupe = typeCoupe;
        $('#remoteSearch').val('');
        $('.user_rules').hide();
        if (typeCoupe == 1) {
            $('.coupetypr_price').show();
            $('.coupetypr_discount').hide();
        } else {
            $('.coupetypr_price').hide();
            $('.coupetypr_discount').show();
        }
    }

    // 券详情：以券真实类别/类型同步表单，避免仍显示优先购/优先券
    function coupenDetail (val, num) {
        $.ajax({
            url: candyfix + "/info",
            async: false,
            data: {
                couponId: val
            },
            dataType: 'json',
            type: 'get',
            success: function (res) {
                var coupenData = res.data || {};
                window.lastSelectedCoupon = coupenData;
                if (coupenData.busiType != null) {
                    applyCouponTypeToForm(coupenData.busiType, coupenData.couType);
                }
                if (coupenData.busiType == 0) {
                    $('.user_rules .rules_inner').text('全部演出、商品');
                } else if (coupenData.busiType == 1 || coupenData.busiType == 2) {
                    var coupenDataArr = [];
                    if (coupenData.useRules && coupenData.useRules.length > 0) {
                        for (var i = 0; i < coupenData.useRules.length; i++ ) {
                            coupenDataArr.push(coupenData.useRules[i].busiName);
                        }
                        $('.user_rules .rules_inner').text(coupenDataArr.join("/"));
                    }
                } else if (coupenData.busiType == 3) {
                    $('.user_rules .rules_inner').text('全部演出');
                }
                if (num == 1 || num == 3) {
                    if (coupenData.title) {
                        $('#remoteSearch').val(coupenData.title);
                    }
                    $('.user_rules').show();
                }
            }
        })
    }

    function applyCouponTypeToForm(busiType, couType) {
        window.typeRadio = busiType;
        window.typeCoupe = Number(busiType) === 3 ? 101 : couType;
        this.typeRadio = window.typeRadio;
        this.typeCoupe = window.typeCoupe;

        var $busiInputs = $('.coupenColumn .coupeAddVal');
        var $couInputs = $('.alltrack_radio .coupeAddVal');
        $busiInputs.prop('checked', false).parent().removeClass('checked');
        $couInputs.prop('checked', false).parent().removeClass('checked');
        if ($.fn.iCheck) {
            $busiInputs.iCheck('uncheck');
            $couInputs.iCheck('uncheck');
        }

        var $busi = $('#coupeAdd' + (Number(busiType) + 1));
        if ($busi.length) {
            $busi.prop('checked', true).parent().addClass('checked');
            if ($.fn.iCheck) {
                $busi.iCheck('check');
            }
        }

        if (Number(busiType) !== 3 && couType != null && Number(couType) !== 101) {
            var $cou = $('#coupetypr' + couType);
            if ($cou.length) {
                $cou.prop('checked', true).parent().addClass('checked');
                if ($.fn.iCheck) {
                    $cou.iCheck('check');
                }
            }
        }
        syncCoupeTypeRow(busiType);
    }

    function resolveCoupeTypeMeta() {
        var busiType = $('input[name="coupeAdd_type"]:checked').val();
        var couType = $('input[name="coupe_type"]:checked').val();
        var selected = window.lastSelectedCoupon || {};
        if ((busiType === undefined || busiType === null || busiType === '') && selected.busiType != null) {
            busiType = selected.busiType;
        }
        if ((couType === undefined || couType === null || couType === '') && selected.couType != null) {
            couType = selected.couType;
        }
        if (busiType === undefined || busiType === null || busiType === '') {
            busiType = window.typeRadio;
        }
        if (couType === undefined || couType === null || couType === '') {
            couType = window.typeCoupe;
        }
        return { busiType: busiType, couType: couType };
    }

    // 权益图片上传
    function icon (obj, num) {
        $('.coverFunNum').val(num);
        if (num) {
            $('.coverIndex').val(0);
        } else {
            var addIconIndex = $('#modalRightsArea .vip_icon').index($(obj));
            if (addIconIndex < 0) {
                addIconIndex = $('.vip_icon').index($(obj));
            }
            $('.coverIndex').val(addIconIndex);
        }
        showCoverPop();
    }
    function delCoupes (obj) {
        var thisVal = $(obj).parents('ul');
        var busiType = Number(thisVal.find('#mrcbusiType').val());
        var couType = Number(thisVal.find('#mrccouType').val());
        var couponId = thisVal.find('#mrccouponId').val();
        var mrightsId = thisVal.find('#mrcmcouponId').val();
        var eventAmt = thisVal.find('#mrceventAmt').val();
        var memberId = member.memberId;
        // var overlay = thisVal.find('#mrcoverlay').val();
        var titleDel = thisVal.find('#mrctitle').val();
        var valFace = thisVal.find('#mrvalFace').val();
        var valOver = thisVal.find('#mrcvalOver').val();
        var valMinus = thisVal.find('#mrcvalMinus').val();
        // var mrightsId =

        if (busiType == 0) {
            var couponRuleList = [{
                useScope: 100,
                busiName: '全场'
            }]
        } else if ( busiType == 1) {
            var couponRuleList = [{
                useScope: 90,
                busiName: '演出'
            }]
        } else if ( busiType == 2 ) {
            var couponRuleList = [{
                useScope: 80,
                busiName: '商品'
            }]
        } else {
            var couponRuleList =  [{
                useScope: 90,
                busiName: '优先购'
            }]
        }

        var MembercoupenData = {
            busiType: busiType,
            couType:  couType == 3 ? 101 : (busiType == 3 ? 101 : couType),
            couponId: couponId,
            couponRuleList: couponRuleList,
            eventAmt: eventAmt,
            label: "标注",
            memberId: memberId,
            mrightsId: mrightsId,
            // overlay: overlay ? overlay : 0,
            overlay: 1,
            title: titleDel,
            valFace: valFace ? valFace : 1,
            valOver: valOver ? valOver : 1,
            valMinus: valMinus ? valMinus : 1,
            oper: 2
        };
        packageSave(prefix + "/edit_coupon", JSON.stringify(MembercoupenData), function (result) {
            hideCoupePop();
            if (!result || result.code != web_status.SUCCESS) {
                return;
            }
            pricePackageNeedReload = true;
            thisVal.remove();
        }, true);
    }

    function busiTypeLabel(busiType) {
        if (busiType == 0) return '全场';
        if (busiType == 1) return '演出';
        if (busiType == 2) return '商品';
        if (busiType == 3) return '优先购';
        return '';
    }

    function couTypeLabel(couType) {
        if (couType == 1) return '代金券';
        if (couType == 2) return '满减券';
        if (couType == 4) return '折扣券';
        if (couType == 101) return '优先券';
        return '';
    }

    // 加券/改券成功后就地刷新列表：优先用券详情真实类别/类型回显
    function refreshCouponRowAfterSave(data) {
        var mrightsId = data.mrightsId;
        if (!mrightsId) {
            return;
        }
        var $item = $('#modalRightsArea .interests_item').filter(function () {
            return String(readRightsId($(this)) || '') === String(mrightsId);
        }).first();
        if (!$item.length) {
            return;
        }

        function paint(row) {
            var days = $('#editDays').val() || '';
            var daysText = days ? (days + '天') : '天';
            var $list = $item.find('.member-coupes-item');
            var oper = Number(row.oper);
            if (oper == 3) {
                var targetId = row.operCouponId || row.couponId;
                var $ul = $list.find('ul').filter(function () {
                    return String($(this).find('#mrccouponId').val() || '') === String(targetId)
                        || String($(this).find('#mrcmcouponId').val() || '') === String(targetId);
                }).first();
                if ($ul.length) {
                    $ul.find('#mrctitle').val(row.title);
                    $ul.find('#mrceventAmt').val(row.eventAmt);
                    $ul.find('#mrcbusiType').val(row.busiType);
                    $ul.find('#mrccouType').val(row.couType);
                    $ul.find('.member-coupes-busiType').text(busiTypeLabel(row.busiType));
                    $ul.find('.member-coupes-type').text(couTypeLabel(row.couType));
                    $ul.find('.member-coupes-title').text(row.title || '');
                    $ul.find('.member-coupes-num').text((row.eventAmt || '') + '张');
                    $ul.find('.member-coupes-time').text(daysText);
                    $ul.find('#mrccouponId').val(row.couponId);
                }
                return;
            }
            var editData = {
                busiType: row.busiType,
                couType: row.couType,
                title: row.title,
                couponId: row.couponId,
                eventAmt: row.eventAmt,
                valFace: row.valFace,
                valOver: row.valOver,
                valMinus: row.valMinus,
                overlay: row.overlay,
                mcouponId: mrightsId
            };
            var $ul = $(''
                + '<ul><div class="member-coupes-inner"><div class="member-coupes-detail">'
                + '<input type="hidden" id="mrcmcouponId" value="' + mrightsId + '"/>'
                + '<input type="hidden" id="mrccouponId" value="' + (row.couponId || '') + '"/>'
                + '<input type="hidden" id="mrcbusiType" value="' + row.busiType + '"/>'
                + '<input type="hidden" id="mrccouType" value="' + row.couType + '"/>'
                + '<input type="hidden" id="mrctitle" value=""/>'
                + '<input type="hidden" id="mrceventAmt" value="' + (row.eventAmt || '') + '"/>'
                + '<input type="hidden" id="mrcdays" class="mrcdays" value="' + days + '"/>'
                + '<input type="hidden" id="mrvalFace" value="' + (row.valFace || '') + '"/>'
                + '<input type="hidden" id="mrcoverlay" value="' + (row.overlay || 1) + '"/>'
                + '<input type="hidden" id="mrcvalMinus" value="' + (row.valMinus || '') + '"/>'
                + '<input type="hidden" id="mrcvalOver" value="' + (row.valOver || '') + '"/>'
                + '<span class="member-coupes-mcouponId" hidden>' + mrightsId + '</span>'
                + '<span class="member-coupes-busiType"></span> '
                + '<span class="member-coupes-type"></span> '
                + '<span class="member-coupes-title"></span> '
                + '<span class="member-coupes-mark">通用</span> '
                + '<span class="member-coupes-num"></span> '
                + '<span class="member-coupes-time package-days-text"></span>'
                + '</div><div class="member-coupes-bth">'
                + '<span class="js-edit-coupes">编辑</span>'
                + '<span class="delCoupes" onclick="delCoupes(this)">删除</span>'
                + '</div></div></ul>');
            $ul.find('#mrctitle').val(row.title || '');
            $ul.find('.member-coupes-busiType').text(busiTypeLabel(row.busiType));
            $ul.find('.member-coupes-type').text(couTypeLabel(row.couType));
            $ul.find('.member-coupes-title').text(row.title || '');
            $ul.find('.member-coupes-num').text((row.eventAmt || '') + '张');
            $ul.find('.member-coupes-time').text(daysText);
            $ul.find('.js-edit-coupes').on('click', function () {
                editCoupes(this, editData);
            });
            $list.append($ul);
        }

        var row = $.extend({}, data);
        var selected = window.lastSelectedCoupon || {};
        if (selected.couponId && String(selected.couponId) === String(data.couponId)) {
            if (selected.busiType != null) row.busiType = selected.busiType;
            if (selected.couType != null) row.couType = selected.couType;
            if (selected.title) row.title = selected.title;
            paint(row);
            return;
        }
        if (!data.couponId) {
            paint(row);
            return;
        }
        $.ajax({
            url: candyfix + "/info",
            data: { couponId: data.couponId },
            dataType: 'json',
            type: 'get',
            success: function (res) {
                var c = (res && res.data) || {};
                if (c.busiType != null) row.busiType = c.busiType;
                if (c.couType != null) row.couType = c.couType;
                if (c.title) row.title = c.title;
                paint(row);
            },
            error: function () {
                paint(row);
            }
        });
    }

    // 添加券（须先保存权益拿到 mrightsId）
    function addCoupes (obj) {
        var item = $(obj).closest('.interests_item');
        var mrightsId = readRightsId(item);
        if (!mrightsId) {
            $.modal.msgWarning('请先保存本条权益，再添加券');
            return;
        }
        this.mrightsId = mrightsId;
        this.couponId = '';
        window.couponId = '';
        window.lastSelectedCoupon = null;
        $('#eventAmt').val('1');
        $('#remoteSearch').val('').attr('data-name', '').attr('data-id', '');
        $('.user_rules').hide();
        // 每次新增加券重置类别，避免沿用上次「优先购」
        $('.coupeAddVal').prop('checked', false).parent().removeClass('checked');
        $('#coupeAdd1').prop('checked', true).parent().addClass('checked');
        window.typeRadio = 0;
        window.typeCoupe = '';
        this.typeRadio = 0;
        this.typeCoupe = '';
        syncCoupeTypeRow(0);
        $('.pop_oper').val(1);
        showCoupePop();
    }

    // 编辑券
    function editCoupes (obj, dataObj) {
        var coupenObj = dataObj || {};
        var parentObj = $(obj).closest('ul');
        var couponId = parentObj.find('#mrccouponId').val() || coupenObj.couponId;
        var eventAmt = parentObj.find('#mrceventAmt').val() || coupenObj.eventAmt;
        var mrightsId = parentObj.find('#mrcmcouponId').val() || coupenObj.mcouponId;
        var valFace = parentObj.find('#mrvalFace').val() || coupenObj.valFace;
        var valOver = parentObj.find('#mrcvalOver').val() || coupenObj.valOver;
        var valMinus = parentObj.find('#mrcvalMinus').val() || coupenObj.valMinus;
        var busiType = parentObj.find('#mrcbusiType').val();
        var couType = parentObj.find('#mrccouType').val();
        if (busiType === undefined || busiType === null || busiType === '') {
            busiType = coupenObj.busiType;
        }
        if (couType === undefined || couType === null || couType === '') {
            couType = coupenObj.couType;
        }
        busiType = Number(busiType);
        couType = Number(couType);

        $('#coupeAdd_title').val(coupenObj.title || parentObj.find('#mrctitle').val() || '');
        applyCouponTypeToForm(busiType, couType);
        window.lastSelectedCoupon = {
            couponId: couponId,
            busiType: busiType,
            couType: couType,
            title: coupenObj.title || parentObj.find('#mrctitle').val() || ''
        };

        this.mrightsId = mrightsId;
        this.couponId = couponId;
        this.operCouponId = couponId;
        window.couponId = couponId;

        $('#eventAmt').val(eventAmt);
        $('#valOver').val(valOver);
        $('#valMinus').val(valMinus);
        $('#valFace').val(valFace);

        if (couType == 1) {
            $('.coupetypr_price').show();
            $('.coupetypr_discount').hide();
        } else {
            $('.coupetypr_price').hide();
            $('.coupetypr_discount').show();
        }

        $('.pop_oper').val(3);
        coupenDetail(couponId, 3);
        showCoupePop();
    }

    // 添加权益（弹窗内）
    function addColumn (obj) {
        var priceId = $('#editMemberPriceId').val();
        if (!priceId) {
            $.modal.msgWarning('请先保存价格包');
            return;
        }
        let appendDom = $('#modalRightsArea');
        appendDom.append($('#rights-empty-template').html());
        let newDom = appendDom.find('.interests_item:last');
        applyRightsId(newDom, '');
        newDom.find('.interestsIcon').attr('src', '');
        newDom.find('#interestsTitle').val('');
        newDom.find('#interestsSubTitle').val('');
        newDom.find('#interestsDesc').val('');
        newDom.find('.member-coupes-item').html('');
        syncPackageDaysText();
    }

    function readRightsId($item) {
        if (!$item || !$item.length) {
            return '';
        }
        var id = $item.attr('data-mrights-id')
            || $item.data('mrightsId')
            || $item.find('.js-mrights-id').val()
            || '';
        id = $.trim(String(id));
        return (!id || id === 'undefined' || id === 'null') ? '' : id;
    }

    function applyRightsId($item, mrightsId) {
        if (!$item || !$item.length) {
            return;
        }
        mrightsId = mrightsId ? String(mrightsId) : '';
        $item.attr('data-mrights-id', mrightsId);
        $item.data('mrightsId', mrightsId);
        $item.find('.js-mrights-id').val(mrightsId);
        var $inner = $item.closest('.interests_inner');
        if ($inner.length) {
            $inner.attr('data-mrights-id', mrightsId);
            $inner.data('mrightsId', mrightsId);
        }
    }

    // 保存权益/删除权益
    function saveColumn(obj, num) {
        var objDom = $(obj).closest('.interests_item');
        var priceId = $('#editMemberPriceId').val();
        if (!priceId) {
            $.modal.msgWarning('请先保存价格包');
            return;
        }
        if (objDom.data('rightsSaving')) {
            return;
        }
        var mrightsId = readRightsId(objDom);
        var postData = [];
        postData.push({
            "name": "cover",
            "value": objDom.find('#interestsIcon').attr('src')
        }, {
            "name": "detail",
            "value": objDom.find('#interestsDesc').val()
        }, {
            "name": "memberId",
            "value": member.memberId
        }, {
            "name": "seqNo",
            "value": $('#modalRightsArea .interests_item').index(objDom)
        }, {
            "name": "state",
            "value": num
        }, {
            "name": "subTitle",
            "value": objDom.find('#interestsSubTitle').val()
        }, {
            "name": "title",
            "value": objDom.find('#interestsTitle').val()
        }, {
            "name": "memberPriceId",
            "value": priceId
        });

        if (num == 2) {
            if (mrightsId) {
                postData.push({"name": "mrightsId", "value" : mrightsId});
                objDom.data('rightsSaving', true);
                packageSave(prefix + "/edit_rights", postData, function (result) {
                    objDom.data('rightsSaving', false);
                    if (!result || result.code != web_status.SUCCESS) {
                        return;
                    }
                    pricePackageNeedReload = true;
                    objDom.closest('.interests_inner').remove();
                });
            } else {
                objDom.closest('.interests_inner').remove();
            }
        } else {
            if (mrightsId) {
                postData.push({"name": "mrightsId", "value" : mrightsId});
            }
            objDom.data('rightsSaving', true);
            packageSave(prefix + "/edit_rights", postData, function (result) {
                objDom.data('rightsSaving', false);
                if (!result || result.code != web_status.SUCCESS) {
                    return;
                }
                pricePackageNeedReload = true;
                var rights = result.data || {};
                var newId = rights.mrightsId || rights.mRightsId || '';
                if (newId) {
                    applyRightsId(objDom, newId);
                } else {
                    $.modal.msgWarning('权益已保存，但未返回权益ID，请关闭弹窗后重新打开再添加券');
                }
            });
        }
    }

    /*基础信息-修改*/
    $("#form-member-edit").validate({
        onkeyup: false,
        rules:{
            title:{
                required:true,
            },
            subTitle:{
                required:true,
            },
            // limitation:{
            //     required:true,
            // },
            // interestsDetail:{
            //     required:true,
            // },
            noticeInfo:{
                required:true,
            },
            notes:{
                required:true,
            },
            onsale:{
                required:true,
            },
        },
        messages: {
            "title": {
                required: "请输入标题",
            },
            "subTitle": {
                required: "请输入会员说明",
            },
            // "limitation": {
            //     required: "请选择是否限购",
            // },
            // "interestsDetail": {
            //     required: "请填写弹窗文案",
            // },
            "noticeInfo": {
                required: "请填写弹窗文案",
            },
            "notes": {
                required: "请填写注意事项",
            },
            "onsale": {
                required: "请选择是否开售",
            },
        },
        focusCleanup: true
    });

    // 保存基础信息
    function submitMemberInfo() {
        if ($.validate.form()) {
            var formData = $('#form-member-edit').serializeArray();
            formData.push({"name": "avatar", "value": $(".memberBanner").attr('src')});
            formData.push({"name": "icon", "value": $(".memberLast").attr('src')});
            formData.push({"name": "name", "value": member.name});
            $.operate.save(prefix + "/edit_basic", formData);
        }
    }

    var pricePackageNeedReload = false;

    // 保存价格（有 memberPriceId 则更新，空则新增）
    function reloadOnMembershipTab() {
        window.localStorage.setItem('tabActive', '1');
        window.location.reload();
    }

    function findPriceById(memberPriceId) {
        var list = memberPriceList || [];
        for (var i = 0; i < list.length; i++) {
            if (String(list[i].memberPriceId) === String(memberPriceId)) {
                return list[i];
            }
        }
        return null;
    }

    function updatePriceRowState(memberPriceId, state) {
        var mp = findPriceById(memberPriceId);
        if (mp) {
            mp.state = state;
        }
        var $tr = $('#membership table tbody tr').filter(function () {
            return $.trim($(this).children('td').eq(0).text()) === String(memberPriceId);
        });
        if (!$tr.length) {
            return;
        }
        var statusHtml = state === 1
            ? '<span class="badge badge-primary">上线中</span>'
            : '<span class="badge">已下线</span>';
        var opHtml = '<a class="btn btn-xs btn-info" href="javascript:void(0)" onclick="openPriceModal(\'edit\', findPriceById(\'' + memberPriceId + '\'))">编辑</a> ';
        if (state === 1) {
            opHtml += '<a class="btn btn-xs btn-danger" href="javascript:void(0)" onclick="offlinePrice(\'' + memberPriceId + '\')">下线</a>';
        } else {
            opHtml += '<a class="btn btn-xs btn-warning" href="javascript:void(0)" onclick="onlinePrice(\'' + memberPriceId + '\')">重新上线</a>';
        }
        $tr.children('td').eq(6).html(statusHtml);
        $tr.children('td').eq(7).html(opHtml);
    }

    function submitMemberShip () {
        var wasNew = !$('#editMemberPriceId').val();
        var MemberShipData = $('#form-membership-edit').serializeArray();
        MemberShipData.push({"name": "memberId", "value": member.memberId});
        MemberShipData.push({"name": "state", "value": 1});
        packageSave(prefix + "/edit_price", MemberShipData, function (result) {
            if (!result || result.code != web_status.SUCCESS) {
                return;
            }
            // 列表等关闭弹窗时再刷新，避免整页跳走
            pricePackageNeedReload = true;
            var mp = result.data || {};
            if (mp.memberPriceId) {
                $('#editMemberPriceId').val(mp.memberPriceId);
                $('#editPriceName').val(mp.name || $('#editPriceName').val());
                $('#editPrice').val(mp.price != null ? mp.price : $('#editPrice').val());
                $('#editPriceFixed').val(mp.priceFixed != null ? mp.priceFixed : $('#editPriceFixed').val());
                $('#editPriceSpecial').val(mp.priceSpecial != null ? mp.priceSpecial : $('#editPriceSpecial').val());
                $('#editDays').val(mp.days != null ? mp.days : $('#editDays').val());
                $('#pricePackageModalTitle').text('编辑价格包 · ' + ($('#editPriceName').val() || '') + ' (' + mp.memberPriceId + ')');
                if (wasNew) {
                    loadRightsIntoModal(mp.memberPriceId);
                } else {
                    syncPackageDaysText();
                    setRightsEditable(true);
                }
            }
        });
    }

    function syncPackageDaysText() {
        var days = $('#editDays').val() || '';
        $('#modalRightsArea .mrcdays').val(days);
        $('#modalRightsArea .package-days-text').text(days ? (days + '天') : '天');
    }

    function setRightsEditable(enabled) {
        if (enabled) {
            $('#modalRightsLockTip').hide();
            $('#modalRightsArea').css({opacity: 1, 'pointer-events': 'auto'});
            $('#modalRightsHint').text('（自动绑定当前价格包）');
        } else {
            $('#modalRightsLockTip').show();
            $('#modalRightsArea').empty().css({opacity: 0.45, 'pointer-events': 'none'});
            $('#modalRightsHint').text('');
        }
    }

    function loadRightsIntoModal(memberPriceId) {
        var area = $('#modalRightsArea');
        area.empty();
        if (!memberPriceId) {
            setRightsEditable(false);
            return;
        }
        setRightsEditable(true);
        var matched = $('#rights-store .rights-store-item').filter(function () {
            return String($(this).attr('data-price-id') || '') === String(memberPriceId);
        });
        if (matched.length) {
            matched.each(function () {
                area.append($(this).clone(true, true));
            });
        } else {
            area.append($('#rights-empty-template').html());
            area.find('.interests_item:last').attr('data-mrights-id', '');
        }
        syncPackageDaysText();
    }

    function openPriceModal(mode, mp) {
        pricePackageNeedReload = false;
        if (mode === 'add') {
            $('#pricePackageModalTitle').text('新增价格包');
            $('#editMemberPriceId').val('');
            $('#editPriceName').val('');
            $('#editPrice').val('');
            $('#editPriceFixed').val('');
            $('#editPriceSpecial').val('');
            $('#editDays').val('');
            loadRightsIntoModal('');
        } else {
            mp = mp || {};
            $('#pricePackageModalTitle').text('编辑价格包 · ' + (mp.name || '') + ' (' + (mp.memberPriceId || '') + ')');
            $('#editMemberPriceId').val(mp.memberPriceId || '');
            $('#editPriceName').val(mp.name || '');
            $('#editPrice').val(mp.price != null ? mp.price : '');
            $('#editPriceFixed').val(mp.priceFixed != null ? mp.priceFixed : '');
            $('#editPriceSpecial').val(mp.priceSpecial != null ? mp.priceSpecial : '');
            $('#editDays').val(mp.days != null ? mp.days : '');
            loadRightsIntoModal(mp.memberPriceId || '');
        }
        $('#pricePackageModal').modal('show');
    }

    // 弹窗关闭时：若保存过价格包，刷新列表并留在套餐 Tab
    $('#pricePackageModal').on('shown.bs.modal', function () {
        // 允许加券/上传等外层弹层内的 input 获得焦点
        $(document).off('focusin.bs.modal');
    });

    $('#pricePackageModal').on('hidden.bs.modal', function () {
        clearUiShade();
        if (pricePackageNeedReload) {
            pricePackageNeedReload = false;
            reloadOnMembershipTab();
        }
    });

    function offlinePrice(memberPriceId) {
        $.modal.confirm("确认下线该价格包？", function () {
            var data = [
                {"name": "memberId", "value": member.memberId},
                {"name": "memberPriceId", "value": memberPriceId},
                {"name": "state", "value": 2},
                {"name": "price", "value": 0.01},
                {"name": "priceFixed", "value": 0.01},
                {"name": "priceSpecial", "value": 0.01},
                {"name": "days", "value": 1}
            ];
            packageSave(prefix + "/edit_price", data, function () {
                updatePriceRowState(memberPriceId, 2);
            });
        });
    }

    function onlinePrice(memberPriceId) {
        $.modal.confirm("确认重新上线该价格包？", function () {
            var data = [
                {"name": "memberId", "value": member.memberId},
                {"name": "memberPriceId", "value": memberPriceId},
                {"name": "state", "value": 1}
            ];
            packageSave(prefix + "/edit_price", data, function () {
                updatePriceRowState(memberPriceId, 1);
            });
        });
    }

</script>
</body>
</html>
