package com.huiju.estateagents.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
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.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.excel.HelpInitiateRecordSucceed;
import com.huiju.estateagents.excel.TaActivityDynamicEnlistExport;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.reportCustomerAop.ReportCustomer;
import com.huiju.estateagents.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huiju.estateagents.event.EventBus.EventType.ActivityCheckin;

/**
 * <p>
 * 项目动态表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-03-21
 */
@RestController
@RequestMapping("/api")
@Api(value = "项目活动", tags = "项目活动")
public class TaBuildingDynamicController extends BaseController {

    @Autowired
    private ITaBuildingDynamicService iBuildingDynamicService;

    @Autowired
    private TaBuildingMapper taBuildingMapper;

    @Autowired
    private ITaPersonService taPersonService;

    @Autowired
    private ITaSaveService taSaveService;

    @Autowired
    private ITaBuildingService iTaBuildingService;

    @Autowired
    private ITaRecommendCustomerService recommendCustomerService;

    @Autowired
    private TaActivityDynamicEnlistMapper taActivityDynamicEnlistMapper;

    @Autowired
    private TaSharePersonFromMapper taSharePersonFromMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private IMiniAppService miniAppService;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private TaMiniappQrcodeMapper taMiniappQrcodeMapper;
    
    @Autowired
    private ITaPointsRecordsService taPointsRecordsService;

