package com.jeequan.jeepay.mch.ctrl.member;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.MemberRechargeRule;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.MchStoreService;
import com.jeequan.jeepay.service.impl.MemberRechargeRuleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 会员充值规则管理
 *
 * @author xiaoyu
 *
 * @date 2023/4/13 17:22
 */
@RestController
@RequestMapping("/api/member/rechargeRule")
public class MemberRechargeRuleController extends CommonCtrl {

    @Autowired private MemberRechargeRuleService memberRechargeRuleService;
    @Autowired private MchConfigService mchConfigService;
    @Autowired private MchStoreService mchStoreService;

    /**
     * @author: xiaoyu
     * @date: 2023/4/13 17:24
     * @describe: 会员充值规则列表
     */
    @PreAuthorize("hasAuthority('ENT_MEMBER_RECHARGE_LIST')")
    @GetMapping
    public ApiRes list() {
        MemberRechargeRule rechargeRule = getObject(MemberRechargeRule.class);

        LambdaQueryWrapper<MemberRechargeRule> wrapper = MemberRechargeRule.gw();
        // 商户号
        wrapper.eq(MemberRechargeRule::getMchNo, getCurrentMchNo());
        // 充值ID
        wrapper.eq(rechargeRule.getRuleId() != null, MemberRechargeRule::getRuleId, rechargeRule.getRuleId());
        // 充值金额
        wrapper.eq(rechargeRule.getRechargeAmount() != null, MemberRechargeRule::getRechargeAmount, rechargeRule.getRechargeAmount());
        // 会员状态
        wrapper.eq(rechargeRule.getState() != null, MemberRechargeRule::getState, rechargeRule.getState());
        //门店id和名称
        if (StringUtils.isNotEmpty(rechargeRule.getStoreId())){
            wrapper.and(i->i.eq(MemberRechargeRule::getStoreId,rechargeRule.getStoreId())
                    .or().eq(MemberRechargeRule::getStoreName,rechargeRule.getStoreId()));
        }
        // 时间范围条件
        Date[] dateRange = rechargeRule.buildQueryDateRange();
        if (dateRange[0] != null) {
            wrapper.ge(MemberRechargeRule::getCreatedAt, dateRange[0]);
        }
        if (dateRange[1] != null) {
            wrapper.le(MemberRechargeRule::getCreatedAt, dateRange[1]);
        }
        wrapper.orderByAsc(MemberRechargeRule::getSort);
        wrapper.orderByDesc(MemberRechargeRule::getCreatedAt);

        IPage page = memberRechargeRuleService.page(getIPage(true), wrapper);
        return ApiRes.page(page);
    }

    /**
     * @author: xiaoyu
     * @date: 2023/4/13 19:09
     * @describe: 新增会员充值规则
     */
    @PreAuthorize("hasAuthority('ENT_MEMBER_RECHARGE_ADD')")
    @MethodLog(remark = "新增会员充值规则")
    @PostMapping
    public ApiRes add() {
        // 充值金额
        Long rechargeAmount = getRequiredAmountL("rechargeAmount");
        // 赠送金额
        Long giveAmount = getAmountL("giveAmount");
        MemberRechargeRule rechargeRule = getObject(MemberRechargeRule.class);
        // 商户号
        rechargeRule.setMchNo(getCurrentMchNo());
        // 充值金额
        rechargeRule.setRechargeAmount(rechargeAmount);
        // 赠送金额
        rechargeRule.setGiveAmount(giveAmount);
        //将规则同步到门店
        if (rechargeRule.getIsAllStore() != null){
            memberRechargeRuleService.saveDB(rechargeRule);
        }
        return ApiRes.ok();
    }

    /**
     * @author: xiaoyu
     * @date: 2023/4/13 17:49
     * @describe: 会员充值规则信息
     */
    @PreAuthorize("hasAnyAuthority('ENT_MEMBER_RECHARGE_VIEW', 'ENT_MEMBER_RECHARGE_EDIT')")
    @GetMapping("/{ruleId}")
    public ApiRes detail(@PathVariable("ruleId") String ruleId) {

        MemberRechargeRule rechargeRule = memberRechargeRuleService.getById(ruleId);

        if (rechargeRule == null || !rechargeRule.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        return ApiRes.ok(rechargeRule);
    }

   /**
    * @author: xiaoyu
    * @date: 2023/4/13 17:51
    * @describe: 更新会员充值规则
    */
    @PreAuthorize("hasAuthority('ENT_MEMBER_RECHARGE_EDIT')")
    @MethodLog(remark = "更新会员充值规则")
    @PutMapping("/{ruleId}")
    public ApiRes update(@PathVariable("ruleId") String ruleId) {
        // 校验当前会员信息
        MemberRechargeRule dbRechargeRule = memberRechargeRuleService.getById(ruleId);
        if (dbRechargeRule == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        // 充值金额
        Long rechargeAmount = getRequiredAmountL("rechargeAmount");
        // 赠送金额
        Long giveAmount = getAmountL("giveAmount");

        MemberRechargeRule rechargeRule = getObject(MemberRechargeRule.class);
        rechargeRule.setMchNo(null);
        // 充值金额
        rechargeRule.setRechargeAmount(rechargeAmount);
        // 赠送金额
        rechargeRule.setGiveAmount(giveAmount);

        if (!dbRechargeRule.getMchNo().equals(getCurrentMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        // 更新信息
        boolean result = memberRechargeRuleService.updateById(rechargeRule);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return ApiRes.ok();
    }

    /**
     * @author: xiaoyu
     * @date: 2023/4/13 17:58
     * @describe: 删除会员充值规则
     */
    @PreAuthorize("hasAuthority('ENT_MEMBER_RECHARGE_DELETE')")
    @MethodLog(remark = "删除会员充值规则")
    @DeleteMapping("/{ruleId}")
    public ApiRes delete(@PathVariable("ruleId") String ruleId) {
        MemberRechargeRule rechargeRule = memberRechargeRuleService.getById(ruleId);

        if (rechargeRule == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        if (!rechargeRule.getMchNo().equals(getCurrentMchNo())) {
            throw new BizException("无权操作！");
        }
        memberRechargeRuleService.removeById(ruleId);
        //清除绑定的门店信息
        MchStore getMchStore = mchStoreService.getById(rechargeRule.getStoreId());
        if (getMchStore != null){
            mchStoreService.update(new LambdaUpdateWrapper<MchStore>()
                    .set(MchStore::getRuleId,null)
                    .eq(MchStore::getStoreId,rechargeRule.getStoreId()));
        }
        return ApiRes.ok();
    }

}
