package com.kiisoo.ic.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kiisoo.ic.activity.bean.ActivityInstanceVO;
import com.kiisoo.ic.activity.bean.PromotionSrcVO;
import com.kiisoo.ic.activity.entity.PmnActivityInstanceConfig;
import com.kiisoo.ic.activity.entity.PmnActivityStoreRelation;
import com.kiisoo.ic.activity.entity.PmnPromotionSrc;
import com.kiisoo.ic.activity.mapper.PmnPromotionSrcDOMapper;
import com.kiisoo.ic.activity.service.IPmnActivityInstanceConfigService;
import com.kiisoo.ic.activity.service.IPmnActivityInstanceService;
import com.kiisoo.ic.activity.service.IPmnActivityStoreRelationService;
import com.kiisoo.ic.activity.service.IPmnPromotionSrcService;
import com.kiisoo.ic.constants.Constants;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.entity.PoiStoreStaffVO;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.store.service.StoreEmployeeService;
import com.kiisoo.ic.system.bean.PrivilageUserBean;
import com.kiisoo.ic.system.entity.PrivilageAccountDO;
import com.kiisoo.ic.system.entity.PrivilageRoleDO;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.mapper.PrivilageRoleDOMapper;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import com.kiisoo.ic.system.service.PrivilageAccountService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动推广的对应场景 例如一个活动，不同地区 活动形式分量不同 服务实现类
 * </p>
 *
 * @author zheng
 * @since 2020-05-19
 */
@Service
public class PmnPromotionSrcServiceImpl extends ServiceImpl<PmnPromotionSrcDOMapper, PmnPromotionSrc> implements IPmnPromotionSrcService {

    @Autowired
    private StoreEmployeeService storeEmployeeService;
    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;
    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;
    @Autowired
    private IPmnActivityInstanceService pmnActivityInstanceService;
    @Autowired
    private PrivilageUserDOMapper privilageUserDOMapper;
    @Autowired
    private PrivilageAccountService privilageAccountService;
    @Autowired
    private PrivilageRoleDOMapper privilageRoleDOMapper;
    @Autowired
    private IPmnActivityInstanceConfigService pmnActivityInstanceConfigService;
    @Autowired
    private IPmnPromotionSrcService pmnPromotionSrcService;
    @Autowired
    private IPmnActivityStoreRelationService pmnActivityStoreRelationService;