    @Autowired
    private IExtendContentService iExtendContentService;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor editor = new CustomDateEditor(df, true);//true表示允许为空，false反之
        binder.registerCustomEditor(Date.class, editor);
    }
    
    @ApiOperation(value = "后台管理端查询项目活动列表", notes = "后台管理端查询项目活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "name", paramType = "query",value = "项目名称"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "cityId", paramType = "query",value = "城市id"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "title", paramType = "query",value = "标题"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "isEnlist", paramType = "query",value = "是否报名"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "time", paramType = "query",value = "日期")
    })
    @RequestMapping(value = "/admin/iBuildingDynamicList", method = RequestMethod.GET)
    public ResponseBean iBuildingDynamicList(@RequestParam("pageNum")Integer pageNum,
                                             @RequestParam("pageSize")Integer pageSize,
                                             @RequestParam(required = false)String name,
                                             @RequestParam(required = false)Integer cityId,
                                             @RequestParam(required = false)String buildingId,
                                             @RequestParam(required = false)String title,
                                             @RequestParam(required = false)String isEnlist,
                                             @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime time,
                                             @RequestParam(required = false)String activityStatus,HttpServletRequest request){
        ResponseBean  responseBean = iBuildingDynamicService.iBuildingDynamicList(pageNum,pageSize,name,buildingId,cityId,isEnlist,time,title,getOrgId(request),activityStatus,getTaPersonBuildingListByUserId(request));
        return responseBean;
    }

    @ApiOperation(value = "后台管理端查询项目活动列表", notes = "后台管理端查询项目活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "name", paramType = "query",value = "项目名称"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "cityId", paramType = "query",value = "城市id"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "title", paramType = "query",value = "标题"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "isEnlist", paramType = "query",value = "是否报名"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "time", paramType = "query",value = "日期")
    })
    @RequestMapping(value = "/admin/iBuildingDynamicSelected", method = RequestMethod.GET)
    public ResponseBean iBuildingDynamicSelectedList(@RequestParam("pageNum")Integer pageNum,
                                             @RequestParam("pageSize")Integer pageSize,
                                             @RequestParam(required = false)String name,
                                             @RequestParam(required = false)Integer cityId,
                                             @RequestParam(required = false)String buildingId,
                                             @RequestParam(required = false)String title,
                                             @RequestParam(required = false)String isEnlist,
                                             @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime time,
                                             @RequestParam(required = false)String activityStatus,HttpServletRequest request){
        ResponseBean  responseBean = iBuildingDynamicService.iBuildingDynamicSelectedList(pageNum,pageSize,name,buildingId,cityId,isEnlist,time,title,getOrgId(request),activityStatus,getTaPersonBuildingListByUserId(request));
        return responseBean;
    }

    @RequestMapping(value = "/admin/iBuildingDynamicSelectId/{id}", method = RequestMethod.GET)
    public ResponseBean iBuildingDynamicSelectId(@PathVariable(value = "id") String id, HttpSession session){
        ResponseBean  responseBean = iBuildingDynamicService.iBuildingDynamicSelectId(id);
        return responseBean;
    }

    /**
     * 活动列表
     * @param pageNumber
     * @param pageSize
     * @param request
     * @return
     */
    @ApiOperation(value = "微信端查询项目活动列表", notes = "微信端查询项目活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "cityId", paramType = "query",value = "城市id"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id"),
            @ApiImplicitParam(dataTypeClass = Boolean.class, name = "mine", paramType = "query")
    })
    @RequestMapping(value = "/wx/buildingDynamiceList", method = RequestMethod.GET)
    public ResponseBean wxBuildingDynamiceList(@RequestParam(value = "buildingId", required = false)String buildingId,
                                               @RequestParam(value = "pageNumber",defaultValue = "1")Integer pageNumber,
                                               @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                               @RequestParam(defaultValue = "false" )boolean mine,
                                               @RequestParam(value = "cityId", required = false)Integer cityId,
                                               HttpServletRequest request){
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        ResponseBean  responseBean = new ResponseBean();
        if(mine){
            List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
            if (null == taPersons || taPersons.size() != 1) {
                return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = taPersons.get(0);
            responseBean.addSuccess(iBuildingDynamicService.getJoinedActivity(pageNumber,pageSize,"",person,orgId));
        }else {
            responseBean = iBuildingDynamicService.getWxBuildingDynamiceList(pageNumber,pageSize,buildingId,openid,cityId,orgId);
        }

        return responseBean;
    }
    
    @ApiOperation(value = "微信端查询收藏项目活动列表", notes = "微信端查询收藏项目活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id")
    })
    @RequestMapping(value = "/wx/save/buildingDynamiceList", method = RequestMethod.GET)
    public ResponseBean wxSaveBuildingDynamiceList(@RequestParam(value = "buildingId", required = false)String buildingId,
                                               @RequestParam(value = "pageNumber",defaultValue = "1")Integer pageNumber,
                                               @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                               HttpServletRequest request){
        String openid = getOpenId(request);
        ResponseBean  responseBean = new ResponseBean();
            List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
            if (null == taPersons || taPersons.size() != 1) {
                return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = taPersons.get(0);
            QueryWrapper<TaSave> saveQueryWrapper = new QueryWrapper<>();
            saveQueryWrapper.eq("person_id",person.getPersonId());
            saveQueryWrapper.eq("tagert_type", CommConstant.FAVOR_ACTIVITY);
            List<TaSave> saveList = taSaveService.list(saveQueryWrapper);
            if(saveList.size()>0){
                List<String> ids = new ArrayList<>();
                for(int i = 0; i<saveList.size();i++){
                    ids.add(saveList.get(i).getSavedTarget());
                }
                IPage<TaBuildingDynamic> page = new Page<>(pageNumber, pageSize);
                QueryWrapper<TaBuildingDynamic> buildingDynamicQueryWrapper = new QueryWrapper<>();
                buildingDynamicQueryWrapper.in("dynamic_id",ids);
                IPage<TaBuildingDynamic> buildingDynamicIPage = iBuildingDynamicService.page(page,buildingDynamicQueryWrapper);
    
                //查询是否报名了普通活动
                QueryWrapper<TaActivityDynamicEnlist> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("org_id",getOrgId(request));
                queryWrapper.eq("person_id",person.getPersonId());
                List<TaActivityDynamicEnlist> taActivityDynamicEnlists = taActivityDynamicEnlistMapper.selectList(queryWrapper);
                
                for(int j=0;j<buildingDynamicIPage.getRecords().size();j++){
                    iBuildingDynamicService.setExtendInfo(buildingDynamicIPage.getRecords().get(j),person);
                    
                    //是否已参与状态
                    TaBuildingDynamic taBuildingDynamic = buildingDynamicIPage.getRecords().get(j);
                    taActivityDynamicEnlists.forEach(dynamic -> {
                        if (taBuildingDynamic.getDynamicId().equals(dynamic.getDynamicId())){
                            taBuildingDynamic.setActivityStatus(CommConstant.ACTIVITY_STATUS_PARTNER);
                        }
                    });
                }
                responseBean.addSuccess(buildingDynamicIPage);
            }else {
                responseBean.addSuccess("暂无收藏活动");
            }


        return responseBean;
    }

    /**
     * 活动详情
     * @param dynamicId
     * @return
     */
    @ApiOperation(value = "微信端查询活动详情", notes = "微信端查询活动详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "dynamicId", paramType = "path",value = "活动ID")
    })
    @RequestMapping(value = "/wx/buildingDynamiceInfo/{dynamicId}", method = RequestMethod.GET)
    @ReportCustomer(type = "activity")
    public ResponseBean iBuildingDynamicInfo(@PathVariable(value = "dynamicId") String dynamicId,
                                             @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                             @RequestParam(value = "channelId", required = false) String channelId,
                                             @RequestParam(value = "sceneId", required = false) String sceneId,
                                             HttpServletRequest request){
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        String buildingId = "";
        ResponseBean  responseBean = iBuildingDynamicService.getWxBuildingDynamiceInfo(dynamicId,buildingId,openid, orgId);
        return responseBean;
    }

    /**
     * 活动详情
     * @param dynamicId
     * @return
     */
    @ApiOperation(value = "微信端查询活报名动详情", notes = "微信端查询活报名动详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "dynamicId", paramType = "path",value = "活动ID")
    })
    @RequestMapping(value = "/wx/buildingDynamiceEnlistInfo/{dynamicId}", method = RequestMethod.GET)
    public ResponseBean iBuildingDynamicEnlistInfo(@PathVariable(value = "dynamicId") String dynamicId,
                                             HttpServletRequest request){
        ResponseBean  responseBean = new ResponseBean();
                String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return responseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        Integer orgId = getOrgId(request);
        QueryWrapper<TaActivityDynamicEnlist>enlistQueryWrapper = new QueryWrapper<>();
        enlistQueryWrapper.eq("dynamic_id",dynamicId);
        enlistQueryWrapper.eq("person_id",person.getPersonId());
        enlistQueryWrapper.eq("org_id",orgId);
        List <TaActivityDynamicEnlist> enlists = taActivityDynamicEnlistMapper.selectList(enlistQueryWrapper);
        TaBuildingDynamic buildingDynamic = iBuildingDynamicService.getById(dynamicId);
        Map<String,Object>data = new HashMap<>();
        TaActivityDynamicEnlist enlist = new TaActivityDynamicEnlist();
        if(enlists.size()>0){
            enlist = enlists.get(0);
        }
        data.put("enlist",enlist);
        data.put("dynamic",buildingDynamic);
        data.put("person",person);
        responseBean.addSuccess(data);
        return responseBean;
    }


    /**
     * 活动签到
     * @param enlistId
     * @return
     */
    @ApiOperation(value = "微信端活动签到", notes = "微信端活动签到")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "enlistId", paramType = "path",value = "活动报名ID")
    })
    @RequestMapping(value = "/wx/buildingDynamicCheckin/{enlistId}", method = RequestMethod.PUT)
    public ResponseBean iBuildingDynamicCheckin(@PathVariable(value = "enlistId") String enlistId,
                                             HttpServletRequest request){
        ResponseBean  responseBean =new ResponseBean();
       TaActivityDynamicEnlist enlist = taActivityDynamicEnlistMapper.selectById(enlistId);
       try{
           if(null != enlist){
               Integer tempIsCheckin = enlist.getIsCheckin();
               enlist.setIsCheckin(CommConstant.STATUS_NORMAL);
               if(taActivityDynamicEnlistMapper.updateById(enlist)>0){
                   System.out.println("验证1");
                   if (tempIsCheckin.equals(CommConstant.STATUS_UNACCALIMED)){
                       System.out.println("验证2");
                       enlist.setEnlistId(Integer.valueOf(enlistId));
                       applicationContext.publishEvent(new EventBus(enlist,ActivityCheckin,getOrgId(request)));
                       QueryWrapper<TaRecommendCustomer> customerQueryWrapper = new QueryWrapper<>();
                       customerQueryWrapper.eq("person_id",enlist.getPersonId());
                       customerQueryWrapper.eq("building_id",enlist.getBuildingId());
                       TaRecommendCustomer recommendCustomer = recommendCustomerService.getOne(customerQueryWrapper);
                       if (null != recommendCustomer&&recommendCustomer.getStatus().equals(CommConstant.CUSTOMER_REPORT)){
                           System.out.println("验证3");
                           recommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
                           recommendCustomer.setArrivalDate(LocalDateTime.now());
                           recommendCustomerService.updateById(recommendCustomer);
                       }
                       Integer rulePoints = taPointsRecordsService.getRulePoints(CommConstant.POINTS_CHANGE_ACTIVITY_CHECKIN, getOrgId(request));
                       enlist.setAddPoints(rulePoints);
                       responseBean.addSuccess(enlist);
                   }else {
                       responseBean.addError("您已签到过");
                   }
               }else {
                   responseBean.addError("签到失败");
               }
           }
       }catch (Exception e){
           e.printStackTrace();
           responseBean.addError("签到异常");
       }
        return responseBean;
    }

    /**
     * 添加活动报名
     * @param taActivityDynamicEnlist
     * @param request
     * @return
     */
    @ApiOperation(value = "微信端添加活动报名", notes = "微信端添加活动报名")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaActivityDynamicEnlist", name = "taActivityDynamicEnlist", paramType = "body",value = "")
    })
    @RequestMapping(value = "/wx/activityDynamicEnlistAdd", method = RequestMethod.POST)
    public ResponseBean taActivityDynamicEnlist(@RequestBody TaActivityDynamicEnlist taActivityDynamicEnlist,
                                                HttpServletRequest request){
        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);
        }
        TaBuildingDynamic buildingDynamic = iBuildingDynamicService.getById(taActivityDynamicEnlist.getDynamicId());
        // TODO 看代码里面是 is_enlist = 1 才是允许报名
        if (buildingDynamic.getIsEnlist().intValue() != 1) {
            return ResponseBean.error("活动不允许报名", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 携带的报名人数(是已经包括自己了)，不能超过活动总人数

        // 检验 个人最大报名人数
        if (taActivityDynamicEnlist.getAttendNum() > buildingDynamic.getMaxEnlistByPerson().intValue()) {
            return ResponseBean.error("报名失败，超过活动报名的个人最大报名人数！", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 当前活动已报名的总人数
        Integer enlistCount = taActivityDynamicEnlistMapper.selectEnlistCount(taActivityDynamicEnlist.getDynamicId(), orgId);
        if ((enlistCount + taActivityDynamicEnlist.getAttendNum()) > buildingDynamic.getPersonNum().intValue()) {
            return ResponseBean.error("报名失败，超过活动报名的最大人数！", ResponseBean.ERROR_UNAVAILABLE);
        }

        TaPerson person = taPersons.get(0);

        // 反向更新TaSharePersonFrom 的 status
        QueryWrapper<TaSharePersonFrom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("target_id", taActivityDynamicEnlist.getDynamicId());
        queryWrapper.eq("target_type", "dynamic_share");
        queryWrapper.eq("person_id", person.getPersonId());
        queryWrapper.orderByDesc("create_date");
        queryWrapper.last("limit 1");
        TaSharePersonFrom taSharePersonFrom = taSharePersonFromMapper.selectOne(queryWrapper);
        if (null != taSharePersonFrom) {
            taSharePersonFrom.setStatus(1);
            taSharePersonFromMapper.updateById(taSharePersonFrom);
        }

        taActivityDynamicEnlist.setPersonId(person.getPersonId());
        taActivityDynamicEnlist.setOrgId(orgId);
        taActivityDynamicEnlist.setIsCheckin(CommConstant.STATUS_UNACCALIMED);
        ResponseBean  responseBean = iBuildingDynamicService.taActivityDynamicEnlistAdd(taActivityDynamicEnlist, orgId);
        return responseBean;
    }
    
    
    @ApiOperation(value = "后端活动添加", notes = "后端活动添加")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaBuildingDynamic", name = "parameter", paramType = "body",value = "活动详细信息")
    })
    @RequestMapping(value = "/admin/buildingDynamic/add" ,method =RequestMethod.POST)
    public  ResponseBean buildingDynamicAdd(@RequestBody String parameter,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaBuildingDynamic dynamic = JSONObject.parseObject(parameter, TaBuildingDynamic.class);
        dynamic.setOrgId(getOrgId(request));
        Integer cityId = iTaBuildingService.getCityById(dynamic.getBuildingId());
        dynamic.setCityId(cityId);
        //发布状态 1展示
        dynamic.setStatus(1);
        //活动状态，如果不需要报名则直接置为进行中
        dynamic.setActivityStatus(1);
        dynamic.setIsEnlist(1);
        //3.5.1版本去除是否需要报名
//        if (dynamic.getIsEnlist() == 0){
//            dynamic.setActivityStatus(0);
//        }
        dynamic.setPublishDate(LocalDateTime.now());
        dynamic.setCreateDate(LocalDateTime.now());

        //判断报名时间是否在活动时间之内
        if (dynamic.getEndDate().isBefore(dynamic.getEnlistEnd())){
            responseBean.addError("报名时间应在活动结束时间之前");
            return responseBean;
        }

        //3.5.2.2版本去除权重验重
//        Integer heavyCount = iTaBuildingService.countNumByHeavy(dynamic.getHeavy(), dynamic.getDynamicId());
//        if (heavyCount != 0){
//            responseBean.addError("权重已存在，请重新编辑");
//            return responseBean;
//        }
         // 根据ORGID查询当前小程序表的miniapp_id
        QueryWrapper<TaMiniapp> taMiniappQuery= new QueryWrapper<>();
        taMiniappQuery.eq("org_id",getOrgId(request));
        TaMiniapp taMiniapp = taMiniappMapper.selectOne(taMiniappQuery);
        iBuildingDynamicService.save(dynamic);
        // 生成二维码
        ResponseBean taMiniappQrcode = miniAppService.getQrCode(CommConstant.ACTIVITY_QRCODE.replace("#0",dynamic.getDynamicId()).replace("#1","activity"),taMiniapp.getMiniappId());
        dynamic.setQrCode(String.valueOf(taMiniappQrcode.getData()));
        iBuildingDynamicService.updateById(dynamic);
        responseBean.addSuccess(dynamic);
        return responseBean;
    }
    
    @ApiOperation(value = "后端活动更新", notes = "后端微信活动更新")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaBuildingDynamic", name = "parameter", paramType = "body",value = "活动详细信息")
    })
    @RequestMapping(value = "/admin/buildingDynamic/update" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicUpdate(@RequestBody String parameter,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaBuildingDynamic dynamic = JSONObject.parseObject(parameter, TaBuildingDynamic.class);
        dynamic.setOrgId(getOrgId(request));
        QueryWrapper<TaBuildingDynamic> buildingDynamicQueryWrapper = new QueryWrapper<>();
        Integer cityId = iTaBuildingService.getCityById(dynamic.getBuildingId());
        dynamic.setCityId(cityId);
        if (dynamic.getEnlistStart() != null && LocalDateTime.now().isBefore(dynamic.getEnlistStart())){
            dynamic.setActivityStatus(1);
        }
        if (dynamic.getEnlistEnd() != null && LocalDateTime.now().isAfter(dynamic.getEnlistEnd())){
            dynamic.setActivityStatus(2);
        }

        //判断报名时间是否在活动时间之内
        if (dynamic.getEndDate().isBefore(dynamic.getEnlistEnd())){
            responseBean.addError("报名时间应在活动结束时间之前");
            return responseBean;
        }

        //3.5.2.2版本去除验重功能
//        Integer heavyCount = iTaBuildingService.countNumByHeavy(dynamic.getHeavy(), dynamic.getDynamicId());
//        if (heavyCount != 0){
//            responseBean.addError("权重已存在，请重新编辑");
//            return responseBean;
//        }
        buildingDynamicQueryWrapper.eq("dynamic_id", dynamic.getDynamicId());
        iBuildingDynamicService.update(dynamic, buildingDynamicQueryWrapper);
        return responseBean;
    }
    
    @ApiOperation(value = "后端置顶", notes = "后端置顶")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "query",value = "活动ID"),
            @ApiImplicitParam(dataType = "Integer", name = "weight", paramType = "query",value = "权重")
    })
    @RequestMapping(value = "/admin/buildingDynamic/weight" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicWeight(@RequestParam String dynamicId,@RequestParam Integer weight,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaBuildingDynamic dynamic = iBuildingDynamicService.getById(dynamicId);
        dynamic.setWeight(weight);
        dynamic.setOrgId(getOrgId(request));
        QueryWrapper<TaBuildingDynamic> dynamicQueryWrapper = new QueryWrapper<>();
        dynamicQueryWrapper.eq("dynamic_id",dynamic);
        if (iBuildingDynamicService.updateById(dynamic)){
            responseBean.addSuccess("成功");
        } else {
            responseBean.addError("失败");
        }
        return responseBean;
    }

    @ApiOperation(value = "活动推首页", notes = "活动推首页")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "query",value = "活动ID"),
            @ApiImplicitParam(dataType = "Integer", name = "home", paramType = "query",value = "首页标志")
    })
    @RequestMapping(value = "/admin/buildingDynamic/home" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicHome(@RequestParam String dynamicId,@RequestParam Integer home,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaBuildingDynamic dynamic = iBuildingDynamicService.getById(dynamicId);
        dynamic.setHome(home);
        dynamic.setOrgId(getOrgId(request));
        QueryWrapper<TaBuildingDynamic> dynamicQueryWrapper = new QueryWrapper<>();
        dynamicQueryWrapper.eq("dynamic_id",dynamic);
        if (iBuildingDynamicService.updateById(dynamic)){
            responseBean.addSuccess("成功");
        } else {
            responseBean.addError("失败");
        }
        return responseBean;
    }
    
    
    @ApiOperation(value = "后端删除", notes = "后端删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", paramType = "query",value = "活动ID")
    })
    @RequestMapping(value = "/admin/buildingDynamic/delete", method = RequestMethod.DELETE)
    public ResponseBean buildingDynamicdelect(@RequestParam(value = "id",required = false)String id) {
        ResponseBean responseBean = iBuildingDynamicService.buildingDynamicDelete(id);
        return responseBean;
    }
    
    @ApiOperation(value = "后端发布活动", notes = "后端发布活动")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "path",value = "活动ID")
    })
    @RequestMapping(value = "/admin/buildingDynamic/send/{dynamicId}", method = RequestMethod.PUT)
    public ResponseBean send(@PathVariable String dynamicId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaBuildingDynamic> dynamicQueryWrapper = new QueryWrapper<>();
        dynamicQueryWrapper.eq("dynamic_id", dynamicId);
        TaBuildingDynamic dynamic = iBuildingDynamicService.getOne(dynamicQueryWrapper);
        dynamic.setStatus(1);
        dynamic.setPublishDate(LocalDateTime.now());
        dynamic.setOrgId(getOrgId(request));
        iBuildingDynamicService.update(dynamic, dynamicQueryWrapper);
        return responseBean;
    }
    
    @ApiOperation(value = "后端取消活动", notes = "后端取消活动")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "path",value = "活动ID")
    })
    @RequestMapping(value = "/admin/buildingDynamic/cancel/{dynamicId}", method = RequestMethod.PUT)
    public ResponseBean cancel(@PathVariable String dynamicId, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaBuildingDynamic> dynamicQueryWrapper = new QueryWrapper<>();
        dynamicQueryWrapper.eq("dynamic_id", dynamicId);
        TaBuildingDynamic dynamic = iBuildingDynamicService.getOne(dynamicQueryWrapper);
        dynamic.setStatus(0);
        // 设置为取消发布以后把轮播图和资讯设置为停用
        iExtendContentService.updateActivity(dynamicId,"activity",getOrgId(request));
        iBuildingDynamicService.update(dynamic, dynamicQueryWrapper);
        return responseBean;
    }
    
    @ApiOperation(value = "后端活动详情", notes = "后端活动详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "query",value = "活动ID")
    })
    @RequestMapping(value = "/admin/buildingDynamic/Details", method = RequestMethod.GET)
    public ResponseBean buildingDynamicDetails(@RequestParam("dynamicId")String dynamicId) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaBuildingDynamic> dynamicQueryWrapper = new QueryWrapper<>();
        dynamicQueryWrapper.eq("dynamic_id", dynamicId);
        TaBuildingDynamic dynamic = iBuildingDynamicService.getOne(dynamicQueryWrapper);
        TaBuilding building= taBuildingMapper.selectBuilding(dynamic.getBuildingId());

        if (null != building) {
            dynamic.setBuildingName(building.getBuildingName());
        }

        responseBean.addSuccess(dynamic);
        return responseBean;
    }
    
    @ApiOperation(value = "后端报名列表", notes = "后端报名列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataType = "String", name = "dynamicId", paramType = "query",value = "活动ID"),
            @ApiImplicitParam(dataType = "String", name = "isCheckin", paramType = "query",value = "0未签到1签到"),
            @ApiImplicitParam(dataType = "String", name = "name", paramType = "query",value = "用户姓名"),
            @ApiImplicitParam(dataType = "String", name = "phone", paramType = "query",value = "手机号")
    })
    @RequestMapping(value = "/admin/SignList", method = RequestMethod.GET)
    public ResponseBean getSignList(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                    @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                    @RequestParam(value = "dynamicId",required = false)String dynamicId,
                                    @RequestParam(value = "isCheckin",required = false)String isCheckin,
                                    @RequestParam(value = "name",required = false)String name,
                                    @RequestParam(value = "phone",required = false)String phone,
                                    HttpServletRequest request) {
        Page<TaActivityDynamicEnlist> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        ResponseBean signList = iBuildingDynamicService.signList(page,dynamicId, getOrgId(request),isCheckin,name,phone);

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", signList);
        map.put("total", page.getTotal());
        map.put("pageNum", page.getCurrent());
        map.put("pageSize", page.getSize());
        return ResponseBean.success(map);
    }
    
    @ApiOperation(value = "后端结束活动", notes = "后端结束活动")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "parameter", paramType = "body",value = "活动ID dynamicId 和 top")
    })
    @RequestMapping(value = "/admin/buildingDynamic/finish" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicFinish(@RequestBody String parameter) {
        ResponseBean responseBean = new ResponseBean();
        JSONObject object = JSONObject.parseObject(parameter);
        String dynamicId = object.getString("dynamicId");
        String top = object.getString("top");
        QueryWrapper<TaBuildingDynamic> taBuildingDynamic = new QueryWrapper<>();
        taBuildingDynamic.eq("dynamic_id", dynamicId);
        TaBuildingDynamic dynamic = iBuildingDynamicService.getOne(taBuildingDynamic);
        if ("1".equals(top)) {
            dynamic.setCreateDate(LocalDateTime.now());
        } else {
            dynamic.setActivityStatus(2);
        }
        iBuildingDynamicService.update(dynamic, taBuildingDynamic);
        responseBean.addSuccess("成功");
        return responseBean;
    }

    /**
     * 报名记录导出
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/admin/activityDynamicEnlist/export")
    public void activityDynamicEnlistExport(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestParam(value = "dynamicId",required = false)String dynamicId,
                                      @RequestParam(value = "isCheckin",required = false)String isCheckin,
                                      @RequestParam(value = "name",required = false)String name,
                                      @RequestParam(value = "phone",required = false)String phone) throws IOException {
        //        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=助力活动发起人.xlsx");

        Integer orgId = getOrgId(request);

        Integer pageCode = 0;
        Integer pageSize = 100;
        // 总页数
        Integer pageCount = 0;

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), TaActivityDynamicEnlistExport.class).registerWriteHandler(new CustomCellWriteHandler()).build();
            // 设置 sheet, 同一个sheet只需要设置一次
            WriteSheet writeSheet = EasyExcel.writerSheet("报名记录").build();
            Integer count = iBuildingDynamicService.getTaActivityDynamicEnlist(dynamicId,isCheckin,name,phone);
            pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
            List<HelpInitiateRecordSucceed> publicList = null;
            do {
                publicList = iBuildingDynamicService.getTaActivityDynamicEnlistExport(pageCode * pageSize, pageSize,dynamicId,isCheckin,name,phone,getOrgId(request));
                excelWriter.write(publicList, writeSheet);

                pageCode++;
            } while (pageCode <= pageCount);

            // finish 会帮忙关闭流
            excelWriter.finish();
        }



}

