package com.gree.mall.manager.logic.coupon;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.activity.CustomSecSpecBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.coupon.*;
import com.gree.mall.manager.commonmapper.CouponDateMapper;
import com.gree.mall.manager.commonmapper.SecKillMapper;
import com.gree.mall.manager.commonmapper.WxCustomerMapper;
import com.gree.mall.manager.enums.*;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CouponLogic {

    @Resource
    CouponService couponService;
    @Resource
    CouponGoodsService couponGoodsService;
    @Resource
    CouponDateMapper couponDateMapper;
    @Resource
    UserCouponService userCouponService;
    @Resource
    CouponTagService couponTagService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private WxCustomerMapper wxCustomerMapper;
    @Autowired
    private SecKillMapper secKillMapper;
    @Autowired
    private CommonLogic commonLogic;

    @Autowired
    CouponCompanyService couponCompanyService;

    @Autowired
    CouponWebsitService couponWebsitService;

    @Autowired
    AdminCompanyService adminCompanyService;

    @Autowired
    AdminWebsitService adminWebsitService;

    /**
     * 优惠券列表
     */
    public IPage<CouponPageBean> page(String couponName, String couponType, String flag, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();
        List<String> adminWebsitIds = adminUser.getAdminWebsitIds();

        return couponDateMapper.pageCoupon(new Page<>(pageNum, pageSize), companyWechatIds, couponName, couponType, flag,
                (adminUser.getType().equals(2) || adminUser.getType().equals(4))?adminWebsitIds:null);
    }


    public void export(HttpServletRequest request, HttpServletResponse response, String couponName, String couponType, String flag) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();

        List<CouponExportBean> couponExportBeans = couponDateMapper.exportCoupon(companyWechatIds, couponName, couponType, flag);
        //List<CouponExportBean> couponSelfBeans =  couponDateMapper.exportSelfCoupon(companyWechatIds, couponName, couponType, flag);
//        if(CollectionUtils.isNotEmpty(couponSelfBeans)){
//            couponExportBeans.addAll(couponSelfBeans);
//        }

        String[] titles = {"优惠券名称","发放数量","领取数量","使用数量","优惠券金额", "领取来源-网点名称", "领取来源-业务员昵称", "领取来源-业务员电话", "优惠券状态", "领券客户昵称", "领券客户电话",
                "用券时间", "订单号", "订单实付金额"};
        ExcelData excelData = new ExcelData();
        List<List<Object>> rows = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (CouponExportBean couponExportBean : couponExportBeans) {
            List<Object> row = new ArrayList<>();
            row.add(couponExportBean.getCouponName());
            row.add(couponExportBean.getCouponAmount());
            row.add(couponExportBean.getReceiveAmount());
            row.add(couponExportBean.getUsedAmount());
            row.add(couponExportBean.getCouponValue());
            row.add(couponExportBean.getWebsitName());
            row.add(couponExportBean.getWorkName());
            row.add(couponExportBean.getWorkPhone());
            row.add(couponExportBean.getStatus() ? "已使用" : "未使用");
            row.add(couponExportBean.getNickName());
            row.add(couponExportBean.getMobile());
            row.add(couponExportBean.getUsedTime() == null ? "" : simpleDateFormat.format(couponExportBean.getUsedTime()));
            row.add(couponExportBean.getOrderId());
            row.add(couponExportBean.getPayAmount() == null ? "" : couponExportBean.getPayAmount().toString());
            rows.add(row);
        }
        String fileName = String.format("优惠券导出_%s.xlsx", simpleDateFormat.format(new Date()));
        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("优惠券");
        excelData.setRows(rows);
        ExcelUtils.exportExcel(request, response, fileName, excelData, -1, null);
    }

    /**
     * 券详情
     *
     * @param couponId
     * @return
     */
    public CouponDetailBean detail(String couponId) {
        Coupon coupon = couponService.getById(couponId);
        CouponDetailBean couponBean = new CouponDetailBean();
        BeanUtils.copyProperties(coupon, couponBean);
        couponBean.setGoodsList(couponGoodsService.lambdaQuery().eq(CouponGoods::getCouponId, couponId).list());
        couponBean.setTagList(couponDateMapper.couponTagDetail(couponId));
        couponBean.setUserList(couponDateMapper.couponTagUser(couponId));
        couponBean.setCouponCompanyList(couponCompanyService.lambdaQuery().eq(CouponCompany::getCouponId, couponId).list());
        couponBean.setCouponWebsitList(couponWebsitService.lambdaQuery().eq(CouponWebsit::getCouponId, couponId).list());
        return couponBean;
    }

    /**
     * 新增券
     *
     * @param couponBean
     */
