package com.huiju.estateagents.controller;

import ch.qos.logback.core.status.StatusUtil;
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.mapper.TaBuildingProjectTypeMapper;
import com.huiju.estateagents.service.*;
import org.apache.commons.collections.map.HashedMap;
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.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-07-23
 */
@RestController
@RequestMapping("/api")
public class TaPersonVisitRecordController extends BaseController {

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

    @Autowired
    public ITaPersonVisitRecordService iTaPersonVisitRecordService;
    @Autowired
    public ITaPersonService taPersonService;
    @Autowired
    public ITaEventPropertiesService taEventPropertiesService;
    @Autowired
    public ITaBuildingIntentionService buildingIntentionService;
    @Autowired
    public ITaPersonIntentionRecordService personIntentionRecordService;
    @Autowired
    public ITaBuildingService buildingService;
    @Autowired
    private ITaRecommendCustomerService taRecommendCustomerService;
    @Autowired
    public ITaPersonFromRecordService iTaPersonFromRecordService;
    @Autowired
    private TaBuildingProjectTypeMapper taBuildingProjectTypeMapper;


    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/taPersonVisitRecord", method = RequestMethod.GET)
    public ResponseBean taPersonVisitRecordList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaPersonVisitRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.page(pg, queryWrapper);
            return ResponseBean.success(result);
        } catch (Exception e) {
            logger.error("taPersonVisitRecordList -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 保存对象--埋点数据保存
     *
     * @param taPersonVisitRecord 实体对象
     * @return
     */
    @RequestMapping(value = "/wx/taPersonVisitRecord", method = RequestMethod.POST)
    public ResponseBean taPersonVisitRecordAdd(@RequestBody TaPersonVisitRecord taPersonVisitRecord, HttpServletRequest request) {
        Integer orgId = getOrgId(request);
        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);

        taPersonVisitRecord.setActivity(taPersonVisitRecord.getPropertyName());
        taPersonVisitRecord.setOrgId(String.valueOf(orgId));
        taPersonVisitRecord.setPersonId(person.getPersonId());

        return iTaPersonVisitRecordService.newRecord(taPersonVisitRecord, person);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/taPersonVisitRecord/{id}", method = RequestMethod.DELETE)
    public ResponseBean taPersonVisitRecordDelete(@PathVariable Integer id) {
        try {
            if (iTaPersonVisitRecordService.removeById(id)) {
                return ResponseBean.success("success");
            } else {
                return ResponseBean.error("删除失败", ResponseBean.ERROR_UNAVAILABLE);
            }
        } catch (Exception e) {
            logger.error("taPersonVisitRecordDelete -=- {}", e.toString());
            return ResponseBean.error("保存失败" + e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 修改对象
     *
     * @param id 实体ID
     * @return
     */
    @RequestMapping(value = "/wx/taPersonVisitRecord/{id}", method = RequestMethod.PUT)
    public ResponseBean taPersonVisitRecordUpdate(@PathVariable Integer id) {
        TaPersonVisitRecord taPersonVisitRecord = iTaPersonVisitRecordService.getById(id);
        if (null == taPersonVisitRecord) {
            return ResponseBean.error("更新失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        taPersonVisitRecord.setLeaveTime(LocalDateTime.now());
        taPersonVisitRecord.setRecordId(id);
        Long duation = taPersonVisitRecord.getLeaveTime().atZone(ZoneOffset.UTC).toEpochSecond() - taPersonVisitRecord.getVisitTime().atZone(ZoneOffset.UTC).toEpochSecond();
        taPersonVisitRecord.setVisitDuration(duation.intValue());
        try {
            if (iTaPersonVisitRecordService.updateById(taPersonVisitRecord)) {
                return ResponseBean.success(taPersonVisitRecord);
            } else {
                return ResponseBean.error("更新失败", ResponseBean.ERROR_UNAVAILABLE);
            }
        } catch (Exception e) {
            logger.error("taPersonVisitRecordUpdate -=- {}", e.toString());
            return ResponseBean.error("更新失败" + e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/taPersonVisitRecord/{id}", method = RequestMethod.GET)
    public ResponseBean taPersonVisitRecordGet(@PathVariable Integer id) {
        try {
            return ResponseBean.success(iTaPersonVisitRecordService.getById(id));
        } catch (Exception e) {
            logger.error("taPersonVisitRecordDelete -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 盘客工具分页获取访问记录
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/wx/taPersonVisitRecord", method = RequestMethod.GET)
    public ResponseBean wxPersonVisitRecordList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "customerId") String customerId) {
        try {
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.getPersonVisitRecordList(pg, customerId);
            return ResponseBean.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPersonVisitRecordList -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @RequestMapping(value = "/admin/taDrainageVisitRecord", method = RequestMethod.GET)
    public ResponseBean drainageVisitRecordList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "activityName", required = false) String activityName,
                                                @RequestParam(value = "buildingId", required = false) String buildingId,
                                                @RequestParam(value = "shareName", required = false) String shareName,
                                                @RequestParam(value = "shareTel", required = false) String shareTel,
                                                @RequestParam(value = "eventType", required = false) String eventType,
                                                @RequestParam(value = "personType", required = false) String personType,
                                                HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.getDrainageVisitRecord(pg, getOrgId(request), activityName, eventType, shareName, shareTel, buildingId, personType, getTaPersonBuildingListByUserId(request));
            responseBean.addSuccess(result);
            return responseBean;
        } catch (Exception e) {
            logger.error("drainageVisitRecord -=- {}", e.toString());
        }
        return responseBean;
    }

    /**
     * 个人中心访客记录分页查询
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/wx/visitRecord", method = RequestMethod.GET)
    public ResponseBean getWxVisitRecordList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             @RequestParam(value = "userId") Integer userId, HttpServletRequest request) {
        try {
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.getWxVisitRecordList(pg, userId, getOrgId(request));
            return ResponseBean.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPersonVisitRecordList -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 个人中心访客记录单个人员的所有活动
     *
     * @return
     */
    @RequestMapping(value = "/wx/visitRecord/activity", method = RequestMethod.GET)
    public ResponseBean wxVisitRecordList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                          @RequestParam(value = "userId") Integer userId,
                                          @RequestParam(value = "personId") String personId,
                                          HttpServletRequest request) {
        try {
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.getWxVisitRecordActivityList(pg, userId, personId, getOrgId(request));
            return ResponseBean.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPersonVisitRecordList -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 个人中心访客记录分页查询
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/wx/activityVisitRecord", method = RequestMethod.GET)
    public ResponseBean wxPersonActivityVisitRecordList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                        @RequestParam(value = "personId", required = false) String personId,
                                                        @RequestParam(value = "userId", required = false) Integer userId,
                                                        @RequestParam(value = "targetId") String targetId,
                                                        @RequestParam(value = "eventType") String eventType,
                                                        HttpServletRequest request) {
        try {
            QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
            if (userId == null){
                taPersonQueryWrapper.eq("person_id", personId);
            }
            if (personId == null){
                taPersonQueryWrapper.eq("user_id", userId);
            }
            TaPerson taPerson = taPersonService.getOne(taPersonQueryWrapper);
            //使用分页插件
            IPage<TaPersonVisitRecord> pg = new Page<>(pageNumber, pageSize);
            IPage<TaPersonVisitRecord> result = iTaPersonVisitRecordService.getWxActivityVisitRecordList(pg, taPerson.getPersonId(), getOrgId(request), targetId, eventType);
            return ResponseBean.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taPersonVisitRecordList -=- {}", e.toString());
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 置业顾问分享项目、活动、资讯、助力、拼团信息
     *
     * @param pageNumber
     * @param pageSize
     * @param personId
     * @param request
     * @return
     */
    @RequestMapping(value = "/wx/shareRecords", method = RequestMethod.GET)
    public ResponseBean wxShareRecordsByUserId(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                               @RequestParam(value = "personId", required = false) String personId,
                                               @RequestParam(value = "userId", required = false) Integer userId,
                                               HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        if (personId == null && userId == null) {
            return responseBean;
        }
        //使用分页插件
        IPage<TaConsultantInfo> pg = new Page<>(pageNumber, pageSize);
        QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
        if (userId == null){
            taPersonQueryWrapper.eq("person_id", personId);
        }
        if (personId == null){
            taPersonQueryWrapper.eq("user_id", userId);
        }
        TaPerson taPerson = taPersonService.getOne(taPersonQueryWrapper);
        IPage<TaConsultantInfo> result = iTaPersonVisitRecordService.getConsultantShareInfoList(pg, taPerson.getPersonId());

        List<TaConsultantInfo> taConsultantInfos = result.getRecords();
        taConsultantInfos.forEach(e -> {
            Integer shareNum = iTaPersonVisitRecordService.countShareNumByEventType(getOrgId(request), e.getTargetId(), taPerson.getUserId(), taPerson.getPersonId(), (CommConstant.FAVOR_PROJECT.equals(e.getEventType()) ? "building" : CommConstant.FAVOR_ACTIVITY.equals(e.getEventType()) ? "dynamic" : e.getEventType()) + "_share");
            switch (e.getEventType()) {
                case CommConstant.FAVOR_ACTIVITY:
                    e.setActivityShareNum(shareNum);
                    break;
                case CommConstant.POINTS_CHANGE_HELP:
                    e.setHelpActivityShareNum(shareNum);
                    break;
                case CommConstant.POINTS_CHANGE_GROUP:
                    e.setGroupActivityShareNum(shareNum);
                    break;
                case CommConstant.CAROUSEL_NEWS:
                    e.setNewsNum(shareNum);
                    break;
                case CommConstant.FAVOR_PROJECT:
                    e.setBuildingNum(shareNum);
                    break;
                case CommConstant.EVENT_H5:
                    e.setDrainageShareNum(shareNum);
                    break;
                case CommConstant.HOUSE:
                    e.setHouseShareNum(shareNum);
                    break;
                case CommConstant.LIVE:
                    e.setLiveShareNum(shareNum);
                    break;
            }
        });
        result.setRecords(taConsultantInfos);
        return ResponseBean.success(result);
    }
}
