package com.huiju.estateagents.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.reportCustomerAop.ReportCustomer;
import com.huiju.estateagents.service.*;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.ITaShareActivityService;
import com.huiju.estateagents.service.ITaShareChildRecordService;
import com.huiju.estateagents.service.ITaShareRecordService;
import com.huiju.estateagents.service.ITdPosterTemplateService;
import com.huiju.estateagents.service.TaPosterService;
import com.huiju.estateagents.service.TaShareContentService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 拼团活动表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@RestController
@RequestMapping("/api")
public class TaShareActivityController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaShareActivityController.class);

    @Autowired
    public ITaShareActivityService iTaShareActivityService;
    
    @Autowired
    private ITaPersonService taPersonService;
    
    @Autowired
    private ITaShareRecordService taShareRecordService;
    
    @Autowired
    private ITaShareChildRecordService taShareChildRecordService;
    
    @Autowired
    private TaPosterService taPosterService;
    
    @Autowired
    private TaShareContentService taShareContentService;

    @Autowired
    private ITaBuildingService iTaBuildingService;
    
    @Autowired
    private ITdPosterTemplateService tdPosterTemplateService;

    @Autowired
    private  IExtendContentService iExtendContentService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taShareActivity/list",method= RequestMethod.GET)
    public ResponseBean taShareActivityList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                            @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                            @RequestParam(value ="buildingId",required = false) String buildingId,
                                            @RequestParam(value ="activityName",required = false) String activityName,
                                            @RequestParam(value ="activityStatus",required = false) String activityStatus,
                                            @RequestParam(value ="cityId",required = false)Integer cityId,
                                            HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaShareActivityService.getList(pageNum, pageSize, buildingId, activityName, activityStatus, null, null, cityId, getOrgId(request),getTaPersonBuildingListByUserId(request));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 分页查询列表 已开始 和 未开始
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taShareActivityEffective/list",method= RequestMethod.GET)
    public ResponseBean taShareActivityList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                            @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                            @RequestParam(value ="cityId",required = false)Integer cityId,
                                            @RequestParam(value ="buildingId",required = false)String buildingId,
                                            @RequestParam(value ="name",required = false)String name,
                                            @RequestParam(value ="status",required = false)Integer status,
                                            HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaShareActivityService.getEffectiveList(pageNum, pageSize, cityId, buildingId, getOrgId(request),status,name,getTaPersonBuildingListByUserId(request));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param parameter 实体对象json格式
     * @return
     */
    @RequestMapping(value="/admin/taShareActivity",method= RequestMethod.POST)
    public ResponseBean taShareActivityAdd(@RequestBody String parameter, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaShareActivity taShareActivity = JSONObject.parseObject(parameter, TaShareActivity.class);
        try {
            if  (taShareActivity.getGroupBuyPeople() <= 1){
                responseBean.addError("拼团人数必须大于等于2人");
                return responseBean;
            }

            QueryWrapper<TaShareActivity> taShareActivityQueryWrapper = new QueryWrapper<>();
            taShareActivityQueryWrapper.eq("heavy", taShareActivity.getHeavy());
//            Integer heavyCount = iTaShareActivityService.count(taShareActivityQueryWrapper);
//            if (heavyCount != 0){
//                responseBean.addError("权重已存在，请重新编辑");
//                return responseBean;
//            }

            Integer cityId = iTaBuildingService.getCityById(taShareActivity.getBuildingId());
            taShareActivity.setCityId(cityId);
            taShareActivity.setOrgId(getOrgId(request));
            taShareActivity.setStatus(1);
            taShareActivity.setActivityStatus(1);
            taShareActivity.setSort(false);
            taShareActivity.setWeight(0);
            if (iTaShareActivityService.save(taShareActivity)){
                responseBean.addSuccess(taShareActivity);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        responseBean.addSuccess(taShareActivity.getGroupActivityId());
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/admin/taShareActivity/{id}", method= RequestMethod.DELETE)
    public ResponseBean taShareActivityDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaShareActivityService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param  parameter 实体对象json
     * @return
     */
    @RequestMapping(value="/admin/taShareActivity/update",method= RequestMethod.PUT)
    public ResponseBean taShareActivityUpdate(@RequestBody String parameter){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaShareActivity taShareActivity = JSONObject.parseObject(parameter, TaShareActivity.class);
            Integer cityId = iTaBuildingService.getCityById(taShareActivity.getBuildingId());
            taShareActivity.setCityId(cityId);

            QueryWrapper<TaShareActivity> taShareActivityQueryWrapper = new QueryWrapper<>();
            taShareActivityQueryWrapper.eq("heavy", taShareActivity.getHeavy());
            taShareActivityQueryWrapper.ne("group_activity_id", taShareActivity.getGroupActivityId());
//            Integer heavyCount = iTaShareActivityService.count(taShareActivityQueryWrapper);
//            if (heavyCount != 0){
//                responseBean.addError("权重已存在，请重新编辑");
//                return responseBean;
//            }

            if (iTaShareActivityService.updateById(taShareActivity)){
                responseBean.addSuccess(taShareActivity);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/taShareActivity/{id}",method= RequestMethod.GET)
    public ResponseBean taShareActivityGet(@PathVariable Integer id, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            TaShareActivity taShareActivity = iTaShareActivityService.getById(id);
//            taShareActivity.setGroupBuyPeople(iTaShareActivityService.countGroupBuyPeople(taShareActivity));
            responseBean.addSuccess(taShareActivity);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     *获取用户平均积分
     */
    @RequestMapping( value = "/admin/taShareActivity/avgScore", method = RequestMethod.GET)
    public ResponseBean taShareActivityAgvScore(HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try{
            Integer orgId = getOrgId(request);
            Integer sumPoints = taPersonService.sumPointsByOrgId(orgId);
            sumPoints = sumPoints == null ? 0 : sumPoints;
            QueryWrapper<TaPerson> taPersonWrapper = new QueryWrapper<>();
            taPersonWrapper.eq("org_id", orgId);
            Integer personNum = taPersonService.count(taPersonWrapper);
            TaShareActivity taShareActivity = new TaShareActivity();
            if (personNum == 0){
                taShareActivity.setAverageScore(0);
            }else{
                taShareActivity.setAverageScore(sumPoints/personNum);
            }

            responseBean.addSuccess(taShareActivity);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityAgvScore -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id结束拼团活动
     * @param id
     * @return
     */
    @RequestMapping(value="/admin/taShareActivity/finish/{id}",method= RequestMethod.PUT)
    public ResponseBean finishShareActicity(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaShareActivity taShareActivity = new TaShareActivity();
            //活动禁用启用 1启动0禁用
            taShareActivity.setStatus(1);
            //0：进行中 1：未开始 2：已结束
            taShareActivity.setActivityStatus(2);
            taShareActivity.setGroupActivityId(id);
            taShareRecordService.updateActivityProcessToEndByGroupActivityId(id);
            taShareChildRecordService.updateActivityProcessToEndByGroupActivityId(id);
            if (iTaShareActivityService.updateById(taShareActivity)){
                responseBean.addSuccess(taShareActivity);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @RequestMapping(value = "/admin/taShareActivity/send/{groupActivityId}", method = RequestMethod.PUT)
    public ResponseBean send(@PathVariable String groupActivityId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaShareActivity> taShareActivityQueryWrapper = new QueryWrapper<>();
        taShareActivityQueryWrapper.eq("group_activity_id", groupActivityId);
        TaShareActivity taShareActivity = iTaShareActivityService.getOne(taShareActivityQueryWrapper);
        taShareActivity.setStatus(1);
        taShareActivity.setOrgId(getOrgId(request));
        iTaShareActivityService.update(taShareActivity, taShareActivityQueryWrapper);
        return responseBean;
    }

    @RequestMapping(value = "/admin/taShareActivity/cancel/{groupActivityId}", method = RequestMethod.PUT)
    public ResponseBean cancel(@PathVariable String groupActivityId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaShareActivity> taShareActivityQueryWrapper = new QueryWrapper<>();
        taShareActivityQueryWrapper.eq("group_activity_id", groupActivityId);
        TaShareActivity dynamic = iTaShareActivityService.getOne(taShareActivityQueryWrapper);
        dynamic.setStatus(-1);
        dynamic.setOrgId(getOrgId(request));
        iTaShareActivityService.update(dynamic, taShareActivityQueryWrapper);
        // 设置为取消发布以后把轮播图和资讯设置为停用
        iExtendContentService.updateActivity(groupActivityId,"group",getOrgId(request));
        return responseBean;
    }

    /**
     * 置顶活动，首页推荐
     * @param taShareActivity
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/taShareActivity/weight" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicWeight(@RequestBody TaShareActivity taShareActivity, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        if (taShareActivity.getWeight() != null){
            taShareActivity.setWeight(taShareActivity.getWeight() == 0 ? 1 : 0);
        }
        if (taShareActivity.getSort() != null){
            taShareActivity.setSort(taShareActivity.getSort() == true ? false : true);
        }

        QueryWrapper<TaNews> newsQueryWrapper = new QueryWrapper<>();
        newsQueryWrapper.eq("group_activity_id", taShareActivity.getGroupActivityId());
        if (iTaShareActivityService.updateById(taShareActivity)){
            responseBean.addSuccess("成功");
        }else {
            responseBean.addError("失败");
        }
        return responseBean;
    }
    
    /**
     * 微信端根据id查询详情
     * @param groupActivityId  实体ID
     */
    @RequestMapping(value="/wx/taShareActivity/{groupActivityId}",method= RequestMethod.GET)
    @ReportCustomer(type = "group")
    public ResponseBean wxShareActivityGet(@PathVariable Integer groupActivityId,
                                           @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                           @RequestParam(value = "channelId", required = false) String channelId,
                                           @RequestParam(value = "sceneId", required = false) String sceneId,
                                           HttpServletRequest request,
                                           @RequestParam(value = "recordId",required = false) Integer recordId ){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        Map<String,Object> map = new HashMap<>();
        try {
            //活动详情
            TaShareActivity taShareActivity = iTaShareActivityService.getById(groupActivityId);
            //查看此活动已经完成的数量
            QueryWrapper<TaShareRecord> shareRecordQueryWrapper = new QueryWrapper<>();
            shareRecordQueryWrapper.eq("org_id",orgId);
            shareRecordQueryWrapper.eq("group_activity_id",taShareActivity.getGroupActivityId());
            shareRecordQueryWrapper.eq("status",CommConstant.STATUS_UNACCALIMED);
            //已经成功的拼团
            List<TaShareRecord> taShareRecordsList = taShareRecordService.list(shareRecordQueryWrapper);
            taShareActivity.setSuccessNum(taShareRecordsList.size());
            map.put("taShareActivity",taShareActivity);
            
            //发起者团长信息
            TaShareRecord taShareRecord = null;
             if (null != recordId){
                 taShareRecord = taShareRecordService.getById(recordId);
             }else {
                 QueryWrapper<TaShareRecord> recordQueryWrapper = new QueryWrapper<>();
                 recordQueryWrapper.eq("org_id",orgId);
                 recordQueryWrapper.eq("group_activity_id",taShareActivity.getGroupActivityId());
                 recordQueryWrapper.eq("person_id",person.getPersonId());
                 taShareRecord = taShareRecordService.getOne(recordQueryWrapper);
             }
            if (null != taShareRecord){
                //团长
                taShareActivity.setGroupStatus(CommConstant.HELP_STATUS_INITIATE);
                map.put("taShareRecord",taShareRecord);
        
                //团员
                QueryWrapper<TaShareChildRecord> childRecordQueryWrapper = new QueryWrapper<>();
                childRecordQueryWrapper.eq("org_id",orgId);
                childRecordQueryWrapper.eq("group_activity_id",taShareActivity.getGroupActivityId());
                childRecordQueryWrapper.eq("record_id",taShareRecord.getRecordId());
                List<TaShareChildRecord> shareChildRecordList = taShareChildRecordService.list(childRecordQueryWrapper);
                shareChildRecordList.forEach(e -> {
                    if (e.getPersonId().equals(person.getPersonId())){
                        map.put("isJoin",true);
                    }
                });
                map.put("shareChildRecordList",shareChildRecordList);
            }
    
            //获取海报信息
            QueryWrapper<TaPoster> posterQueryWrapper = new QueryWrapper<>();
            posterQueryWrapper.eq("target_type",CommConstant.GROUP_ACTIVITY);
            posterQueryWrapper.eq("target_id",groupActivityId);
            posterQueryWrapper.eq("org_id",orgId);
            List<TaPoster> postList = taPosterService.list(posterQueryWrapper);
            map.put("postList",postList);
    
            QueryWrapper<TdPosterTemplate> tdPosterTemplateQueryWrapper = new QueryWrapper<>();
            //tdPosterTemplateQueryWrapper.eq("org_id",orgId);
            tdPosterTemplateQueryWrapper.eq("status",CommConstant.STATUS_NORMAL);
            tdPosterTemplateQueryWrapper.eq("type",CommConstant.GROUP_ACTIVITY);
            List<TdPosterTemplate> posterTemplateList = tdPosterTemplateService.list(tdPosterTemplateQueryWrapper);
            map.put("posterTemplateList",posterTemplateList);
    
            //获取分享信息
            QueryWrapper<TaShareContent> taShareContentQueryWrapper = new QueryWrapper<>();
            taShareContentQueryWrapper.eq("share_content_type",CommConstant.GROUP_ACTIVITY);
            taShareContentQueryWrapper.eq("target_id",groupActivityId);
            taShareContentQueryWrapper.eq("org_id",orgId);
            List<TaShareContent> shareContentList = taShareContentService.list(taShareContentQueryWrapper);
            map.put("shareContentList",shareContentList);
            
            responseBean.addSuccess(map);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taShareActivityDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
}