    @Override
    @Transactional
    public List<PromotionSrcVO> listUserCodes(Long userId) throws Exception {
        PoiStoreStaff staff = poiStoreStaffDOMapper.selectOne(Wrappers.<PoiStoreStaff>lambdaQuery().eq(PoiStoreStaff::getUserId, userId));
        List<PromotionSrcVO> lists = new ArrayList<>();
        PrivilageUserDO privilageUserDO = privilageUserDOMapper.selectById(userId);
        // 用户不存在
        if (null == privilageUserDO) {
            return lists;
        }
        PrivilageAccountDO result = privilageAccountService.getAccountByUserId(userId);
        // 该账号已暂停，请联系店长
        if (null != result && result.getStatus().equals(2)) {
            return lists;
        }
        PrivilageRoleDO roleDO = privilageRoleDOMapper.selectRoleName(userId);
        Long type;
        if (roleDO.getCode().equals("DZ-DIANZHANG")) {
            type = 2L;
        } else if (roleDO.getCode().equals("DG-DAOGOU")) {
            type = 1L;
        } else {
            return lists;
        }
        if (type.equals(2L)) {
            userId = staff.getStoreId();
        }
        List<PmnPromotionSrc> srcs = list(Wrappers.<PmnPromotionSrc>lambdaQuery().eq(PmnPromotionSrc::getPromoterId, userId).eq(PmnPromotionSrc::getType, type).eq(PmnPromotionSrc::getStatus, 1));
        for (PmnPromotionSrc src : srcs) {
            File codeFile = new File("activity/" + src.getCode() + ".png");
            if (!codeFile.exists() || src.getQrCode() == null) {
                String cpUserId = "mayifei";
//                    String cpUserId = staff.getStaffCode();
                String url = "https://wework.qpic.cn/wwpic/789548_SW5hhAm-TgyEW0F_1590128879/0";
                if (cpUserId != "mayifei") {
                    url = storeEmployeeService.createActivityQrCode(cpUserId, staff.getStoreCode(), src.getType().intValue(), src.getInstanceId(), src.getPromoterId());
                }
                saveCodeFile(url, src.getCode());
                src.setQrCode(url);
                updateById(src);
            }
            PromotionSrcVO vo = new PromotionSrcVO();
            BeanUtils.copyProperties(src, vo);
            ActivityInstanceVO instance = pmnActivityInstanceService.getVO(src.getInstanceId());
            if(instance.getStatus() != 2) {
                continue;
            }
//            if (
//                    !((instance.getBeginTime().compareTo(new Date()) == -1 || instance.getBeginTime().compareTo(new Date()) == 0) &&
//                            instance.getEndTime().compareTo(new Date()) == 1
//                    )) {
//                continue;
//            }
            if(src.getExpiredTime().compareTo(new Date()) == -1) {
                continue;
            }
            vo.setInstanceVO(instance);
            vo.setQrCode("/activity/" + src.getCode() + ".png");
            if (type.equals(2L)) {
                QueryWrapper<PoiStoreStaff> wrapper = new QueryWrapper<>();
                //如果有店铺则查店铺
                wrapper.eq("store_id", staff.getStoreId());
                //状态有效
                wrapper.eq("status", 1);
                wrapper.ne("user_id", 0);
                wrapper.orderByDesc("id");
                wrapper.select("user_id");
                //返回店铺对应的导购
                List<PoiStoreStaff> poiStoreStaffs = poiStoreStaffDOMapper.selectList(wrapper);
                List<Long> userIds = poiStoreStaffs.stream().map(PoiStoreStaff::getUserId).collect(Collectors.toList());
                List<PmnPromotionSrc> staffSrcs = pmnPromotionSrcService.list(Wrappers.<PmnPromotionSrc>lambdaQuery().in(PmnPromotionSrc::getPromoterId, userIds).eq(PmnPromotionSrc::getType, 1).select(PmnPromotionSrc::getPromoterId).eq(PmnPromotionSrc::getInstanceId, src.getInstanceId()).eq(PmnPromotionSrc::getStatus, 1));
                List<Long> staffSrcUsers = staffSrcs.stream().map(PmnPromotionSrc::getPromoterId).collect(Collectors.toList());
                List<PoiStoreStaff> storeStaffs;
                if (staffSrcUsers.size() > 0) {
                    storeStaffs = poiStoreStaffDOMapper.selectList(Wrappers.<PoiStoreStaff>lambdaQuery().in(PoiStoreStaff::getUserId, staffSrcUsers));
                    List<PoiStoreStaffVO> staffVOs = new ArrayList<>();
                    for (PoiStoreStaff s : storeStaffs) {
                        PoiStoreStaffVO staffVO = new PoiStoreStaffVO();
                        BeanUtils.copyProperties(s, staffVO);
                        PrivilageUserBean privilageUserBean = privilageUserDOMapper.selectUserInfoAndRoleInfo(s.getUserId());
                        if(null != privilageUserBean){
                            staffVO.setName(privilageUserBean.getName());
                            staffVO.setMobil(privilageUserBean.getMobil());
                        }
                        staffVOs.add(staffVO);
                    }
                    vo.setStoreStaffs(staffVOs);
                }
            }
            lists.add(vo);
        }
        return lists;
    }

