package com.huiju.estateagents.property.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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.property.dao.*;
import com.huiju.estateagents.property.model.*;
import com.huiju.estateagents.property.service.TpAnnouncementService;
import com.huiju.estateagents.property.vo.AnnouncementTable;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
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.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * version V1.0
 * class_name: $METHOD_NAME$
 * param: $METHOD_PARAM$
 * describe: TODO
 * creat_user:fannaixi
 * creat_time: 2018/12/28
 **/
@Slf4j
@Transactional
@Service
public class TpAnnouncementServiceImpl extends ServiceImpl<TpAnnouncementMapper, TpAnnouncement> implements TpAnnouncementService {

@Autowired
private  TpAnnouncementMapper tpAnnouncementMapper;

    @Autowired
    private TdImagesMapper imagesMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MessageMapper messageMapper;

//    @Autowired
//    private TaUserMapper taUserMapper;
    @Override
    public ResponseBean tpAnnouncemenList(String paramets, Integer CommunityId) {
        ResponseBean responseBean = new ResponseBean();

        TpAnnouncement   tpAnnouncement= JSONObject.parseObject(paramets, TpAnnouncement.class);
        tpAnnouncement.setCommunityId(CommunityId);
        JSONObject jsonobject = JSONObject.parseObject(paramets);
        Integer pageNum = jsonobject.getInteger("pageNum");
        Integer announcementNumber = jsonobject.getInteger("announcementNumber");
        Integer pageSize = jsonobject.getInteger("pageSize");
        tpAnnouncement.setId(announcementNumber);
        // 分页
        Page<TpBuildingOwnerInfo> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);
        // page.setDesc("sort", "create_date");

        IPage<TpAnnouncement> pageInfo = tpAnnouncementMapper.getAnnouncements(page,tpAnnouncement);
        List<TpAnnouncement> tpAnnouncementList = pageInfo.getRecords();

        List<AnnouncementTable> tableList = tpAnnouncementList.stream().map(e->{
            AnnouncementTable announcementTable = new AnnouncementTable();
            BeanUtils.copyProperties(e, announcementTable);
            //创建人
            String  updateDateName= userMapper.selectByIdUserName(e.getUpdateUser());
            //修改人
            String  createUserName= userMapper.selectByIdUserName(e.getCreateUser());
            announcementTable.setCreateUserName(createUserName);
            announcementTable.setUpdateDateName(updateDateName);
            return announcementTable;
        }).collect(Collectors.toList());

        Map<String, Object> map = Maps.newHashMap();
        map.put("list", tableList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        responseBean.addSuccess(map);
        return responseBean;
    }

    @Override
    public ResponseBean addAnnouncement(String paramets, Integer communityId,Integer userId) {
        ResponseBean response = new ResponseBean();
        JSONObject jsonobject = JSONObject.parseObject(paramets);
        TpAnnouncement tpAnnouncement = JSONObject.parseObject(paramets, TpAnnouncement.class);
        tpAnnouncement.setCommunityId(communityId);
        tpAnnouncement.setCreateDate(new Date());
        tpAnnouncement.setCreateUser(userId);
        tpAnnouncement.setViewCount(0);
        JSONArray contentImg = jsonobject.getJSONArray("contentImg");
        String[] contentImgArray = contentImg.toArray(new String[]{});

        if (tpAnnouncement.getAnnouncementTitle() == null) {
            response.addError("标题不能为空");
            return response;
        }
        if (null == tpAnnouncement.getAnnouncementContent() && null == contentImg) {
            response.addError("内容和图片必须填一个");
            return response;
        }
        tpAnnouncementMapper.insert(tpAnnouncement);
        //根据1.5需求维护tp_message
            Message message = new Message();
            message.setCommunityId(communityId);
            message.setMessageType("5");
            message.setModelType("2");
            message.setAdviceType("4");
            message.setUuid(userId);
            message.setUuidType("2");
            message.setSource("2");
            message.setMessageContent("公告“" + tpAnnouncement.getAnnouncementTitle() + "”还未发布，查看详情");
            message.setStatus("1");
            message.setReadStatus("0");
            message.setCreateUser(userId);
            message.setCreateDate(LocalDateTime.now());
            message.setAnnouncementId(tpAnnouncement.getId());
            //为草稿的时
            if ("2".equals(tpAnnouncement.getStatus())) {
                messageMapper.insert(message);
            }
            message.setModelType("1");
            message.setAdviceType("1");
            message.setSource("1");
            message.setUuidType("1");
            message.setMessageContent(tpAnnouncement.getAnnouncementTitle());

        if ("1".equals(tpAnnouncement.getStatus())) {
            QueryWrapper<TaUser> queryWrapperTaUser = new QueryWrapper<>();
            queryWrapperTaUser.eq("community_id",communityId);
//            List<TaUser> userList= taUserMapper.selectList(queryWrapperTaUser);
//            for (TaUser taUser:userList) {
//                message.setUuid(taUser.getId());
//                messageMapper.insert(message);
//            }
        }
        for (String img : contentImgArray) {
            TdImages tdImages = new TdImages();
            tdImages.setImageUrl(img);
            tdImages.setType("announcement");
            tdImages.setUuid(tpAnnouncement.getId());
            tdImages.setCreateTime(LocalDateTime.now());
            tdImages.setCreateUser(userId);
            imagesMapper.insert(tdImages);
        }
            return response;
    }
        @Override
        public ResponseBean announcementById(String paramets) {
            ResponseBean response= new ResponseBean<>();
            JSONObject jsonobject = JSONObject.parseObject(paramets);
            Integer   id= jsonobject.getInteger("id");
            TpAnnouncement tpAnnouncement=tpAnnouncementMapper.selectById(id);
            //查询图片
            QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TdImages::getUuid,id);
            queryWrapper.lambda().eq(TdImages::getType,"announcement");
            List<TdImages> studentList = imagesMapper.selectList(queryWrapper);
            HashMap map= new HashMap<>();

