package com.fzm.mall.server.admin.home_page.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.auth_center.entity.dto.AddAdminDTO;
import com.fzm.mall.server.admin.auth_center.entity.dto.RepairAdminRoleDTO;
import com.fzm.mall.server.admin.auth_center.entity.dto.ResetAdminPwdDTO;
import com.fzm.mall.server.admin.auth_center.enums.type.AdminRoleTypeEnum;
import com.fzm.mall.server.admin.auth_center.service.IAdminRoleService;
import com.fzm.mall.server.admin.config.Redis;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.enums.response.MallResponseEnum;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.goods_center.model.Spu;
import com.fzm.mall.server.admin.goods_center.service.ICountService;
import com.fzm.mall.server.admin.goods_center.service.ISpuService;
import com.fzm.mall.server.admin.home_page.dao.AdminMapper;
import com.fzm.mall.server.admin.home_page.entity.dto.RepairPwdDTO;
import com.fzm.mall.server.admin.home_page.entity.dto.ResetPwdDTO;
import com.fzm.mall.server.admin.home_page.entity.dto.SetPwdDTO;
import com.fzm.mall.server.admin.home_page.entity.vo.AdminVO;
import com.fzm.mall.server.admin.home_page.entity.vo.MerchantStatistics;
import com.fzm.mall.server.admin.home_page.entity.vo.PersonInfoVO;
import com.fzm.mall.server.admin.home_page.entity.vo.PlatformStatistics;
import com.fzm.mall.server.admin.home_page.enums.status.AdminStatusEnum;
import com.fzm.mall.server.admin.home_page.enums.status.MerchantRegisterEnum;
import com.fzm.mall.server.admin.home_page.enums.type.AdminTypeEnum;
import com.fzm.mall.server.admin.home_page.enums.type.RepairPwdTypeEnum;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.model.Merchant;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.home_page.service.IMerchantService;
import com.fzm.mall.server.admin.order.model.Order;
import com.fzm.mall.server.admin.order.model.OrderDetail;
import com.fzm.mall.server.admin.order.service.IOrderDetailService;
import com.fzm.mall.server.admin.order.service.IOrderService;
import com.fzm.mall.server.admin.system.model.SysConfig;
import com.fzm.mall.server.admin.system.service.ISysConfigService;
import com.fzm.mall.server.admin.user_center.model.User;
import com.fzm.mall.server.admin.user_center.model.UserFollow;
import com.fzm.mall.server.admin.user_center.model.UserFoot;
import com.fzm.mall.server.admin.user_center.service.IUserFollowService;
import com.fzm.mall.server.admin.user_center.service.IUserFootService;
import com.fzm.mall.server.admin.user_center.service.IUserService;
import com.fzm.mall.server.admin.util.DateUtil;
import com.fzm.mall.server.admin.util.Sha256Util;
import com.fzm.mall.server.admin.util.SmsUtil;
import com.fzm.mall.server.admin.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangp
 * @date 2021/2/26 16:06
 * @description 管理员服务实现类
 * @since JDK 1.8
 */