    @Override
    @Transactional
    public PmnPromotionSrc createCode(PoiStoreStaff staff, Long instanceId) {
        try {
            Long promoterId = staff.getUserId();
            if (staff.getType().equals(1L)) {
                promoterId = staff.getStoreId();
            }
            PmnPromotionSrc src = getOne(Wrappers.<PmnPromotionSrc>lambdaQuery().eq(PmnPromotionSrc::getPromoterId, promoterId).eq(PmnPromotionSrc::getType, staff.getType().equals(1L) ? 2 : 1).eq(PmnPromotionSrc::getInstanceId, instanceId));
            ActivityInstanceVO instanceVO = pmnActivityInstanceService.getVO(instanceId);
            PmnActivityInstanceConfig config = pmnActivityInstanceConfigService.getOne(Wrappers.<PmnActivityInstanceConfig>lambdaQuery().eq(PmnActivityInstanceConfig::getInstanceId, instanceId));
            String state = Constants.ACTIVITY_QR_CODE_PREFIX + Constants.LINE + instanceId + Constants.LINE + 3 + Constants.LINE + promoterId;
            PmnPromotionSrc saveSrc = new PmnPromotionSrc();
            if (src != null) {
                saveSrc.setId(src.getId());
            }
            saveSrc.setPromoterId(promoterId);
            saveSrc.setCaseId(config.getCaseId());
            saveSrc.setCode(new SimpleHash("MD5", state).toHex());
            saveSrc.setCreateTime(new Date());
            saveSrc.setExpiredTime(instanceVO.getEndTime());
            saveSrc.setInstanceId(instanceId);
            saveSrc.setIsAddition(2L); //是否要独立码:  1、默认 2、额外码
            saveSrc.setType(staff.getType().equals(1L) ? 2L : 1L); //要注意
            saveSrc.setUpdateTime(new Date());
            Long status = 1L;
            if(instanceVO.getStatus() == 3 || instanceVO.getStatus() == 4) {
                status = 2L;
            }
            saveSrc.setStatus(status);
//            String url = storeEmployeeService.createActivityQrCode(staff.getStaffCode(), staff.getStoreCode(), 3, instanceId, promoterId);

            String url = storeEmployeeService.createActivityQrCode("mayifei", staff.getStoreCode(), 3, instanceId, promoterId);
            if (url == null || url.length() <= 0) {
                url = "https://wework.qpic.cn/wwpic/789548_SW5hhAm-TgyEW0F_1590128879/0"; //测试用
            }
            saveSrc.setQrCode(url);
            pmnPromotionSrcService.saveCodeFile(url, new SimpleHash("MD5", state).toHex());
            boolean save = pmnPromotionSrcService.saveOrUpdate(saveSrc);
            return saveSrc;
        } catch (Exception e) {
            log.error("活动码创建失败", e);
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, Object> pageStoreCode(Long userId, Long instanceId, Integer pageNum, Integer pageSize) throws Exception {
        Map<String, Object> results = new HashMap<>();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(pageNum, pageSize);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<PmnActivityStoreRelation> storeRelations = pmnActivityStoreRelationService.page(page, Wrappers.<PmnActivityStoreRelation>lambdaQuery().eq(PmnActivityStoreRelation::getInstanceId, instanceId));
        if (CollectionUtils.isEmpty(storeRelations.getRecords())) {
            results.put("this", null);
        }
        AtomicInteger number = new AtomicInteger(1 + ((pageNum - 1) * pageSize));
        List<PromotionSrcVO> srcs = new ArrayList<>();
        for (PmnActivityStoreRelation store : storeRelations.getRecords()) {
            PmnPromotionSrc src = getOne(Wrappers.<PmnPromotionSrc>lambdaQuery().eq(PmnPromotionSrc::getPromoterId, store.getStoreId()).eq(PmnPromotionSrc::getInstanceId, instanceId).eq(PmnPromotionSrc::getType, 2).last("limit 0,1"));
            if (src == null || src.getCode() == null) {
                PoiStoreStaff staff = poiStoreStaffDOMapper.selectOne(Wrappers.<PoiStoreStaff>lambdaQuery().eq(PoiStoreStaff::getStoreId, store.getStoreId()).eq(PoiStoreStaff::getType, 1).ne(PoiStoreStaff::getUserId, 0).eq(PoiStoreStaff::getDeleted, 0).eq(PoiStoreStaff::getStatus, 1));
                src = createCode(staff, instanceId);
            }
            PromotionSrcVO vo = new PromotionSrcVO();
            BeanUtils.copyProperties(src, vo);
            vo.setStore(poiStoreDOMapper.selectById(store.getStoreId()));
            vo.setOrganizational(poiStoreDOMapper.findStoreCompany(store.getStoreId()));
            srcs.add(vo);
            number.incrementAndGet();
        }
        //求分页总数
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<PromotionSrcVO> srcVoPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<PromotionSrcVO>();
        BeanUtils.copyProperties(storeRelations, srcVoPage);
        srcVoPage.setRecords(srcs);
        results.put("this", srcVoPage);
        return results;
    }

    @Override
    public String saveCodeFile(String fileUrl, String code) {
        try {
            File targetPath = new File("activity");
            if (!targetPath.exists()) {
                boolean state = targetPath.mkdirs();
            }
            String path = "activity/" + code + ".png";
            URL httpurl = new URL(fileUrl);
            FileUtils.copyURLToFile(httpurl, new File(path));
            return path;
        } catch (Exception e) {
            log.error("上传出错", e);
            return "";
        }
    }
}