            for (TdImages tdImages:studentList){
               tdImages.getImageUrl();
            }
            map.put("tpAnnouncement",tpAnnouncement);
            map.put("studentList",studentList);
            response.addSuccess(map);
            return response;
        }

    @Override
    public ResponseBean updateAnnouncement(String paramets,Integer communityId,Integer userId) {
                  ResponseBean response= new ResponseBean();
         TpAnnouncement tpAnnouncement = JSONObject.parseObject(paramets, TpAnnouncement.class);
         int Status= Integer.parseInt(tpAnnouncement.getStatus());
         if (0!=Status){
                        tpAnnouncement.setCommunityId(communityId);
                        tpAnnouncement.setUpdateUser(userId);
                        tpAnnouncement.setCreateUser(null);
                        //为草稿时不跟新时间
             TpAnnouncement AnnouncementStatus=tpAnnouncementMapper.selectById(tpAnnouncement.getId());
                            tpAnnouncement.setUpdateDate("2".equals(AnnouncementStatus.getStatus())?null:new Date());
                            tpAnnouncement.setUpdateUser("2".equals(AnnouncementStatus.getStatus())?null:userId);
                        tpAnnouncementMapper.updateTpAnnouncement(tpAnnouncement);

        JSONObject parseObject = JSONObject.parseObject(paramets);
        //内容包含多个图转数组
        JSONArray contentImg = parseObject.getJSONArray("contentImg");
        Integer tdImagesUuid = parseObject.getInteger("id");
        String[] contentImgArray = contentImg.toArray(new String[]{});
        //修改图片时删除原来图片
            QueryWrapper<TdImages> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TdImages::getUuid, tdImagesUuid);
            queryWrapper.lambda().eq(TdImages::getType, "announcement");
            imagesMapper.delete(queryWrapper);

            for (String img : contentImgArray) {
                TdImages tdImages = new TdImages();
                tdImages.setImageUrl(img);
                tdImages.setType("announcement");
                tdImages.setUuid(tpAnnouncement.getId());
                tdImages.setCreateTime(LocalDateTime.now());
                tdImages.setCreateUser(userId);
                imagesMapper.insert(tdImages);
            }
                // 公告发布成功删除时消息变为无效
                Message message = new Message();
                message.setMessageContent("公告“" + tpAnnouncement.getAnnouncementTitle() + "”还未发布，查看详情");
                message.setAnnouncementId(tpAnnouncement.getId());
                message.setUpdateDate(LocalDateTime.now());
                message.setUpdateUser(userId);
                message.setStatus("0");
                messageMapper.updateMessage(message);

        }
        return response;
    }

    @Override
    public ResponseBean deleteAnnouncement(String paramets, Integer communityId, Integer userId) {
        ResponseBean response = new ResponseBean();
        JSONObject parseObject = JSONObject.parseObject(paramets);

        JSONArray announcementIdId = parseObject.getJSONArray("id");
        Integer[] announcementIdArray = announcementIdId.toArray(new Integer[]{});
        for (Integer id : announcementIdArray) {
            TpAnnouncement tpAnnouncement = new TpAnnouncement();
            tpAnnouncement.setId(id);
            tpAnnouncement.setCommunityId(communityId);
            tpAnnouncement.setStatus("0");
            tpAnnouncementMapper.updateTpAnnouncement(tpAnnouncement);
            //1.5版本维护消息
            Message message= new Message();
            message.setStatus("0");
            message.setAnnouncementId(id);
            message.setUpdateUser(userId);
            message.setUpdateDate(LocalDateTime.now());
            messageMapper.updateMessage(message);
        }
        return response;
    }
}
