package cn.pluss.platform.controller;

import cn.pluss.platform.activityActivate.ActivityActivateService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.entity.ActivityActivate;
import cn.pluss.platform.entity.MerchantMenber;
import cn.pluss.platform.entity.MerchantMenberRecharge;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantMenberComsume.MerchantMenberComsumeService;
import cn.pluss.platform.merchantMenberRecharge.MerchantMenberRechargeService;
import cn.pluss.platform.phoneValidateCode.PhoneValidateCodeService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.EmojiUtil;
import cn.pluss.platform.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/merchantMenber")
@Transactional
@Slf4j
@RequiredArgsConstructor
@Api(value = "MerchantMenber控制类", tags = {"MerchantMenber接口"})
public class MerchantMenberController {
    private final MerchantMenberService merchantMenberService;
    private final MerchantMenberComsumeService merchantMenberComsumeService;
    private final MerchantMenberRechargeService merchantMenberRechargeService;
    private final PhoneValidateCodeService phoneValidateCodeService;
    private final MerchantBaseInfoService merchantBaseInfoService;
    private final ActivityActivateService activityActivateService;
    private final MemberOrderService memberOrderService;

    @Autowired @Lazy
    private UserAppService userAppService;


    @PostMapping
    @ApiOperation(tags = {"页面-会员选择", "页面-会员_管理"}, value = "获取全部", notes = "返回分页过后的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantMenber", value = "查询对象的实例信息", paramType = "body", dataType = "MerchantMenber"),})
    public Result<PageInfo<MerchantMenber>> list(@RequestBody MerchantMenber merchantMenber) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantMenber.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(merchantMenber.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码！");
        }
        if (merchantMenber.getSize() == null || merchantMenber.getSize() == 0) {
            merchantMenber.setSize(ProjectConstant.PAGE_SIZE);
        }
        if (merchantMenber.getPage() == null || merchantMenber.getPage() == 0) {
            merchantMenber.setPage(1);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", merchantMenber.getSize());
        map.put("offset", (merchantMenber.getPage() - 1) * merchantMenber.getSize());
        map.put("merchantCode", merchantMenber.getMerchantCode());
        map.put("memberCode", merchantMenber.getMemberCode());
        if (StringUtil.isNotEmpty(merchantMenber.getStoreId())) {
            map.put("storeId", merchantMenber.getStoreId());
        }
        if (!StringUtil.isEmpty(merchantMenber.getPhone()) || !StringUtil.isEmpty(merchantMenber.getMemberName())) {
            map.put("keyWord", "1");
        }
        //判断是否有检索条件
        if (StringUtil.isNotEmpty(merchantMenber.getPhone())) {
            map.put("phone", merchantMenber.getPhone());
        }
        if (StringUtil.isNotEmpty(merchantMenber.getNickName())) {
            map.put("nickName", merchantMenber.getNickName());
        }
        List<MerchantMenber> merchantMenberList = merchantMenberService.queryMerchantMenberPage(map);
        for (MerchantMenber m : merchantMenberList) {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("memberCode", m.getMemberCode());
            orderMap.put("orderType", "0");
            orderMap.put("orderStatus", "1");
            Integer count = memberOrderService.queryMemberOrderPageCount(orderMap);
            m.setOrderNumber(count + "");

            if (StringUtils.isNotBlank(m.getAppOpenId())) {
                m.setOpenid(m.getAppOpenId());
            }
        }
        Integer count = merchantMenberService.queryMerchantMenberPageCount(map);

        for (MerchantMenber menber : merchantMenberList) {
            menber.setNickName(EmojiUtil.emojiRecovery2(menber.getNickName()));
        }

        // 返回参数
        PageInfo<MerchantMenber> pager = new PageInfo<>(count.longValue(), (long)StringUtil.getPageCount(count, merchantMenber.getSize()),
                merchantMenber.getPage().longValue(), merchantMenber.getSize().longValue(), merchantMenberList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @GetMapping("/queryMemberIsExist")
    @ApiOperation(tags = {"会员开卡"}, value = "获取关注公众号二维码", notes = "获取关注公众号二维码", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号"),
            @ApiImplicitParam(name = "checkCode", value = "验证码"),
            @ApiImplicitParam(name = "nickName", value = "会员名"),
            @ApiImplicitParam(name = "birthday", value = "生日"),
    })
    public Result<String> queryMemberIsExist(@RequestParam String merchantCode, String storeId,
                                     @RequestParam String phone, @RequestParam String checkCode,
                                     @RequestParam String nickName, @RequestParam String birthday) {

        String result = merchantMenberService.queryMemberIsExist(merchantCode, storeId, phone, checkCode, nickName, birthday);
        return ResultGenerator.genSuccessResult(result);
    }

    @GetMapping("/queryMemberIsExistV2")
    @ApiOperation(tags = {"会员开卡"}, value = "获取关注公众号二维码", notes = "获取关注公众号二维码", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantCode", value = "商家编码"),
            @ApiImplicitParam(name = "storeId", value = "门店Id"),
            @ApiImplicitParam(name = "phone", value = "手机号"),
            @ApiImplicitParam(name = "checkCode", value = "验证码"),
            @ApiImplicitParam(name = "nickName", value = "会员名"),
            @ApiImplicitParam(name = "birthday", value = "生日"),
    })
    public Result<String> queryMemberIsExistV2(String merchantCode, String storeId,
                                             @RequestParam String phone, @RequestParam String checkCode,
                                             @RequestParam String nickName, @RequestParam String birthday) {

        String result = merchantMenberService.queryMemberIsExistV2(merchantCode, storeId, phone, checkCode, nickName, birthday);
        return ResultGenerator.genSuccessResult(result);
    }

    @GetMapping("/queryIsOenCardSuccess")
    @ApiOperation(value = "会员是否开卡成功", notes = "会员是否开卡成功", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantCode", value = "商家编码", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店Id", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true),
    })
    public Result queryIsOenCardSuccess(@RequestParam String phone, @RequestParam String merchantCode, @RequestParam String storeId) {
        MerchantMenber merchantMenber = new MerchantMenber();
        merchantMenber.setStoreId(storeId);
        merchantMenber.setPhone(phone);
        merchantMenber.setMerchantCode(merchantCode);
        List<MerchantMenber> queryMerchantMenberList = merchantMenberService.queryMerchantMenberList(merchantMenber);
        if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
            merchantMenber = queryMerchantMenberList.get(0);
            if (StringUtil.isEmpty(merchantMenber.getOpenid())) {
                return ResultGenerator.genFailResult("请稍等，会员还未进行绑卡");
            } else {
                return ResultGenerator.genSuccessResult("开卡成功");
            }
        } else {
            return ResultGenerator.genFailResult("开卡失败");
        }
    }

    public void dealMemberActivity(MerchantMenber merchantMenber) {
        ActivityActivate querActivityActivate = new ActivityActivate();
        querActivityActivate.setStoreId(merchantMenber.getStoreId());
        List<ActivityActivate> activityActivateList = activityActivateService.queryActivityActivateList(querActivityActivate);
        if (activityActivateList != null && activityActivateList.size() > 0) {
            querActivityActivate = activityActivateList.get(0);
            MerchantMenberRecharge merchantMenberRecharge = new MerchantMenberRecharge();//增加会员的储值记录
            merchantMenberRecharge.setMerchantCode(merchantMenber.getMerchantCode());
            merchantMenberRecharge.setMerchantName(merchantMenber.getMerchantName());
            merchantMenberRecharge.setStoreId(merchantMenber.getStoreId());
            merchantMenberRecharge.setStoreName(merchantMenber.getStoreName());
            merchantMenberRecharge.setCreateDt(new Date());
            merchantMenberRecharge.setMemberCode(merchantMenber.getMemberCode());
            merchantMenberRecharge.setNickName(merchantMenber.getNickName());
            merchantMenberRecharge.setPhone(merchantMenber.getPhone());
            merchantMenberRecharge.setRechargeMoney(0d);
            merchantMenberRecharge.setGiveMoney(querActivityActivate.getGiveMoney());
            merchantMenberRecharge.setPayType(2);
            merchantMenberRechargeService.saveMerchantMenberRecharge(merchantMenberRecharge);
            //更新会员的赠送金额
            MerchantMenber updateMerchantMenber = new MerchantMenber();
            updateMerchantMenber.setId(merchantMenber.getId());
            if (merchantMenber.getTotalGiveFee() == null) {
                merchantMenber.setTotalGiveFee(0.0);
            }
            updateMerchantMenber.setTotalGiveFee(merchantMenber.getTotalGiveFee() + querActivityActivate.getGiveMoney());
            if (merchantMenber.getUsableGiveFee() == null) {
                merchantMenber.setUsableGiveFee(0.0);
            }

            updateMerchantMenber.setUsableGiveFee(merchantMenber.getUsableGiveFee() + querActivityActivate.getGiveMoney());
            merchantMenberService.updateMerchantMenber(updateMerchantMenber);
        }
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)})
    public Result delete(@PathVariable Integer id) {
        MerchantMenber merchantMenber = new MerchantMenber();
        merchantMenber.setId(id);
        merchantMenberService.deleteMerchantMenber(merchantMenber);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantMenber", value = "更新的MerchantMenber实例", paramType = "body", dataType = "MerchantMenber", required = true)})
    public Result update(@RequestBody MerchantMenber merchantMenber) {
        merchantMenberService.updateMerchantMenber(merchantMenber);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/queryDetailByMemberCode")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantMenber", value = "查询的实例信息", paramType = "body", required = true, dataType = "MerchantMenber")})
    public Result detail(@RequestBody MerchantMenber merchantMenber) {
        MerchantMenber queryerchantMenber = new MerchantMenber();
        queryerchantMenber.setMemberCode(merchantMenber.getMemberCode());
        queryerchantMenber = merchantMenberService.queryMerchantMenber(merchantMenber);
        return ResultGenerator.genSuccessResult(queryerchantMenber);
    }

    @PostMapping("/queryMerchantMemberData")
    @ApiOperation(tags = {"页面-会员_数据"}, value = "查询当前商家的会员信息", notes = "查看单个项目的内容", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantMenber", value = "查询的实例信息", paramType = "body", required = true, dataType = "MerchantMenber")})
    public Result queryMerchantMemberData(@RequestBody MerchantMenber merchantMenber) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantMenber.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(merchantMenber.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码！");
        }
        // 当前时间毫秒数
        long current = System.currentTimeMillis();
        // 今天零点零分零秒的毫秒数
        long zeroT = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        String zero = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(zeroT);
        // 今天23点59分59秒的毫秒数
        long endT = zeroT + 24 * 60 * 60 * 1000 - 1;
        String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endT);
        Map<String, String> memberMap = new HashMap<>();
        memberMap.put("startTime", zero);
        memberMap.put("endTime", end);
        memberMap.put("merchantCode", merchantMenber.getMerchantCode());
        Map<String, String> totalMemberMap = new HashMap<>();
        totalMemberMap.put("endTime", end);
        totalMemberMap.put("merchantCode", merchantMenber.getMerchantCode());
        // 查询今日会员充值金额
        double todayRecharg = merchantMenberService.queryMerchantMemberBill(null, "1", merchantMenber.getMerchantCode(), zero, end);
        // 查询今日会员消费金额
        double todayConsume = merchantMenberService.queryMerchantMemberBill(null, "0", merchantMenber.getMerchantCode(), zero, end);
        // 查询今日会员线上充值金额 + app扫码充值
        double onlineRecharg = merchantMenberService.queryMerchantMemberBill("0", "1", merchantMenber.getMerchantCode(), zero, end);
        // 查询今日会员扫码充值
        double scanRecharge = merchantMenberService.queryMerchantMemberBill("2", "1", merchantMenber.getMerchantCode(), zero, end);
        // 查询今日会员现金充值金额
        double cashRecharg = merchantMenberService.queryMerchantMemberBill("1", "1", merchantMenber.getMerchantCode(), zero, end);
        // 查询会员可用充值金额
        double totalRemainRecharg = merchantMenberService.queryMerchantMenberUsableRechargeFee(totalMemberMap);
        // 查询会员充值总额
        double totalRecharg = merchantMenberService.queryMerchantMemberBill(null, "1", merchantMenber.getMerchantCode(), null, null);
        // 查询会员消费总额
        double totalConsume = merchantMenberService.queryMerchantMemberBill(null, "0", merchantMenber.getMerchantCode(), null, null);
        // 查询今日新增会员人数
        double todayRegistNum = merchantMenberService.queryMerchantMenberNumByTime(memberMap);
        // 查询所有会员数
        double totalMemberNum = merchantMenberService.queryMerchantMenberNumByTime(totalMemberMap);
        double giveReturn = merchantMenberService.queryMerchantGiveMoney(merchantMenber.getMerchantCode());
        MerchantMenber queryerchantMenber = new MerchantMenber();
        queryerchantMenber.setMerchantCode(merchantMenber.getMerchantCode());
        queryerchantMenber.setTodayRecharg(todayRecharg);
        queryerchantMenber.setTodayConsume(todayConsume);
        queryerchantMenber.setTodayRegistNum(todayRegistNum);
        queryerchantMenber.setOnlineRecharg(onlineRecharg);
        queryerchantMenber.setGiveReturn(giveReturn);
        queryerchantMenber.setCashRecharg(cashRecharg);
        queryerchantMenber.setTotalRecharg(totalRecharg);
        queryerchantMenber.setTotalRemainRecharg(totalRemainRecharg);
        queryerchantMenber.setTotalConsume(totalConsume);
        queryerchantMenber.setTotalMemberNum(totalMemberNum);
        queryerchantMenber.setScanRecharge(scanRecharge);
        return ResultGenerator.genSuccessResult(queryerchantMenber);
    }

}