//    @Async
    @Transactional(rollbackFor = Exception.class)
    public void add(HttpServletRequest request,CouponBean couponBean) throws RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        if (CollectionUtils.isEmpty(couponBean.getCouponCompanyList()))
            throw new RemoteServiceException("请选择使用商户");

 /*       if (couponBean.getActiveType() == 1) {
            if (Objects.isNull(couponBean.getActiveStartTime()) || Objects.isNull(couponBean.getActiveEndTime())) {
                throw new RemoteServiceException("使用时间区间不能为空！");
            }
            if (couponBean.getActiveEndTime().compareTo(couponBean.getActiveStartTime()) < 0) {
                throw new RemoteServiceException("使用结束时间不能少于开始时间！");
            }
        }*/
        couponBean.setFlag(CouponFlagEnum.WAIT.toString());
        couponBean.setLeftAmount(couponBean.getCouponAmount());
        couponBean.setCreateTime(new Date());
        couponBean.setActiveType(2);
        couponBean.setCompanyName(adminUser.getCompanyName());
        couponBean.setCompanyId(adminUser.getCompanyId());

        if (!CollectionUtils.isEmpty(couponBean.getCouponWebsitList()))
            couponBean.setBuyType("WEBSIT");

        couponService.save(couponBean);
        String couponId = couponBean.getCouponId();


        for (CouponCompany couponCompany : couponBean.getCouponCompanyList()) {
            AdminCompany adminCompany = adminCompanyService.getById(couponCompany.getCompanyId());
            couponCompany.setCouponId(couponId);
            couponCompany.setCompanyName(adminCompany.getAdminCompanyName());
        }

        couponCompanyService.saveBatch(couponBean.getCouponCompanyList());

        if (!CollectionUtils.isEmpty(couponBean.getCouponWebsitList())){
            for (CouponWebsit couponWebsit : couponBean.getCouponWebsitList()) {
                AdminWebsit adminWebsit = adminWebsitService.getById(couponWebsit.getWebsitId());
                couponWebsit.setCouponId(couponId);
                couponWebsit.setWebsitName(adminWebsit.getName());
            }
            couponWebsitService.saveBatch(couponBean.getCouponWebsitList());
        }


        if (couponBean.getCouponType().trim().equals(CouponTypeEnum.GOODS.getKey()) && couponBean.getGoodsList() != null) {
            List<CouponGoods> couponGoodsList = new ArrayList<>();
            for (CouponGoods couponGoods : couponBean.getGoodsList()) {
                couponGoods.setCouponId(couponId);
                couponGoods.setCreateTime(new Date());
                couponGoods.setCompanyId(adminUser.getCompanyId());
                couponGoods.setCompanyName(adminUser.getCompanyName());
                couponGoodsList.add(couponGoods);
            }
            couponGoodsService.saveBatch(couponGoodsList);
        }


        //所有会员
        if (couponBean.getReceiveCrowd().equals(Convert.toInt(CouponCrowdEnum.ALL.getKey())) && couponBean.getUserList() != null) {
            List<CouponUser> couponUserList = new ArrayList<>();
            List<User> userList = userService.lambdaQuery()
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponCompanyList()),User::getCompanyId, couponBean.getCouponCompanyList().stream().map(CouponCompany::getCompanyId).collect(Collectors.toList()))
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponWebsitList()),User::getWebsitId, couponBean.getCouponWebsitList().stream().map(CouponWebsit::getWebsitId).collect(Collectors.toList()))
                    .list();
            for (User user : userList) {
                CouponUser couponUser = new CouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(user.getUserId());
                couponUser.setUserName(user.getNickName());
                couponUser.setCreateTime(new Date());
                couponUserList.add(couponUser);
            }
            if (couponUserList.size() > 0) {
                couponUserService.saveBatch(couponUserList);
            }

        }

        //指定会员
        if (couponBean.getReceiveCrowd().equals(Convert.toInt(CouponCrowdEnum.SPECIFY.getKey())) && couponBean.getUserList() != null) {
            List<CouponUser> couponUserList = new ArrayList<>();
//            List<UserCoupon> userCouponList = new ArrayList<>();
            for (CouponUserTypeBean couponUserTypeBean : couponBean.getUserList()) {
                CouponUser couponUser = new CouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(couponUserTypeBean.getUserId());
                couponUser.setUserName(couponUserTypeBean.getUserName());
                couponUser.setCreateTime(new Date());
                couponUser.setCompanyName("");
                couponUser.setCompanyId("");
                couponUserList.add(couponUser);
//                if (couponUserTypeBean.getType().equals(UserTypeEnum.SERVICE.toString())) {
//                    userCouponList.add(assignCoupon(adminUser, couponBean, couponUserTypeBean.getUserId()));
//                }

            }

            if (couponUserList.size() > 0) {
                couponUserService.saveBatch(couponUserList);
            }

//            if (userCouponList.size() > 0) {
//                userCouponService.saveBatch(userCouponList);
//            }

        }
        //全部业务员
        if (couponBean.getReceiveCrowd().equals(Convert.toInt(CouponCrowdEnum.ALL_SERVICE.getKey()))) {
            List<UserCoupon> userCouponList = new ArrayList<>();
            List<User> userList = userService.lambdaQuery()
                    .eq(User::getType, UserTypeEnum.SERVICE.toString())
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponCompanyList()),User::getCompanyId, couponBean.getCouponCompanyList().stream().map(CouponCompany::getCompanyId).collect(Collectors.toList()))
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponWebsitList()),User::getWebsitId, couponBean.getCouponWebsitList().stream().map(CouponWebsit::getWebsitId).collect(Collectors.toList()))
                    .list();
            List<CouponUser> couponUserList = new ArrayList<>();
            for (User user : userList) {
                userCouponList.add(assignCoupon(adminUser, couponBean, user.getUserId()));
                CouponUser couponUser = new CouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(user.getUserId());
                couponUser.setUserName(user.getNickName());
                couponUser.setCreateTime(new Date());
                couponUserList.add(couponUser);
            }
            if (couponUserList.size() > 0) {
                couponUserService.saveBatch(couponUserList);
            }
        }
        //全部普通用户
        if (couponBean.getReceiveCrowd().equals(Convert.toInt(CouponCrowdEnum.ALL_GENRERAL.getKey()))) {
            List<CouponUser> couponUserList = new ArrayList<>();
            List<User> userList = userService.lambdaQuery()
                    .eq(User::getType, UserTypeEnum.GENERAL.toString())
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponCompanyList()),User::getCompanyId, couponBean.getCouponCompanyList().stream().map(CouponCompany::getCompanyId).collect(Collectors.toList()))
                    .in(CollectionUtils.isNotEmpty(couponBean.getCouponWebsitList()),User::getWebsitId, couponBean.getCouponWebsitList().stream().map(CouponWebsit::getWebsitId).collect(Collectors.toList()))
                    .list();
            for (User user : userList) {
                CouponUser couponUser = new CouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(user.getUserId());
                couponUser.setUserName(user.getNickName());
                couponUser.setCreateTime(new Date());
                couponUserList.add(couponUser);
            }
            if (couponUserList.size() > 0) {
                couponUserService.saveBatch(couponUserList);
            }
        }


        couponService.lambdaUpdate()
                .eq(Coupon::getFlag, CouponFlagEnum.WAIT.toString())
                .le(Coupon::getObtainStartTime, new Date())
                .set(Coupon::getFlag, CouponFlagEnum.START.toString())
                .update();


    }


    private UserCoupon assignCoupon(AdminUserCom adminUserCom,CouponBean couponBean, String userId) {
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setCouponId(couponBean.getCouponId());
        userCoupon.setUserId(userId);
        userCoupon.setReceiveTime(new Date());
        userCoupon.setCouponName(couponBean.getCouponName());
        userCoupon.setCouponType(couponBean.getCouponType());
        userCoupon.setOrderAmount(couponBean.getOrderAmount());
        userCoupon.setCouponValue(couponBean.getCouponValue());
        userCoupon.setStatus(false);
        //userCoupon.setTransferType(true);
        userCoupon.setLeftShareTimes(couponBean.getShareTimes());
        if (couponBean.getActiveDay() == null) {
            couponBean.setActiveDay(0);
        }
        if (couponBean.getActiveType() == CouponActiveTypeEnum.COMMON.getActiveType()) {
            userCoupon.setActiveStartTime(couponBean.getActiveStartTime());
            userCoupon.setActiveEndTime(couponBean.getActiveEndTime());
        }
        //当日起多少天
        if (couponBean.getActiveType() == CouponActiveTypeEnum.TODAY.getActiveType()) {
            userCoupon.setActiveStartTime(DateUtils.getStartTime());
            userCoupon.setActiveEndTime(DateUtils.getStartTimeByDay(couponBean.getActiveDay()));
        }
        //次日起多少天
        if (couponBean.getActiveType() == CouponActiveTypeEnum.NEXTDAY.getActiveType()) {
            userCoupon.setActiveStartTime(DateUtils.getStartTimeByDay(1));
            userCoupon.setActiveEndTime(DateUtils.getStartTimeByDay(couponBean.getActiveDay() + 1));
        }
        userCoupon.setState(new Date().before(couponBean.getActiveEndTime()) && new Date().after(couponBean.getActiveStartTime()));
        return userCoupon;
    }

    public void reissueCoupon(HttpServletRequest request, ReissueCouponBean reissueCouponBean) throws RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Coupon coupon = couponService.getById(reissueCouponBean.getCouponId());
        if (coupon == null) {
            throw new RemoteServiceException("优惠券不存在");
        }
        if (coupon.getTransferType() != null && !coupon.getTransferType()) {
            throw new RemoteServiceException("优惠券不可以补发");
        }
        if (coupon.getObtainEndTime().compareTo(new Date()) <= 0) {
            throw new RemoteServiceException("优惠券超过领取时间");
        }
        List<CouponUserTypeBean> userIds = reissueCouponBean.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            userIds = couponDateMapper.reissueCouponUser(null,coupon.getCouponId());
        }
        List<CouponUser> couponUserList = new ArrayList<>();
        List<UserCoupon> userCouponList = new ArrayList<>();
        for (CouponUserTypeBean couponUserTypeBean : userIds) {
            CouponUser couponUser = new CouponUser();
            couponUser.setCouponId(coupon.getCouponId());
            couponUser.setUserId(couponUserTypeBean.getUserId());
            couponUser.setUserName(couponUserTypeBean.getUserName());
            couponUser.setCreateTime(new Date());
            couponUserList.add(couponUser);
            CouponBean couponBean = new CouponBean();
            BeanUtils.copyProperties(coupon, couponBean);
            userCouponList.add(assignCoupon(adminUser, couponBean, couponUserTypeBean.getUserId()));
        }

        if (couponUserList.size() > 0) {
            couponUserService.saveBatch(couponUserList);
        }

        if (userCouponList.size() > 0) {
            userCouponService.saveBatch(userCouponList);
        }

    }


    /**
     * 修改券
     *
     * @param couponBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(HttpServletRequest request, CouponBean couponBean) throws RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Coupon coupon = couponService.getById(couponBean.getCouponId());
        couponBean.setCreateTime(null);

        couponCompanyService.lambdaUpdate().eq(CouponCompany::getCouponId,coupon.getCouponId()).remove();
        for (CouponCompany couponCompany : couponBean.getCouponCompanyList()) {
            AdminCompany adminCompany = adminCompanyService.getById(couponCompany.getCompanyId());
            couponCompany.setCouponId(coupon.getCouponId());
            couponCompany.setCompanyName(adminCompany.getAdminCompanyName());
        }

        couponCompanyService.saveBatch(couponBean.getCouponCompanyList());

        couponWebsitService.lambdaUpdate().eq(CouponWebsit::getCouponId,coupon.getCouponId()).remove();
        if (!CollectionUtils.isEmpty(couponBean.getCouponWebsitList())){
            for (CouponWebsit couponWebsit : couponBean.getCouponWebsitList()) {
                AdminWebsit adminWebsit = adminWebsitService.getById(couponWebsit.getWebsitId());
                couponWebsit.setCouponId(coupon.getCouponId());
                couponWebsit.setWebsitName(adminWebsit.getName());
            }
            couponWebsitService.saveBatch(couponBean.getCouponWebsitList());
        }



        Date now = new Date();
        if (coupon.getFlag().trim().equals(CouponFlagEnum.WAIT.toString())) {
            //待发布处理
            couponService.updateById(couponBean);
            //清除商品
            if (couponBean.getGoodsList() != null && couponBean.getGoodsList().size() > 0) {
                couponGoodsService.lambdaUpdate()
                        .eq(CouponGoods::getCouponId, couponBean.getCouponId()).remove();
                for (CouponGoods couponGoods : couponBean.getGoodsList()) {
                    couponGoods.setCouponId(couponBean.getCouponId());
                    couponGoods.setCreateTime(now);
                    couponGoodsService.save(couponGoods);
                }
            }
            //清除会员
            if (couponBean.getTagList() != null && couponBean.getTagList().size() > 0) {
                couponTagService.lambdaUpdate()
                        .eq(CouponTag::getCouponId, couponBean.getCouponId())
                        .remove();
                for (CouponTag couponTag : couponBean.getTagList()) {
                    couponTag.setCouponId(couponBean.getCouponId());
                    couponTag.setCreateTime(now);
                    couponTagService.save(couponTag);
                }
            }

            if (couponBean.getUserList() != null && couponBean.getUserList().size() > 0) {
                couponUserService.lambdaUpdate()
                        .eq(CouponUser::getCouponId, couponBean.getCouponId())
                        .remove();
                List<CouponUser> couponUserList = new ArrayList<>();
                for (CouponUserTypeBean couponUserTypeBean : couponBean.getUserList()) {
                    CouponUser couponUser = new CouponUser();
                    couponUser.setCouponId(couponBean.getCouponId());
                    couponUser.setUserId(couponUserTypeBean.getUserId());
                    couponUser.setUserName(couponUserTypeBean.getUserName());
                    couponUser.setCreateTime(new Date());
                    couponUserList.add(couponUser);
                    if (couponUserTypeBean.getType().equals(UserTypeEnum.SERVICE.toString())) {
                        UserCoupon userCoupon = userCouponService.lambdaQuery()
                                .eq(UserCoupon::getCouponId, couponBean.getCouponId())
                                .eq(UserCoupon::getUserId, couponUserTypeBean.getUserId())
                                //.eq(UserCoupon::getTransferType, true)
                                .one();
                        if (userCoupon == null) {
                            userCouponService.save(assignCoupon(adminUser, couponBean, couponUserTypeBean.getUserId()));
                        }

                    }
                }
                if (couponUserList.size() > 0) {
                    couponUserService.saveBatch(couponUserList);
                }
            }
        } else if (!coupon.getFlag().trim().equals(CouponFlagEnum.CANCEL.toString()) && coupon.getDisplayTime().before(now) && coupon.getObtainEndTime().after(now)) {
            //进行中处理
            if (coupon.getCouponAmount() > couponBean.getCouponAmount()) {
                throw new RemoteServiceException("修改优惠券发放总量时只能增加不能减少！");
            }
            couponService.lambdaUpdate()
                    .eq(Coupon::getCouponId, couponBean.getCouponId())
                    .set(StringUtils.isNotBlank(couponBean.getCouponName()), Coupon::getCouponName, couponBean.getCouponName())
                    .set(couponBean.getCouponAmount() > coupon.getCouponAmount(), Coupon::getCouponAmount, couponBean.getCouponAmount())
                    .set(!Objects.isNull(couponBean.getSortNum()), Coupon::getSortNum, couponBean.getSortNum())
                    .set(StringUtils.isNotBlank(couponBean.getNote()), Coupon::getNote, couponBean.getNote())
                    .set(StringUtils.isNotBlank(couponBean.getRemark()), Coupon::getRemark, couponBean.getRemark())
                    .update();
            //更改已领取的券名称
            if (StringUtils.isNotBlank(couponBean.getCouponName())) {
                userCouponService.lambdaUpdate()
                        .eq(UserCoupon::getCouponId, couponBean.getCouponId())
                        .set(UserCoupon::getCouponName, couponBean.getCouponName())
                        .update();
            }
        }
    }

    /**
     * 券标志
     *
     * @param couponId
     * @param startDate
     * @param endDate
     * @param flag
     */
    public void updateFlag(String couponId, String startDate, String endDate, String flag) throws RemoteServiceException {
        if (flag.trim().equals(CouponFlagEnum.START.toString())) {
            if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
                throw new RemoteServiceException("时间不能为空！");
            }
            if (endDate.compareTo(startDate) < 0) {
                throw new RemoteServiceException("结束时间不能少于开始时间！");
            }

            couponService.lambdaUpdate()
                    .eq(Coupon::getCouponId, couponId)
                    .set(Coupon::getReleaseStartTime, startDate)
                    .set(Coupon::getReleaseEndTime, endDate)
                    .set(Coupon::getFlag, CouponFlagEnum.START.toString())
                    .update();
        } else {
            couponService.lambdaUpdate()
                    .eq(Coupon::getCouponId, couponId)
                    .set(Coupon::getFlag, CouponFlagEnum.CANCEL.toString())
                    .update();

            userCouponService.lambdaUpdate()
                    .set(UserCoupon::getState, false)
                    .set(UserCoupon::getLeftShareTimes, 0)
                    .set(UserCoupon::getActiveEndTime, DateUtil.formatDate(DateUtil.date()) + " 00:00:00")
                    .eq(UserCoupon::getCouponId, couponId)
                    .eq(UserCoupon::getStatus, false)
                    .update();
        }
    }

    /**
     * 券数据
     *
     * @param couponId
     * @return
     */
    public CouponDataBean data(String couponId) {
        return couponDateMapper.data(couponId);
    }


    /**
     * 修改优惠券是否可以转让
     */
    public void updateUserCouponTransfer(List<String> userIds, Boolean transferType) {
        userCouponService.lambdaUpdate()
                .set(UserCoupon::getTransferType, transferType)
                .in(UserCoupon::getUserId, userIds)
                .update();
    }

    /**
     * 我的优惠券
     */
    public IPage<UserCoupon> userCouponList(String userId, Integer pageNo, Integer pageSize) {
        return userCouponService.lambdaQuery()
                .eq(UserCoupon::getUserId, userId)
                .orderByDesc(UserCoupon::getReceiveTime)
                .page(new Page<>(pageNo, pageSize));
    }

    /**
     * 领取优惠券明细
     * @param userCouponId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public IPage<UserCouponBean> receiveCouponDetail(String userCouponId,Integer pageNo,Integer pageSize){

        //UserCoupon uc = userCouponService.getById(userCouponId);

        IPage page = userCouponService.lambdaQuery()
                .eq(UserCoupon::getTransferor, userCouponId)
                .eq(UserCoupon::getTransferType, 0)
                .orderByDesc(UserCoupon::getReceiveTime)
                .page(new Page<>(pageNo, pageSize));

        List<UserCouponBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            UserCoupon userCoupon = (UserCoupon)o;
            UserCouponBean couponUser = new UserCouponBean();
            BeanUtils.copyProperties(userCoupon,couponUser);
            User user = userService.getById(userCoupon.getUserId());
            couponUser.setUserName(user.getNickName());
            couponUser.setMobile(user.getMobile());
            list.add(couponUser);
        }
        page.setRecords(list);
        return page;

    }

    public IPage<User> userList(HttpServletRequest request,
                                String tel, Date registerTime, String keyword, String type, Integer pageNo, Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();

        return userService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(companyWechatIds), User::getCompanyId, companyWechatIds)
                .eq(StringUtils.isNotEmpty(type), User::getType, type)
                .ge(registerTime != null, User::getCreateTime, registerTime)
                .like(StringUtils.isNotEmpty(tel), User::getMobile, tel.trim())
                .like(StringUtils.isNotEmpty(keyword), User::getNickName, keyword.trim())
                .orderByAsc(User::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
    }

    public IPage<CustomSecSpecBean> goodsSpecList(HttpServletRequest request, String categoryId, String keyword, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        return secKillMapper.querySpecListforCoupon(new Page<>(pageNum, pageSize), adminUser.getAdminCompanyIds(), categoryId, keyword);
    }




    /**
     * 订单取消,恢复优惠券
     */
    @Transactional
    public void refundCoupon(String userCouponId) {
        if(StringUtils.isEmpty(userCouponId)){
            return;
        }
        userCouponService.lambdaUpdate()
                .set(UserCoupon::getStatus, false)
                .set(UserCoupon::getUsedTime, null)
                .eq(UserCoupon::getId, userCouponId)
                .update();

        if (StringUtils.isEmpty(userCouponId)) {
            return;
        }
        log.info("订单取消,恢复用户优惠券id{}", userCouponId);
        UserCoupon userCoupon = userCouponService.getById(userCouponId);
        if(userCoupon.getTransferType() != null && userCoupon.getTransferType()){
            userCoupon.setLeftShareTimes(userCoupon.getLeftShareTimes() + 1);
            userCoupon.updateById();
        }
    }


    /**
     * 导入楼小贤优惠券
     */
    @Transactional
    public void importLxx(MultipartFile file) throws IOException, ParseException {
        List<Object> datas = ExcelUtils.importExcel(file);
        int i = 1;

        List<Coupon> couponList = new ArrayList<>();
        List<CouponUser> couponUserList = new ArrayList<>();
        List<UserCoupon> userCouponList = new ArrayList<>();
        for(Object o : datas){
            String companyWechatId = "1";
            String companyName = "嘉讯茂商城";
            i ++;
            List<Object> row = (List<Object>)o;
            String couponName = (String)row.get(0);
            String mobile = (String)row.get(1);
            BigDecimal amount = new BigDecimal(row.get(2).toString());
            Date startTime = DateUtils.parseDate(row.get(3).toString());
            Date endTime = DateUtils.parseDate(row.get(4).toString());
            if(StringUtils.isEmpty(couponName) || StringUtils.isEmpty(mobile) || amount == null || startTime == null || endTime == null){
                throw new RemoteServiceException("请检查第"+i+"行数据是否完整");
            }
            User user = userService.lambdaQuery().eq(User::getMobile, mobile).eq(User::getCompanyId,companyWechatId).one();
            if(user == null)
                throw new RemoteServiceException("手机号为"+mobile+"的找不到对应用户");

            //生成优惠券
            String couponId = "C"+ com.baomidou.mybatisplus.core.toolkit.IdWorker.getIdStr();
            Coupon coupon = new Coupon();
            coupon.setCouponId(couponId);
            coupon.setCouponName(couponName);
            coupon.setCouponType(CouponTypeEnum.SATISFY.toString());
            coupon.setActiveStartTime(startTime);
            coupon.setActiveEndTime(endTime);
            coupon.setReceiveCrowd(2);
            coupon.setCouponValue(amount);
            coupon.setObtainStartTime(startTime);
            coupon.setObtainEndTime(endTime);
            coupon.setDisplayTime(startTime);
            coupon.setFlag("WAIT");
            coupon.setRemark(mobile);
            coupon.setShareTimes(1);
            couponList.add(coupon);

            CouponUser couponUser = new CouponUser();
            couponUser.setCouponId(couponId);
            couponUser.setUserId(user.getUserId());
            couponUser.setUserName(user.getNickName());
            couponUser.setCreateTime(new Date());
            couponUser.setCompanyName(companyName);
            couponUserList.add(couponUser);

            //发到师傅手上的券
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserId(user.getUserId());
            userCoupon.setCouponId(couponId);
            userCoupon.setCouponName(couponName);
            userCoupon.setCouponValue(coupon.getCouponValue());
            userCoupon.setCouponType(coupon.getCouponType());
            userCoupon.setStatus(false);
            userCoupon.setState(true);
            userCoupon.setReceiveTime(new Date());
            userCoupon.setActiveStartTime(startTime);
            userCoupon.setActiveEndTime(endTime);
            userCoupon.setCompanyName(companyName);
            userCoupon.setTransferType(false);
            userCoupon.setLeftShareTimes(1);
            userCouponList.add(userCoupon);
        }
        //新增券
        couponService.saveBatch(couponList);
        //新增券和人对应关系
        couponUserService.saveBatch(couponUserList);
        //发券
        userCouponService.saveBatch(userCouponList);
    }

    public void cancel(String couponId) {
        userCouponService.lambdaUpdate()
                .eq(UserCoupon::getCouponId,couponId)
                .eq(UserCoupon::getStatus,false).remove();
    }

    public IPage<CouponVO> list(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //1.组装查询条件
        FieldUtils.supplyParam(zfireParam, CouponVO.class);

        IPage<CouponVO> couponVOIPage = couponDateMapper.couponList(page, zfireParam,adminUser.getAdminCompanyIds(),(adminUser.getType().equals(2) || adminUser.getType().equals(4))?adminUser.getAdminWebsitIds():null);
        return couponVOIPage;
    }
}