@Service
@Transactional
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private DozerBeanMapper beanMapper;
    @Autowired
    private Redis redis;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private ISpuService spuService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IUserFollowService userFollowService;
    @Autowired
    private IUserFootService userFootService;
    @Autowired
    private ICountService countService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IAdminRoleService adminRoleService;
    @Autowired
    private IUserService userService;

    @Override
    public void initPlatformAdmin(Admin admin) {
        boolean isExist = getPlatformAdminIsExist(admin.getType());
        if (isExist)
            return;
        admin.setAdminId(UUIDUtil.getUUID());
        save(admin);
    }

    @Override
    public void initAdmin(Admin admin) {
        Integer status = AdminStatusEnum.NORMAL.getStatus();
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.lambda().eq(Admin::getAccount, admin.getAccount())
                .eq(Admin::getStatus, status);
        if (getOne(qw) != null)
            return;
        admin.setAdminId(UUIDUtil.getUUID());
        save(admin);
    }


    @Override
    public void addPlatForm(AddAdminDTO platFormAdminDTO) {
        Admin admin = beanMapper.map(platFormAdminDTO, Admin.class);
        admin.setAdminId(UUIDUtil.getUUID());
        admin.setMerchantId(MALLGlobalConfig.PLATFORM_MERCHANT_ID);
        admin.setType(AdminTypeEnum.PLATFORM.getType());
        admin.setStatus(AdminStatusEnum.NORMAL.getStatus());
        admin.setPassword(Sha256Util.encode(admin.getPassword()));
        boolean save = save(admin);
        if (!save) {
            throw new MyException(MallResponseError.SAVE_ERROR);
        }
    }

    @Override
    public void add(AddAdminDTO adminDTO, String merchantId, Integer type) {
        Admin admin = beanMapper.map(adminDTO, Admin.class);
        admin.setAdminId(UUIDUtil.getUUID());
        admin.setMerchantId(merchantId);
        admin.setType(type.equals(
                AdminTypeEnum.PLATFORM_ADMINISTRATOR.getType()) ?
                AdminTypeEnum.PLATFORM.getType() : type);
        admin.setStatus(AdminStatusEnum.NORMAL.getStatus());
        admin.setPassword(Sha256Util.encode(admin.getPassword()));

        SysConfig headImg = sysConfigService.getOne(new QueryWrapper<SysConfig>().lambda().eq(SysConfig::getDictKey, "admin_head_img"));
        admin.setHeadImg(headImg.getDictValue());
        save(admin);
    }

    @Override
    public Admin login(String account, String password) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getAccount, account);
        qw.eq(Admin::getPassword, Sha256Util.encode(password));
        qw.ne(Admin::getStatus, AdminStatusEnum.DELETE.getStatus());
        return getOne(qw);
    }

    @Override
    public Admin getByAdminId(String adminId) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getAdminId, adminId);
        qw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
        return getOne(qw);
    }

    @Override
    public List<Admin> getByMerchantId(String merchantId) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getMerchantId, merchantId);
        qw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
        return list(qw);
    }

    @Override
    public String repairPwd(RepairPwdDTO repairPwdDTO, String adminId) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());

        Admin admin = null;
        Integer type = repairPwdDTO.getType();
        String phone = repairPwdDTO.getPhone();
        String pwd = repairPwdDTO.getPwd();
        String pCode = repairPwdDTO.getCode();
        String pToken = repairPwdDTO.getToken();

        switch (RepairPwdTypeEnum.getByType(type)) {
            case PWD:
                //使用原密码修改密码
                if (StringUtils.isBlank(pwd)) {
                    return MallResponseError.NULL_PARAM_ERROR;
                }

                qw.eq(Admin::getAdminId, adminId);
                admin = getOne(qw);

                if (!admin.getPassword().equals(Sha256Util.encode(pwd))) {
                    return MallResponseError.OLD_PASSWORD_ERROR;
                }
                break;
            case SMS:
                //使用验证码修改密码
                if (StringUtils.isBlank(phone) || StringUtils.isBlank(pCode)) {
                    return MallResponseError.NULL_PARAM_ERROR;
                }

                qw.eq(Admin::getAdminId, adminId);
                admin = getOne(qw);

                String code = redis.getKey(phone + MALLGlobalConfig.PHONE_CODE_REPAIR_PWD_REDIS_KEY_SUFFIX);
                if (!pCode.equals(code)) {
                    return MallResponseError.PHONE_CODE__ERROR;
                }
                break;
            case RESET:
                //重置密码
                if (StringUtils.isBlank(phone) || StringUtils.isBlank(pToken)) {
                    return MallResponseError.NULL_PARAM_ERROR;
                }

                String token = redis.getKey(phone + MALLGlobalConfig.IDENTITY_AUTH_REDIS_KEY_SUFFIX);
                if (!token.equals(pToken)) {
                    return MallResponseError.TOKEN_ERROR;
                }
                redis.del(phone + MALLGlobalConfig.IDENTITY_AUTH_REDIS_KEY_SUFFIX);

                qw.eq(Admin::getAccount, phone);
                admin = getOne(qw);
                break;
        }

        admin.setPassword(Sha256Util.encode(repairPwdDTO.getNewPwd()));

        if (updateById(admin)) {
            return MallResponseEnum.SUCCESS.code();
        } else {
            return MallResponseError.MYSQL_ERROR;
        }
    }

    @Override
    public void resetPwd(ResetPwdDTO resetPwdDTO) {
        LambdaUpdateWrapper<Admin> uw = new LambdaUpdateWrapper<>();
        uw.set(Admin::getPassword, Sha256Util.encode(resetPwdDTO.getNewPwd()));
        uw.eq(Admin::getAccount, resetPwdDTO.getPhone());
        uw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
        if (!update(uw)) {
            throw new MyException(MallResponseError.UPDATE_ERROR);
        }
    }

    @Override
    public boolean checkAdminExist(String phone) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getAccount, phone);
        qw.ne(Admin::getStatus, AdminStatusEnum.DELETE.getStatus());
        return getOne(qw) != null;
    }

    @Override
    public void resetLoginPwd(String account) {
        LambdaUpdateWrapper<Admin> uw = new LambdaUpdateWrapper<>();
        uw.set(Admin::getPassword, Sha256Util.encode(MALLGlobalConfig.INIT_PASSWORD));
        uw.eq(Admin::getAccount, account);
        uw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
        if (!update(uw)) throw new MyException(MallResponseError.UPDATE_ERROR);
    }

    @Override
    public boolean getPlatformAdminIsExist(Integer type) {
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getType, type);
        qw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
        return getOne(qw) != null;
    }

    public void adminAuthCheck(String adminId, Integer type) {
        Integer adminType = getByAdminId(adminId).getType();
        if (!type.equals(adminType)) {
            throw new MyException(MallResponseError.NO_AUTH_ERROR);
        }
    }

    @Override
    public void adminAuthChecks(String adminId, Integer[] type) {
        Integer adminType = getByAdminId(adminId).getType();
        boolean res = false;
        for (Integer t : type) {
            res = t.equals(adminType);
            if (res) break;
        }
        if (!res) throw new MyException(MallResponseError.NO_AUTH_ERROR);
    }

    @Override
    public IPage<AdminVO> page(String uid, String account, Admin admin, Integer pageNum, Integer pageSize) {
        String loginAdminId = admin.getAdminId();
        String merchantId = admin.getMerchantId();
        return baseMapper.page(new Page<>(pageNum, pageSize), uid, account, loginAdminId, merchantId);
    }

    public String hidePwd(String pwd) {
        if (!StringUtils.isBlank(pwd)) {
            String sub = pwd.substring(0, 3);
            return sub + "***********";
        }
        return "";
    }

    public Admin queryByAccount(String account) {
        Integer status = AdminStatusEnum.DELETE.getStatus();

        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.lambda().eq(Admin::getAccount, account)
                .ne(Admin::getStatus, status);
        return getOne(qw);
    }

    @Override
    public void disable(String uid) {
        Integer status = AdminStatusEnum.DISABLE.getStatus();
        UpdateWrapper<Admin> uw = new UpdateWrapper<>();
        uw.lambda().set(Admin::getStatus, status)
                .eq(Admin::getAdminId, uid);
        update(uw);
    }

    @Override
    public void able(String uid) {
        Integer status = AdminStatusEnum.NORMAL.getStatus();
        UpdateWrapper<Admin> uw = new UpdateWrapper<>();
        uw.lambda().set(Admin::getStatus, status)
                .eq(Admin::getAdminId, uid);
        update(uw);
    }

    @Override
    public void resetAdminPwd(ResetAdminPwdDTO dto) {
        UpdateWrapper<Admin> uw = new UpdateWrapper<>();
        uw.lambda().set(Admin::getPassword, Sha256Util.encode(dto.getNewPwd1()))
                .eq(Admin::getAdminId, dto.getAdminId());
        update(uw);
    }

    @Override
    public void repairAdminRole(RepairAdminRoleDTO dto) {
        UpdateWrapper<Admin> uw = new UpdateWrapper<>();
        uw.lambda().set(Admin::getRoleId, dto.getRoleId())
                .eq(Admin::getAdminId, dto.getAdminId());
        update(uw);
    }

    @Override
    public void delete(String uid) {
        Integer status = AdminStatusEnum.DELETE.getStatus();
        UpdateWrapper<Admin> uw = new UpdateWrapper<>();
        uw.lambda().set(Admin::getStatus, status)
                .eq(Admin::getAdminId, uid);
        update(uw);
    }

    @Override
    public void offLineByRoleId(String roleId) {
        Integer status = AdminStatusEnum.NORMAL.getStatus();
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.lambda().eq(Admin::getRoleId, roleId)
                .eq(Admin::getStatus, status);
        List<Admin> admins = list(qw);
        admins.forEach(v -> redis.del(v.getAdminId() + MALLGlobalConfig.MALL_TOKEN_REDIS_KEY_SUFFIX));
    }

    @Override
    public MerchantStatistics merchantStatistics(String merchantId) {
        MerchantStatistics statistics = new MerchantStatistics();

        //累计商品数
        LambdaQueryWrapper<Spu> qwSpu = new LambdaQueryWrapper<>();
        int spuNum = spuService.count(qwSpu.in(Spu::getStatus, 1, 2, 7).eq(Spu::getMerchantId, merchantId));
        statistics.setSpuNum(spuNum);

        //累计订单数
        LambdaQueryWrapper<Order> qwOrder = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OrderDetail> qwOrderDetail = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OrderDetail> qwOrderDetail2 = new LambdaQueryWrapper<>();
        List<Order> orderList = orderService.list(qwOrder.eq(Order::getMerchantId, merchantId));
        statistics.setOrderNum(orderList.size());

        //累计销量
        List<String> oids = orderList.stream().map(Order::getOid).collect(Collectors.toList());
        Integer salesNum = 0;
        if (oids.size() != 0) {
            List<OrderDetail> details = orderDetailService.list(qwOrderDetail.in(OrderDetail::getOid, oids));
            salesNum = details.stream().map(OrderDetail::getNumber).reduce(0, Integer::sum);
        }
        statistics.setSalesNum(salesNum);

        //昨日新增销量
        List<Order> orders = orderService.list(qwOrder
                .ge(Order::getCreateTime, DateUtil.getYesterdayStartTime())
                .le(Order::getCreateTime, DateUtil.getYesterdayEndTime()));
        List<String> oidsToday = orders.stream().map(Order::getOid).collect(Collectors.toList());
        Integer yesterdayNewAddSalesNum = 0;
        if (oidsToday.size() != 0) {
            List<OrderDetail> detailsToday = orderDetailService.list(qwOrderDetail2.in(OrderDetail::getOid, oidsToday));
            yesterdayNewAddSalesNum = detailsToday.stream().map(OrderDetail::getNumber).reduce(0, Integer::sum);
        }
        statistics.setYesterdayNewAddSalesNum(yesterdayNewAddSalesNum);

        LambdaQueryWrapper<Order> qwOrder2 = new LambdaQueryWrapper<>();
        qwOrder2.ge(Order::getCreateTime, DateUtil.getTodayStartTime());
        qwOrder2.le(Order::getCreateTime, DateUtil.getTodayEndTime());
        List<Order> todayOrder = orderService.list(qwOrder2);
        //今日订单数
        statistics.setTodayOrderNum(todayOrder.size());
        //今日待付款订单
        int todayWaitPayOrderNum = orderService.count(qwOrder2.eq(Order::getOrderState, 7));
        statistics.setTodayWaitPayOrderNum(todayWaitPayOrderNum);

        //今日成交额
        LambdaQueryWrapper<Order> qwOrder3 = new LambdaQueryWrapper<>();
        qwOrder3.ge(Order::getCreateTime, DateUtil.getTodayStartTime());
        qwOrder3.le(Order::getCreateTime, DateUtil.getTodayEndTime());
        qwOrder3.in(Order::getOrderState, 1, 4, 8, 9);
        BigDecimal todayTurnover = todayOrder.stream().map(Order::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
        statistics.setTodayTurnover(todayTurnover);

        //店铺收藏数
        LambdaQueryWrapper<UserFollow> qwFollow = new LambdaQueryWrapper<>();
        int storeCollections = userFollowService.count(qwFollow.eq(UserFollow::getStatus, 1));
        statistics.setStoreCollections(storeCollections);

        //今日浏览量
        LambdaQueryWrapper<UserFoot> qwFoot = new LambdaQueryWrapper<>();
        List<UserFoot> foots = userFootService.list(qwFoot.eq(UserFoot::getIsDelete, 0)
                .ge(UserFoot::getCreateTime, DateUtil.getTodayStartTime())
                .le(UserFoot::getCreateTime, DateUtil.getTodayEndTime()));
        List<String> goodsIds = foots.stream().map(UserFoot::getGoodsId).collect(Collectors.toList());
        long todayViews = goodsIds.stream().filter(i -> {
            Spu spu = spuService.getByGoodsId(i);
            if (spu == null)
                return false;
            return spu.getMerchantId().equals(merchantId);

        }).count();
        statistics.setTodayViews((int) todayViews);

        //销量top10
        statistics.setSaleTop10(countService.salesTopTen(merchantId));

        //销售额
        //订单量
        Map<String, String> salesVolume = new HashMap<>();
        Map<String, String> orderNumMonth = new HashMap<>();

        JSONArray jsonArrayX = new JSONArray();
        JSONArray jsonArrayYSalesVolume = new JSONArray();
        JSONArray jsonArrayYOrderNumMonth = new JSONArray();

        for (int i = 1; i <= 12; i++) {
            LambdaQueryWrapper<Order> qwOrder4 = new LambdaQueryWrapper<>();

            List<Order> orders12 = orderService.list(qwOrder4
                    .in(Order::getOrderState, 1, 4, 8, 9)
                    .ge(Order::getCreateTime, DateUtil.getMonthStartTime(i))
                    .le(Order::getCreateTime, DateUtil.getMonthEndTime(i)));
            if (orders12.size() == 0) {
                jsonArrayYSalesVolume.add(0);
                jsonArrayYOrderNumMonth.add(0);
            } else {
                jsonArrayYSalesVolume.add(orders12.stream().map(Order::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
                jsonArrayYOrderNumMonth.add(orders12.size());
            }
            jsonArrayX.add(i);
        }

        salesVolume.put("x", JSON.toJSONString(jsonArrayX));
        salesVolume.put("y", JSON.toJSONString(jsonArrayYSalesVolume));

        orderNumMonth.put("x", JSON.toJSONString(jsonArrayX));
        orderNumMonth.put("y", JSON.toJSONString(jsonArrayYOrderNumMonth));

        statistics.setSalesVolume(salesVolume);
        statistics.setOrderNumMonth(orderNumMonth);

        return statistics;
    }

    @Override
    public PlatformStatistics platformStatistics() {
        PlatformStatistics statistics = new PlatformStatistics();

        //累计用户数
        LambdaQueryWrapper<User> qwUser = new LambdaQueryWrapper<>();
        int userNum = userService.count();
        statistics.setUserNum(userNum);

        //昨日新增用户数
        int yesterdayNewAddUserNum = userService.count(qwUser
                .ge(User::getCreateTime, DateUtil.getYesterdayStartTime())
                .le(User::getCreateTime, DateUtil.getYesterdayEndTime()));
        statistics.setYesterdayNewAddUserNum(yesterdayNewAddUserNum);

        //累计商户数
        LambdaQueryWrapper<Merchant> qwMerchant = new LambdaQueryWrapper<>();
        int merchantNum = merchantService.count(qwMerchant
                .in(Merchant::getStatus, 0, 1)
                .eq(Merchant::getDel, 0));
        statistics.setMerchantNum(merchantNum);

        //昨日新增商户数
        int yesterdayNewAddMerchantNum = merchantService.count(qwMerchant
                .ge(Merchant::getCreateTime, DateUtil.getYesterdayStartTime())
                .le(Merchant::getCreateTime, DateUtil.getYesterdayEndTime()));
        statistics.setYesterdayNewAddMerchantNum(yesterdayNewAddMerchantNum);

        //累计商品数
        LambdaQueryWrapper<Spu> qwSpu = new LambdaQueryWrapper<>();
        int spuNum = spuService.count(qwSpu.in(Spu::getStatus, 1, 2, 7));
        statistics.setSpuNum(spuNum);

        //昨日新增商户数
        int yesterdayNewAddSpuNum = spuService.count(qwSpu
                .ge(Spu::getCreateTime, DateUtil.getYesterdayStartTime())
                .le(Spu::getCreateTime, DateUtil.getYesterdayEndTime()));
        statistics.setYesterdayNewAddSpuNum(yesterdayNewAddSpuNum);

        //累计订单数
        LambdaQueryWrapper<Order> qwOrder = new LambdaQueryWrapper<>();
        int orderNum = orderService.count();
        statistics.setOrderNum(orderNum);

        //昨日新增订单数
        int yesterdayNewAddOrderNum = orderService.count(qwOrder
                .ge(Order::getCreateTime, DateUtil.getYesterdayStartTime())
                .le(Order::getCreateTime, DateUtil.getYesterdayEndTime()));
        statistics.setYesterdayNewAddOrderNum(yesterdayNewAddOrderNum);

        //累计GMV
        List<Order> orderList = orderService.list();
        BigDecimal gmv = BigDecimal.ZERO;
        for (Order order : orderList) {
            switch (order.getOrderState()) {
                case 1:
                case 4:
                case 8:
                case 9:
                    gmv = gmv.add(order.getTotal());
                    break;
                case 2:
                case 3:
                case 5:
                case 6:
                case 7:
                    break;
            }
        }
        statistics.setGmv(gmv);

        //昨日新增GMV 1625191293348
        List<Order> orderListYesterday = orderService.list(qwOrder);
        BigDecimal yesterdayNewAddGmv = BigDecimal.ZERO;
        for (Order order : orderListYesterday) {
            switch (order.getOrderState()) {
                case 1:
                case 4:
                case 8:
                case 9:
                    yesterdayNewAddGmv = yesterdayNewAddGmv.add(order.getTotal());
                    break;
                case 2:
                case 3:
                case 5:
                case 6:
                case 7:
                    break;
            }
        }
        statistics.setYesterdayNewAddGmv(yesterdayNewAddGmv);

        //销量趋势、销量统计 salesStatistics
        Map<String, String> salesTrend = new HashMap<>();
        Map<String, String> salesStatistics = new HashMap<>();

        JSONArray jsonArrayX = new JSONArray();
        JSONArray jsonArrayYTrend = new JSONArray();
        JSONArray jsonArrayYStatistics = new JSONArray();

        for (int i = 1; i <= 12; i++) {
            LambdaQueryWrapper<Order> qwOrder2 = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<OrderDetail> qwOrderDetail2 = new LambdaQueryWrapper<>();
            JSONObject jsonObject = new JSONObject();

            List<Order> orders = orderService.list(qwOrder2
                    .in(Order::getOrderState, 1, 4, 8, 9)
                    .ge(Order::getCreateTime, DateUtil.getMonthStartTime(i))
                    .le(Order::getCreateTime, DateUtil.getMonthEndTime(i)));
            List<String> oids = orders
                    .stream()
                    .map(Order::getOid)
                    .collect(Collectors.toList());
            if (orders.size() == 0) {
                jsonObject.put("totalNum", 0);
                jsonObject.put("totalSales", BigDecimal.ZERO);
                jsonArrayYTrend.add(jsonObject);
                jsonArrayYStatistics.add(0);
            } else {
                List<OrderDetail> details = orderDetailService.list(qwOrderDetail2
                        .in(OrderDetail::getOid, oids));

                Integer reduce = details.stream().map(OrderDetail::getNumber).reduce(0, Integer::sum);

                jsonObject.put("totalNum", reduce);
                jsonObject.put("totalSales", orders.stream().map(Order::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
                jsonArrayYTrend.add(jsonObject);
                jsonArrayYStatistics.add(reduce);
            }
            jsonArrayX.add(i);
        }

        salesTrend.put("x", JSON.toJSONString(jsonArrayX));
        salesTrend.put("y", JSON.toJSONString(jsonArrayYTrend));

        salesStatistics.put("x", JSON.toJSONString(jsonArrayX));
        salesStatistics.put("y", JSON.toJSONString(jsonArrayYStatistics));

        statistics.setSalesTrend(salesTrend);
        statistics.setSalesStatistics(salesStatistics);

        return statistics;
    }

    @Override
    public PersonInfoVO getMerchantInfo(String adminId) {
        Admin admin = getByAdminId(adminId);
        String roleName = adminRoleService.getByRoleId(admin.getRoleId()).getRoleName();

        PersonInfoVO vo = new PersonInfoVO();
        vo.setAccount(admin.getAccount());
        vo.setHeadImg(admin.getHeadImg());
        vo.setRole(roleName);

        Merchant merchant = merchantService.getByMerchantId(admin.getMerchantId());
        if (merchant != null) {
            vo.setApplyName(merchant.getApplyName());
            String idCard = merchant.getIdCard();
            if (!StringUtils.isBlank(idCard)) {
                String sub1 = idCard.substring(0, 3);
                String sub2 = idCard.substring(idCard.length() - 3);
                idCard = sub1 + "***" + sub2;
                vo.setIdCard(idCard);
            }
            vo.setApplyPhone(merchant.getApplyPhone());
            vo.setPostAddress(merchant.getPostAddress());
            vo.setType(merchant.getType());
            vo.setEnterpriseName(merchant.getEnterpriseName());
            vo.setCreditCode(merchant.getCreditCode());
            vo.setBusinessLicense(merchant.getBusinessLicense());
        }
        return vo;
    }

    @Override
    public void repairHeadImg(String adminId, String headImg) {
        LambdaUpdateWrapper<Admin> uw = new LambdaUpdateWrapper<>();
        uw.set(Admin::getHeadImg, headImg);
        uw.ne(Admin::getStatus, 0);
        uw.eq(Admin::getAdminId, adminId);
        update(uw);
    }

    @Override
    public void SetPwd(SetPwdDTO dto) {
        log.info("设置密码：" + dto);
//        LambdaUpdateWrapper<Admin> uw = new LambdaUpdateWrapper<>();
//        uw.set(Admin::getPassword, Sha256Util.encode(dto.getPwd()));
//        uw.eq(Admin::getAccount, dto.getPhone());
//        uw.eq(Admin::getStatus, AdminStatusEnum.NORMAL.getStatus());
//        update(uw);

        Admin admin = queryByAccount(dto.getPhone());
        admin.setPassword(Sha256Util.encode(dto.getPwd()));
        updateById(admin);

        log.info("设置密码：" + admin);

//        baseMapper.setPwd(Sha256Util.encode(dto.getPwd()), dto.getPhone(), AdminStatusEnum.NORMAL.getStatus());
        log.info("设置密码：" + queryByAccount(dto.getPhone()));

    }
}


