package com.huiju.estateagents.service.impl;


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.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.excel.HelpInitiateRecordSucceed;
import com.huiju.estateagents.mapper.TaActivityDynamicEnlistMapper;
import com.huiju.estateagents.mapper.TaBuildingDynamicMapper;
import com.huiju.estateagents.mapper.TaBuildingMapper;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.service.ITaBuildingDynamicService;
import com.huiju.estateagents.service.ITaSaveService;
import com.huiju.estateagents.service.TaPosterService;
import com.huiju.estateagents.service.TaShareContentService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 项目动态表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-03-21
 */
@Service
public class TaBuildingDynamicServiceImpl extends ServiceImpl<TaBuildingDynamicMapper, TaBuildingDynamic> implements ITaBuildingDynamicService {

    @Autowired
    private TaBuildingDynamicMapper buildingDynamicMapper;

    @Autowired
    private TaBuildingMapper buildingMapper;

    @Autowired
    private TaActivityDynamicEnlistMapper taActivityDynamicEnlistMapper;

    @Autowired
    private TaPersonMapper taPersonMapper;

    @Autowired
    private ITaSaveService iTaSaveService;

    @Autowired
    private TaPosterService taPosterService;

    @Autowired
    private TaShareContentService taShareContentService;

    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomDateEditor editor = new CustomDateEditor(df, true);//true表示允许为空，false反之
        binder.registerCustomEditor(Date.class, editor);
    }
    @Override
    public ResponseBean iBuildingDynamicList(Integer pageNum, Integer pageSize, String name, String buildingId,Integer cityId,String isEnlist, LocalDateTime time,String title,Integer orgId,String activityStatus,List<TaPersonBuilding> personBuildingList) {
        Page<TaBuildingDynamic> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<TaBuildingDynamic> buildingDynamic = buildingDynamicMapper.buildingDynamicList(page, name, buildingId,cityId,isEnlist,time,title,orgId,activityStatus,personBuildingList);

        HashMap hashMap= new HashMap<>();
        hashMap.put("list",buildingDynamic.getRecords());
        hashMap.put("total",buildingDynamic.getTotal());
        hashMap.put("pageNum",buildingDynamic.getCurrent());
        hashMap.put("pageSize",buildingDynamic.getSize());
        return ResponseBean.success(hashMap);
    }

    @Override
    public ResponseBean iBuildingDynamicSelectId(String id) {
        TaBuildingDynamic buildingDynamicList= buildingDynamicMapper.iBuildingDynamicSelectId(id);
        return ResponseBean.success(buildingDynamicList);
    }

    @Override
    public ResponseBean getWxBuildingDynamiceList(Integer pageNum, Integer pageSize,String buildingId,String openid,Integer cityId,Integer orgId) {
        Page<TaBuildingDynamic> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        TaPerson taPerson = taPersonMapper.selectByIdPerson(openid);
        if (null == taPerson){
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        QueryWrapper<TaBuildingDynamic> buildingDynamicQueryWrapper = new QueryWrapper<>();
        buildingDynamicQueryWrapper.eq(!StringUtils.isEmpty(buildingId),"building_id", buildingId);
        buildingDynamicQueryWrapper.eq("status", "1");
        buildingDynamicQueryWrapper.eq(null != cityId,"city_id",cityId);
        buildingDynamicQueryWrapper.eq("org_id",orgId);
        buildingDynamicQueryWrapper.orderByDesc("weight","create_date");
        IPage<TaBuildingDynamic> buildingDynamicIPage = buildingDynamicMapper.selectPage(page, buildingDynamicQueryWrapper);
        List<TaBuildingDynamic> records = buildingDynamicIPage.getRecords();
        // 判断换当前列表活动状态—1:进行中(展示活动报名截止时间)，2:未开始（展示活动报名时间）,3:结束（不展示）
        for (TaBuildingDynamic taBuildingDynamic:records){
            setExtendInfo(taBuildingDynamic, taPerson);

        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", records);
        map.put("total", buildingDynamicIPage.getTotal());
        map.put("pageNum", buildingDynamicIPage.getCurrent());
        map.put("pageSize", buildingDynamicIPage.getSize());
        return ResponseBean.success(map);
    }

    @Override
    public ResponseBean getWxBuildingDynamiceInfo(String dynamicId,String buildingId,String openid, Integer orgId) {

        QueryWrapper<TaBuildingDynamic> buildingDynamicQueryWrapper = new QueryWrapper<>();
        buildingDynamicQueryWrapper.eq("dynamic_id", dynamicId);
        buildingDynamicQueryWrapper.eq("status",1);
        TaBuildingDynamic tabuildingDynamic = buildingDynamicMapper.selectOne(buildingDynamicQueryWrapper);
        if (null == tabuildingDynamic){
            return ResponseBean.error("当前活动已失效", ResponseBean.ERROR_UNAVAILABLE);
        }
        // 当前阅读量加1
        Integer saveNum = tabuildingDynamic.getPvNum() == null ? 1:tabuildingDynamic.getPvNum()+1;
        tabuildingDynamic.setPvNum(saveNum);
        buildingDynamicMapper.updateById(tabuildingDynamic);
        TaBuildingDynamic buildingDynamic = buildingDynamicMapper.selectOne(buildingDynamicQueryWrapper);
        TaPerson taPerson = taPersonMapper.selectByIdPerson(openid);
        if (null == taPerson){
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }


        setExtendInfo(buildingDynamic, taPerson);

        // 活动已报名人数
        Integer enlistCount = taActivityDynamicEnlistMapper.selectEnlistCount(buildingDynamic.getDynamicId(), orgId);
        buildingDynamic.setEnlisted(enlistCount);
        buildingDynamic.setEnlistNum(buildingDynamic.getPersonNum());

        // 活动海报
        buildingDynamic.setPosters(taPosterService.getPostersForTarget(buildingDynamic.getDynamicId(), CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));
        buildingDynamic.setShareContents(taShareContentService.getPostersForTarget(buildingDynamic.getDynamicId(), CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));

        return ResponseBean.success(buildingDynamic);
    }

    @Override
    public ResponseBean buildingDynamicAdd(HashMap map) {
        TaBuildingDynamic buildingDynamic= new TaBuildingDynamic();
        Date time = (Date)map.get("publishDate");
        Instant instant = time.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

//        buildingDynamic.setDynamicId(idGen.nextId()+"");
        buildingDynamic.setBuildingId(map.get("buildingId")+"");
        buildingDynamic.setImgUrl((String) map.get("imgUrl"));
        buildingDynamic.setListImgUrl((String) map.get("listImgUrl"));
        buildingDynamic.setDesc(map.get("desc")+"");
        buildingDynamic.setUrl(map.get("url")+"");
        buildingDynamic.setTitle(map.get("title")+"");
        buildingDynamic.setPublishDate(localDateTime);
        buildingDynamic.setStatus(1);
        buildingDynamic.setCreateDate(LocalDateTime.now());

        buildingDynamicMapper.insertBuildingDynamic(buildingDynamic);
        return ResponseBean.success("成功");
    }

    @Override
    public ResponseBean buildingDynamicDelete(String id) {
        TaBuildingDynamic buildingDynamic= new TaBuildingDynamic();
        buildingDynamic.setDynamicId(id);
        buildingDynamic.setStatus(-1);
        QueryWrapper<TaBuildingDynamic> buildingDynamicQueryWrapper = new QueryWrapper<>();
        buildingDynamicQueryWrapper.eq("dynamic_id", id);
        buildingDynamicMapper.update(buildingDynamic,buildingDynamicQueryWrapper);
        return ResponseBean.success("成功");
    }

    @Override
    public ResponseBean buildingDynamicUpdate(HashMap<Object, Object> map) {
        TaBuildingDynamic buildingDynamic= new TaBuildingDynamic();

        Date time = (Date)map.get("publishDate");
        Instant instant = time.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

        buildingDynamic.setDynamicId(map.get("dynamicId")+"");
        buildingDynamic.setBuildingId(map.get("buildingId")+"");
        buildingDynamic.setImgUrl((String) map.get("imgUrl"));
        buildingDynamic.setListImgUrl((String) map.get("listImgUrl"));
        buildingDynamic.setDesc(map.get("desc")+"");
        buildingDynamic.setUrl(map.get("url")+"");
        buildingDynamic.setTitle(map.get("title")+"");
        buildingDynamic.setPublishDate(localDateTime);
        buildingDynamic.setStatus(1);
        buildingDynamic.setCreateDate(LocalDateTime.now());

        buildingDynamicMapper.buildingDynamicUpdate(buildingDynamic);
        return ResponseBean.success("成功");
    }

    @Override
    public ResponseBean taActivityDynamicEnlistAdd(TaActivityDynamicEnlist taActivityDynamicEnlist, Integer orgId) {
        ResponseBean responseBean= new ResponseBean<>();
        // 查询当前活动属于哪个楼盘
        TaBuildingDynamic taBuildingDynamic= buildingDynamicMapper.selectById(taActivityDynamicEnlist.getDynamicId());

        /**
         * 判断当前活动是否满
         */

        TaBuildingDynamic buildingDynamic = this.getById(taActivityDynamicEnlist.getDynamicId());
        // 已报名人数
        Integer enlistCount = taActivityDynamicEnlistMapper.selectEnlistCount(taActivityDynamicEnlist.getDynamicId(), orgId);

        // 当报名人数已满时，活动为已结束
        if ((enlistCount + taActivityDynamicEnlist.getAttendNum()) > buildingDynamic.getPersonNum()) {
            //taBuildingDynamic.setIsEnlist(2);
            buildingDynamicMapper.updateById(taBuildingDynamic);
            responseBean.addError("当前报名人数已满");
            return responseBean;
        }
        if(null != buildingDynamic.getEnlistStart() && buildingDynamic.getEnlistStart().isAfter(LocalDateTime.now())){
            responseBean.addError("当前活动未开始报名");
            return responseBean;
        }
        if(null != buildingDynamic.getEnlistEnd() && buildingDynamic.getEnlistEnd().isBefore(LocalDateTime.now())){
            responseBean.addError("当前活动已结束报名");
            return responseBean;
        }
        // 判断是否报名根据电话号码校验
        QueryWrapper<TaActivityDynamicEnlist> taBuildingDynamicQuery=  new QueryWrapper<>();
        taBuildingDynamicQuery.eq("dynamic_id",taBuildingDynamic.getDynamicId());
        taBuildingDynamicQuery.eq("phone",taActivityDynamicEnlist.getPhone());
        TaActivityDynamicEnlist activityDynamicEnlist = taActivityDynamicEnlistMapper.selectOne(taBuildingDynamicQuery);
        if (null !=activityDynamicEnlist){
            responseBean.addError("此号码已报名活动");
            return responseBean;
        }

        // 默认未签到
        taActivityDynamicEnlist.setIsCheckin(0);
        taActivityDynamicEnlist.setCreateDate(LocalDateTime.now())
                .setBuildingId(taBuildingDynamic.getBuildingId());
        int state = taActivityDynamicEnlistMapper.insert(taActivityDynamicEnlist);
        int joinNum = taBuildingDynamic.getEnlistNum() == null ? taActivityDynamicEnlist.getAttendNum():taBuildingDynamic.getEnlistNum()+taActivityDynamicEnlist.getAttendNum();
        taBuildingDynamic.setEnlistNum(joinNum);
        buildingDynamicMapper.updateById(taBuildingDynamic);
        return ResponseBean.success(state);
    }

    @Override
    public ResponseBean signList(Page<TaActivityDynamicEnlist> page, String dynamicId, Integer orgId,String isCheckin,String name,String phone) {
        List<TaActivityDynamicEnlist> signList= taActivityDynamicEnlistMapper.signList(page,dynamicId, orgId,isCheckin,name,phone);
        return ResponseBean.success(signList);
    }

    /**
     *     根据报名开始时间和结束时间判断当前图标状态
     */
    private  TaBuildingDynamic  timeCondition(TaBuildingDynamic taBuildingDynamic){
        Long currentTime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        if (null == taBuildingDynamic.getEnlistEnd () && null == taBuildingDynamic.getEnlistStart()){
            return  taBuildingDynamic;
        }
        // 报名截止时间
        Long enlistEnd = taBuildingDynamic.getEnlistEnd ().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        // 报名开始时间
        Long enlistStart = taBuildingDynamic.getEnlistStart().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        // (1:进行中)当前时间小于报名截止时间,并且报名状态为1
        if ("1".equals(taBuildingDynamic.getIsEnlist()) && currentTime <= enlistEnd ) {
            taBuildingDynamic.setActivityCondition(CommConstant.ACTIVITY_CONDITION_PROCESSING);
        }
        //(2:未开始)当前时间是否小于报名时间,并且报名状态为1
        if (!"1".equals(taBuildingDynamic.getIsEnlist()) && currentTime <= enlistStart){
            taBuildingDynamic.setActivityCondition(CommConstant.ACTIVITY_CONDITION_PREPARE);
        }
        //(3:结束)当前时间大于报名结束时间,并且报名状态为1
        if ("1".equals(taBuildingDynamic.getIsEnlist()) && currentTime >= enlistEnd){
            taBuildingDynamic.setActivityCondition(CommConstant.ACTIVITY_CONDITION_FINISH);
        }
        return taBuildingDynamic;
    }


    @Override
    public void setExtendInfo(TaBuildingDynamic taBuildingDynamic, TaPerson taPerson) {
        // 是否已报名
        QueryWrapper<TaActivityDynamicEnlist> activityDynamicEnlist = new QueryWrapper<>();
        activityDynamicEnlist.eq("person_id", taPerson.getPersonId());
        activityDynamicEnlist.eq("dynamic_id", taBuildingDynamic.getDynamicId());
        Integer taActivityDynamicEnlistPhone= taActivityDynamicEnlistMapper.selectCount(activityDynamicEnlist);
        if (taActivityDynamicEnlistPhone>0){
            taBuildingDynamic.setIsSign(1);
        } else {
            taBuildingDynamic.setIsSign(0);
        }

        // 获取报名总数
        QueryWrapper<TaActivityDynamicEnlist> taActivityDynamicEnlist = new QueryWrapper<>();
        taActivityDynamicEnlist.eq("dynamic_id", taBuildingDynamic.getDynamicId());
        taActivityDynamicEnlist.eq("building_id", taBuildingDynamic.getBuildingId());
        int applyCount= taActivityDynamicEnlistMapper.selectCount(taActivityDynamicEnlist);
        taBuildingDynamic.setCount(applyCount);
        taBuildingDynamic.setPosters(taPosterService.getPostersForTarget(taBuildingDynamic.getDynamicId(),CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));
        taBuildingDynamic.setShareContents(taShareContentService.getPostersForTarget(taBuildingDynamic.getDynamicId(),CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));

        // 是否收藏
        TaSave taSave = iTaSaveService.getInfoBy(taPerson.getPersonId(), CommConstant.FAVOR_ACTIVITY, taBuildingDynamic.getDynamicId());
        if (null == taSave) {
            taBuildingDynamic.setIsSaved(0);
        } else {
            taBuildingDynamic.setIsSaved(1);
        }

        timeCondition(taBuildingDynamic);
    }

    @Override
    public Integer updateActivityToUnStart(String time) {
        return buildingDynamicMapper.updateActivityToUnStart(time);
    }

    @Override
    public Integer updateUnStartActivity(String curTime) {
        return buildingDynamicMapper.updateUnStartActivity(curTime);
    }

    @Override
    public void updateProcessingActivity() {
        buildingDynamicMapper.updateProcessingActivity();
    }

    @Override
    public Integer getTaActivityDynamicEnlist(String dynamicId, String isCheckin, String name, String phone) {
        QueryWrapper<TaActivityDynamicEnlist> querTaActivityDynamicEnlist = new QueryWrapper<>();
        querTaActivityDynamicEnlist.eq("dynamic_id",dynamicId);
        querTaActivityDynamicEnlist.eq(!StringUtils.isEmpty(isCheckin),"is_checkin",isCheckin);
        querTaActivityDynamicEnlist.eq(!StringUtils.isEmpty(name),"name",name);
        querTaActivityDynamicEnlist.eq(!StringUtils.isEmpty(phone),"name",phone);
        return taActivityDynamicEnlistMapper.selectCount(querTaActivityDynamicEnlist);
    }

    @Override
    public List<HelpInitiateRecordSucceed> getTaActivityDynamicEnlistExport(int i, Integer pageSize, String dynamicId, String isCheckin, String name, String phone,Integer orgId) {
        return taActivityDynamicEnlistMapper.getTaActivityDynamicEnlistExport(i,pageSize,dynamicId,isCheckin,name,phone,orgId);
    }

    /**
     * 下拉选框数据
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param buildingId
     * @param cityId
     * @param isEnlist
     * @param time
     * @param title
     * @param orgId
     * @param activityStatus
     * @return
     */
    @Override
    public ResponseBean iBuildingDynamicSelectedList(Integer pageNum, Integer pageSize, String name, String buildingId, Integer cityId, String isEnlist, LocalDateTime time, String title, Integer orgId, String activityStatus,List<TaPersonBuilding> personBuildingList) {
        Page<TaBuildingDynamic> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<TaBuildingDynamic> buildingDynamic = buildingDynamicMapper.iBuildingDynamicSelectedList(page, name, buildingId,cityId,isEnlist,time,title,orgId,activityStatus,personBuildingList);

        HashMap hashMap= new HashMap<>();
        hashMap.put("list",buildingDynamic.getRecords());
        hashMap.put("total",buildingDynamic.getTotal());
        hashMap.put("pageNum",buildingDynamic.getCurrent());
        hashMap.put("pageSize",buildingDynamic.getSize());
        return ResponseBean.success(hashMap);
    }

    @Override
    public IPage<TaBuildingDynamic> getJoinedActivity(int pageNumber, int pageSize,String building,TaPerson person,Integer orgId){
        QueryWrapper<TaActivityDynamicEnlist> activityDynamicEnlistQueryWrapper = new QueryWrapper<>();
        activityDynamicEnlistQueryWrapper.eq("phone",person.getPhone());
        activityDynamicEnlistQueryWrapper.eq("org_id",orgId);
        if(!StringUtils.isEmpty(building)){
            activityDynamicEnlistQueryWrapper.eq("building_id",building);
        }
        List<TaActivityDynamicEnlist> activityDynamicEnlists = taActivityDynamicEnlistMapper.selectList(activityDynamicEnlistQueryWrapper);
        List<String>activityIds = new ArrayList<>();
        for (int i=0;i<activityDynamicEnlists.size();i++){
            activityIds.add(activityDynamicEnlists.get(i).getDynamicId());
        }
        IPage<TaBuildingDynamic> page = new Page<>(pageNumber, pageSize);
        IPage<TaBuildingDynamic> pageEmpty = new Page<>(pageNumber, pageSize);
        QueryWrapper<TaBuildingDynamic> empty = new QueryWrapper<>();
        if(activityIds.size()>0){
            empty.in("dynamic_id",activityIds);
            empty.orderBy(true,false,"start_date");
            IPage<TaBuildingDynamic> result = buildingDynamicMapper.selectPage(page,empty);
            for(int i=0;i<result.getRecords().size();i++){
                TaBuildingDynamic taBuildingDynamic = result.getRecords().get(i);
                taBuildingDynamic.setIsSign(CommConstant.STATUS_NORMAL);
                // 获取报名总数
                QueryWrapper<TaActivityDynamicEnlist> taActivityDynamicEnlist = new QueryWrapper<>();
                taActivityDynamicEnlist.eq("dynamic_id", result.getRecords().get(i).getDynamicId());
                taActivityDynamicEnlist.eq("building_id", result.getRecords().get(i).getBuildingId());
                int applyCount= taActivityDynamicEnlistMapper.selectCount(taActivityDynamicEnlist);
                taBuildingDynamic.setCount(applyCount);

                // 是否收藏
                TaSave taSave = iTaSaveService.getInfoBy(person.getPersonId(), CommConstant.FAVOR_ACTIVITY, result.getRecords().get(i).getDynamicId());
                if (null == taSave) {
                    taBuildingDynamic.setIsSaved(0);
                } else {
                    taBuildingDynamic.setIsSaved(1);
                }

                // 获取海报图 和 分享图
                taBuildingDynamic.setPosters(taPosterService.getPostersForTarget(taBuildingDynamic.getDynamicId(), CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));
                taBuildingDynamic.setShareContents(taShareContentService.getPostersForTarget(taBuildingDynamic.getDynamicId(), CommConstant.POSTER_CONTENT_TYPE_ACTIVITY));

                //更改状态为已参与
                taBuildingDynamic.setActivityStatus(CommConstant.ACTIVITY_STATUS_PARTNER);

            }
            return result;
        }else {
            return pageEmpty;
        }
    }
}
