package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.commom.utils.BeanTools;
import com.community.huiju.common.base.QRCode;
import com.community.huiju.common.perproties.QRCodePerproties;
import com.community.huiju.dao.MessageMapper;
import com.community.huiju.dao.TaUserMapper;
import com.community.huiju.dao.TdImagesMapper;
import com.community.huiju.dao.TpActivityMapper;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.ITdImagesService;
import com.community.huiju.service.ITpActivityService;
import com.community.huiju.service.IUserService;
import com.community.huiju.service.ImageServiceI;
import com.community.huiju.vo.ActivityVO;
import com.google.common.collect.Maps;
import com.google.zxing.WriterException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 物业web端活动表 服务实现类
 * </p>
 *
 * @author weiximei
 * @since 2018-12-28
 */
@Service
public class TpActivityServiceImpl extends ServiceImpl<TpActivityMapper, TpActivity> implements ITpActivityService {

    @Autowired
    private TpActivityMapper tpActivityMapper;

    @Autowired
    private TdImagesMapper tdImagesMapper;

    @Autowired
    private ITdImagesService iTdImagesService;

    // 物业用户
    @Autowired
    private IUserService iUserService;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private ImageServiceI imageServiceI;

    @Autowired
    private QRCodePerproties qrCodePerproties;

    @Override
    public ResponseBean listQuery(String parameter, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        JSONObject jsonObject = JSONObject.parseObject(parameter);
        // TpActivity tpActivity = jsonObject.toJavaObject(TpActivity.class);
        String id = jsonObject.getString("id");
        String activityTitle = jsonObject.getString("activityTitle");
        Long pageNum = jsonObject.getLong("pageNum") == null ? 1 : jsonObject.getLong("pageNum");
        Long pageSize = jsonObject.getLong("pageSize") == null ? 10 : jsonObject.getLong("pageSize");

        Page<TpActivity> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        QueryWrapper<TpActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(id != null && !"".equals(id),"id", id);
        queryWrapper.like(activityTitle != null && !"".equals(activityTitle),"activity_title", activityTitle);
        queryWrapper.eq("community_id", userElement.getCommunityId());
        queryWrapper.orderByDesc("sort","create_date");

        IPage<TpActivity> infoPage = tpActivityMapper.selectPage(page, queryWrapper);
        List<TpActivity> activityList = infoPage.getRecords();
        List<ActivityVO> activityVOList = activityList.stream().map(activity-> {
            ActivityVO activityVO = new ActivityVO();
            BeanUtils.copyProperties(activity, activityVO);
            User createUser = iUserService.getById(activity.getCreateUser());
            activityVO.setCrateUserName(createUser.getUserName());
            if (activity.getUpdateUser() != null) {
                User updateUser = iUserService.getById(activity.getUpdateUser());
                activityVO.setUpdateUserName(updateUser.getUserName());
            }
            // TODO 临时数据
            activityVO.setSignInCount(1);
            return activityVO;
        }).collect(Collectors.toList());

        Map<String, Object> map = Maps.newHashMap();
        map.put("list", activityVOList);
        map.put("total", infoPage.getTotal());
        map.put("pageNum", infoPage.getCurrent());
        map.put("pageSize", infoPage.getSize());

        responseBean.addSuccess(map);

        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addActivity(String parameter, UserElement userElement) {

        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        //是否需要签到二维码1:需要2不需要
        int radio= jsonObject.getIntValue("radio");
        // 活动配图
        JSONArray jsonArray = jsonObject.getJSONArray("contentImg");
        String [] contentImgArray = jsonArray.toArray(new String[]{});
        TpActivity tpActivity = jsonObject.toJavaObject(TpActivity.class);

        if (StringUtils.isBlank(tpActivity.getActivityTitle())) {
            responseBean.addError("活动标题不能为空!");
            return responseBean;
        }

        if (tpActivity.getSignUpMax() == null) {
            responseBean.addError("活动报名人数上限不能为空!");
            return responseBean;
        }

        if (tpActivity.getRegistrationEndTime() == null) {
            responseBean.addError("活动报名截止时间不能为空!");
            return responseBean;
        }

        if (tpActivity.getSort() == null) {
            responseBean.addError("活动权重值不能为空!");
            return responseBean;
        }

        if (contentImgArray.length <= 0 && (null == tpActivity.getActivityContent() || "".equals(tpActivity.getActivityContent()))){
            responseBean.addError("活动内容描述 和 活动配图至少要存在一个!");
            return responseBean;
        }


        // 活动报名人数默认为 0
        tpActivity.setSignUpCount(0);
        tpActivity.setViewCount(0);
        if (radio>0) {
            tpActivity.setSignInCode(radio+"");
        }
        tpActivity.setCommunityId(userElement.getCommunityId());
        tpActivity.setCreateDate(LocalDateTime.now());
        tpActivity.setCreateUser(userElement.getId());

        int row = tpActivityMapper.insert(tpActivity);

        // 插入图片
        insertImg(contentImgArray, userElement, tpActivity);

        if (row <= 0) {
            throw new WisdomException("操作失败!");
        } else {

                // 草稿时插入消息
                Message activityMessage = new Message();
            activityMessage.setCommunityId(userElement.getCommunityId());
            activityMessage.setMessageType("8");
            activityMessage.setAdviceType("4");
            activityMessage.setModelType("2");
            activityMessage.setUuid(userElement.getId());
            activityMessage.setUuidType("2");
            activityMessage.setSource("2");
            activityMessage.setMessageContent("活动“{" + tpActivity.getActivityTitle() + "}”还未发布，点击发布");
            activityMessage.setStatus("1");
            activityMessage.setActivityId(tpActivity.getId());
            activityMessage.setCreateDate(LocalDateTime.now());
            activityMessage.setCreateUser(userElement.getId());
            activityMessage.setReadStatus("0");
                //为草稿时
                if ("2".equals(tpActivity.getStatus())) {
                    messageMapper.insert(activityMessage);
                }
            activityMessage.setModelType("1");
            activityMessage.setAdviceType("1");
            activityMessage.setSource("1");
            activityMessage.setUuidType("1");
            activityMessage.setMessageContent(tpActivity.getActivityTitle());

            if("1".equals(tpActivity.getStatus())) {
                QueryWrapper<TaUser> queryWrapperTaUser = new QueryWrapper<>();
                queryWrapperTaUser.eq("community_id",userElement.getCommunityId());
                List<TaUser> userList= taUserMapper.selectList(queryWrapperTaUser);
                for (TaUser taUser:userList){
                    activityMessage.setUuid(taUser.getId());
                    messageMapper.insert(activityMessage);
                }

            }
                // 发布时消息为无效
//                if ("1".equals(tpActivity.getStatus())) {
//                    QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.eq("community_id", userElement.getCommunityId());
//                    queryWrapper.eq("message_type", "8");
//                    queryWrapper.eq("model_type", "2");
//                    queryWrapper.eq("source", "2");
//                    queryWrapper.eq("status", "1");
//                    Message message = messageMapper.selectOne(queryWrapper);
//                    if (null != message) {
//                        message.setStatus("0");
//                        message.setUpdateDate(LocalDateTime.now());
//                        message.setUpdateUser(userElement.getId());
//                        messageMapper.updateById(message);
//                    }
//
//                }
                // 扫码签到

                if (radio==1){

//                       InputStream inputStream= QRCode.encode(qrCodePerproties.getUrl(),tpActivity.getId()+"");
//                        String codeUrl= imageServiceI.getImageUrl(inputStream);

                        TdImages tdImages= new TdImages();
                        tdImages.setImageUrl(qrCodePerproties.getUrl() + tpActivity.getId());
                        tdImages.setUuid(tpActivity.getId());
                        tdImages.setType("activityCode");
                        tdImages.setCreateUser(userElement.getId());
                        tdImages.setCreateTime(LocalDateTime.now());
                        tdImagesMapper.insert(tdImages);


                }

            responseBean.addSuccess("操作成功!");
        }

        return responseBean;
    }

    /**
     * 插入图片
     * @param contentImgArray
     * @param userElement
     * @param tpActivity
     */
    private void insertImg(String [] contentImgArray, UserElement userElement, TpActivity tpActivity) {
        if (contentImgArray == null) {
            return;
        }
        for (String img : contentImgArray) {
            TdImages tdImages = new TdImages();
            tdImages.setCreateTime(LocalDateTime.now());
            tdImages.setCreateUser(userElement.getId());
            tdImages.setImageUrl(img);
            tdImages.setType("activity");
            tdImages.setUuid(tpActivity.getId());

            tdImagesMapper.insert(tdImages);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateActivity(String parameter, UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        TpActivity tpActivity = jsonObject.toJavaObject(TpActivity.class);

        // 活动配图
        JSONArray jsonArray = jsonObject.getJSONArray("contentImg");
        String [] contentImgArray = jsonArray.toArray(new String[]{});
        //是否需要签到二维码1:需要2不需要
        int radio= jsonObject.getIntValue("radio");
        if(radio==2){
            tpActivity.setSignInCode("2");
                QueryWrapper<TdImages> tdImages= new QueryWrapper<>();
                tdImages.eq("uuid",tpActivity.getId())
                        .eq("type","activityCode");
            tdImagesMapper.delete(tdImages);
        }

        TpActivity selectTpActivity = tpActivityMapper.selectById(tpActivity.getId());
        if (null == selectTpActivity) {
            responseBean.addError("活动不存在!");
            return responseBean;
        }
        // 状态
        int temp = Integer.valueOf(selectTpActivity.getStatus());

        BeanTools.copyProperties(tpActivity, selectTpActivity);

        /**
         * 如果是草稿, 则只需要变更创建时间! 因为前端页面的活动修改, 就是发布按钮, 这样前端就不会显示为已修改状态
         */
        if (temp == 2) {
            selectTpActivity.setCreateDate(LocalDateTime.now());
        } else {
            selectTpActivity.setUpdateDate(LocalDateTime.now());
            selectTpActivity.setUpdateUser(userElement.getId());
        }

        // 发布时消息为无效
        if ("1".equals(tpActivity.getStatus())) {
            QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("community_id", userElement.getCommunityId());
            queryWrapper.eq("message_type", "8");
            queryWrapper.eq("model_type", "2");
            queryWrapper.eq("source", "2");
            queryWrapper.eq("status", "1");
            queryWrapper.eq("activity_id",tpActivity.getId());
            Message message = messageMapper.selectOne(queryWrapper);
            if (null != message) {
                message.setStatus("0");
                message.setUpdateDate(LocalDateTime.now());
                message.setUpdateUser(userElement.getId());
                messageMapper.updateById(message);
            }


        }

        int row = tpActivityMapper.updateById(selectTpActivity);

        // 先将原图删除!
         QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("uuid", tpActivity.getId());
         queryWrapper.eq("type", "activity");
         tdImagesMapper.delete(queryWrapper);

        if (radio==1){

//                InputStream inputStream= QRCode.encode(qrCodePerproties.getUrl(), tpActivity.getId()+"");
//                String codeUrl= imageServiceI.getImageUrl(inputStream);
                TdImages tdImages= new TdImages();
                tdImages.setImageUrl(qrCodePerproties.getUrl() + tpActivity.getId());
                tdImages.setUuid(tpActivity.getId());
                tdImages.setType("activityCode");
                tdImages.setCreateUser(userElement.getId());
                tdImages.setCreateTime(LocalDateTime.now());
                tdImagesMapper.insert(tdImages);

        }


        // 插入图片
        insertImg(contentImgArray, userElement, tpActivity);

        if (row <= 0) {
            throw new WisdomException("操作失败!");
        } else {
            responseBean.addSuccess("操作成功!");
        }

        return responseBean;
    }

    @Override
    public ResponseBean getById(Integer id) {
        ResponseBean responseBean = new ResponseBean();

        TpActivity tpActivity = tpActivityMapper.selectById(id);

        QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", tpActivity.getId());
        queryWrapper.eq("type", "activity");
        List<TdImages> imagesList = tdImagesMapper.selectList(queryWrapper);

        /*查询活动二维码*/
        QueryWrapper<TdImages> activityCode = new QueryWrapper<>();
        activityCode.eq("uuid", tpActivity.getId());
        activityCode.eq("type", "activityCode");
        TdImages img = tdImagesMapper.selectOne(activityCode);
        if (null!= img) {
            tpActivity.setActivityCode( img.getImageUrl());
        }
        // 转换, 只保留 imageUrl 字段
        List<String> stringList = imagesList.stream().map(e->new String(e.getImageUrl())).collect(Collectors.toList());

        Map<String, Object> map = Maps.newHashMap();
        map.put("info", tpActivity);
        map.put("contentImg", stringList);

        responseBean.addSuccess(map);

        return responseBean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateStatusInvalid(List<Integer> ids, UserElement userElement) {

        ResponseBean responseBean = new ResponseBean();
        List<TpActivity> tpActivityList = (List<TpActivity>) listByIds(ids);
        tpActivityList.stream().forEach(e-> {
            if ("0".equals(e.getStatus())) {
                throw new WisdomException("已作废活动无法修改");
            }
            e.setStatus("0");
            // e.setUpdateUser(userElement.getId());
            // 作废时消息为无效
            if ("0".equals(e.getStatus())) {
                QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("community_id", userElement.getCommunityId());
                queryWrapper.eq("message_type", "8");
                queryWrapper.eq("model_type", "2");
                queryWrapper.eq("source", "2");
                queryWrapper.eq("status", "1");
                Message message = messageMapper.selectOne(queryWrapper);
                if (null != message) {
                    message.setStatus("0");
                    message.setUpdateDate(LocalDateTime.now());
                    message.setUpdateUser(userElement.getId());
                    messageMapper.updateById(message);
                }


            }
        });
        updateBatchById(tpActivityList);

        responseBean.addSuccess("操作成功!");

        return responseBean;
    }
}
