package com.bs.df.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.bs.common.annotation.Anonymous;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.ServletUtils;
import com.bs.df.domain.DfOrder;
import com.bs.df.domain.DfUserBroker;
import com.bs.df.mapper.DfBizClueMapper;
import com.bs.df.service.IDfUserBrokerService;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.df.domain.DfBizClue;
import com.bs.df.service.IDfBizClueService;
import javax.annotation.Resource;

/**
 * 业务线索Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "业务线索")
@RestController
@RequestMapping("/biz/clue")
public class DfBizClueController extends BaseController {
    @Resource
    private IDfBizClueService dfBizClueService;
    @Resource
    private DfBizClueMapper dfBizClueMapper;
    @Resource
    private ISysUserService userService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private IDfUserBrokerService dfUserBrokerService;
    /**
     * 分页查询业务线索列表
     */
    @ApiOperation("分页查询业务线索列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfBizClue dfBizClue) {
        startPage();
        LambdaQueryWrapper<DfBizClue> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBizClue);
        queryWrapper.orderByDesc(DfBizClue::getBrowseTime);
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (!admin) {
            SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
            if (!sysUser.getDeptId().equals(-1L)) {
                SysUser byId = userService.getById(SecurityUtils.getUserId());
                if ("jj".equals(byId.getUserType())) {
                    queryWrapper.eq(DfBizClue::getUserId,SecurityUtils.getUserId());
                }
            }
        }
        List<DfBizClue> list = dfBizClueService.list(queryWrapper);
        for (DfBizClue clue : list) {
            if (Validator.isNotEmpty(clue.getUserName())) {
                clue.setNickName(clue.getUserName());
            }
        }
        return getDataTable(list);
    }



    /**
     * 分页查询业务线索数量列表
     */
    @ApiOperation("分页查询业务线索数量列表")
    @GetMapping("/getVisitsNum")
    public TableDataInfo getVisitsNum(DfBizClue dfBizClue) {
//        startPage();
        //condition(queryWrapper,dfBizClue);
        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        LambdaQueryWrapper<DfBizClue> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DfBizClue::getDataType,dfBizClue.getDataType());
        //传入hasOrder参数为1时，查询出存在orderId的数据
        SysUser sysUser = sysUserMapper.selectById(getUserId());
        if (!sysUser.getDeptId().equals(-1L)) {
            if (Validator.isNotEmpty(dfBizClue.getHasOrder())) {
                queryWrapper.isNotNull(DfBizClue::getOrderId);
                if (Validator.isNotEmpty(dfBizClue.getBrokerId())) {
                    queryWrapper.eq(DfBizClue::getShareUser,dfBizClue.getBrokerId());
                } else {
                    queryWrapper.eq(DfBizClue::getShareUser,SecurityUtils.getUserId());
                }
            } else {
                queryWrapper.eq(DfBizClue::getShareUser,SecurityUtils.getUserId());
            }
        }
        queryWrapper.orderByDesc(DfBizClue::getBrowseTime);
        List<DfBizClue> list = dfBizClueService.list(queryWrapper);
        Map<String, Integer> visitsNum = new HashMap<>();
        for (DfBizClue clue : list) {
            String key = clue.getUnionId() + "_" + clue.getDataType();
            int count = visitsNum.getOrDefault(key, 0) + 1;
            visitsNum.put(key, count);
            clue.setVisitsNum(count);
        }
        Map<String, DfBizClue> latestClues = new HashMap<>();
        for (DfBizClue clue : list) {
            String key = clue.getUnionId() + "_" + clue.getDataType();
            if (!latestClues.containsKey(key) || clue.getBrowseTime().after(latestClues.get(key).getBrowseTime())) {
                latestClues.put(key, clue);
            }
        }
        List<DfBizClue> newList = new ArrayList<>(latestClues.values());
        for (DfBizClue clue : newList) {
            String key = clue.getUnionId() + "_" + clue.getDataType();
            int visits = visitsNum.getOrDefault(key, 0);
            clue.setVisitsNum(visits);
            if (Validator.isNotEmpty(clue.getUserName())) {
                clue.setNickName(clue.getUserName());
            }
        }
        List<DfBizClue> sortedList = newList.stream()
                .sorted((o1, o2) -> o2.getBrowseTime().compareTo(o1.getBrowseTime())) // 倒序
                .collect(Collectors.toList());
        Integer start = (pageNum - 1) * pageSize;
        List<DfBizClue> result = sortedList.stream()
                .skip(start)
                .limit(pageSize)
                .collect(Collectors.toList());
        TableDataInfo data = getDataTable(result);
        data.setTotal(sortedList.size());
        return data;
//        return getDataTable(newList);
    }

    /**
     * 查询业务线索列表
     */
    @ApiOperation("查询业务线索列表")
    @GetMapping("/list")
    public AjaxResult list(DfBizClue dfBizClue) {
        LambdaQueryWrapper<DfBizClue> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBizClue);
        List<DfBizClue> list = dfBizClueService.list(queryWrapper);
        for (DfBizClue clue : list) {
            if (Validator.isNotEmpty(clue.getUserName())) {
                clue.setNickName(clue.getUserName());
            }
        }
        return success(list);
    }

    /**
     * 查询业务线索列表
     */
    @ApiOperation("查询业务线索列表")
    @GetMapping("/listByClassify")
    @Anonymous
    public AjaxResult listByClassify(DfBizClue dfBizClue) {
        LambdaQueryWrapper<DfBizClue> queryWrapper = new LambdaQueryWrapper();
        if ("0".equals(dfBizClue.getClassify())) {
            queryWrapper.in(DfBizClue::getDataType, "0", "3");
        } else if ("1".equals(dfBizClue.getClassify())) {
            queryWrapper.in(DfBizClue::getDataType, "2", "4");
        } else if ("2".equals(dfBizClue.getClassify())) {
            queryWrapper.in(DfBizClue::getDataType, "1");
        }
        if (Validator.isNotEmpty(dfBizClue.getBusinessLinks())) {
            queryWrapper.eq(DfBizClue::getBusinessLinks, dfBizClue.getBusinessLinks());
        }
        List<DfBizClue> list = dfBizClueService.list(queryWrapper);
        for (DfBizClue clue : list) {
            if (Validator.isNotEmpty(clue.getUserName())) {
                clue.setNickName(clue.getUserName());
            }
        }
        List<DfBizClue> uniqueList = list.stream()
                .collect(Collectors.toMap(
                        DfBizClue::getUserId, // 指定键的抽取函数
                        dfBizClueVo -> dfBizClueVo, // 指定值的映射函数
                        (existing, replacement) -> existing // 处理重复键的方式，这里选择保留第一个出现的元素
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
        List<String> avatarLinks = uniqueList.stream()
                .map(DfBizClue::getAvatarLink) // 获取每个对象的 avatarLink
                .limit(5) // 限制最多只取前 5 个
                .collect(Collectors.toList());
        DfBizClue dfBizClueByNum = new DfBizClue();
        dfBizClueByNum.setAvatarLinks(avatarLinks);
        dfBizClueByNum.setUserNum(uniqueList.size());
        return success(dfBizClueByNum);
    }

    /**
     * 导出业务线索列表
     */
    @ApiOperation("导出业务线索列表")
    @Log(title = "业务线索导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfBizClue dfBizClue) {
        LambdaQueryWrapper<DfBizClue> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBizClue);
        List<DfBizClue> list = dfBizClueService.list(queryWrapper);
        for (DfBizClue clue : list) {
            if (Validator.isNotEmpty(clue.getUserName())) {
                clue.setNickName(clue.getUserName());
            }
        }
        ExcelUtil<DfBizClue> util = new ExcelUtil<DfBizClue>(DfBizClue. class);
        util.exportExcel(response, list, "业务线索数据");
    }

    /**
     * 获取业务线索详细信息
     */
    @ApiOperation("获取业务线索详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DfBizClue byId = dfBizClueService.getById(id);
        List<SysUser> list = userService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, byId.getShareUser()));
        if (!list.isEmpty()) {
            String realName = list.get(0).getRealName();
            if (Validator.isEmpty(realName)) {
                if (Validator.isNotEmpty(list.get(0).getUserName())) {
                    list.get(0).setNickName(list.get(0).getUserName());
                }
                String nickName = list.get(0).getNickName();
                if (Validator.isEmpty(nickName)) {
                    String userName = list.get(0).getUserName();
                    byId.setRealName(userName);
                } else {
                    byId.setRealName(nickName);
                }
            } else {
                byId.setRealName(realName);
            }
        }
        return success(byId);
    }

    /**
     * 新增业务线索
     */
    @ApiOperation("新增业务线索")
    @Log(title = "业务线索新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DfBizClue dfBizClue) {
        return toAjax(dfBizClueService.save(dfBizClue));
    }

    /**
     * 新增业务线索
     *
     */
    @ApiOperation("新增业务线索")
    @Log(title = "业务线索新增", businessType = BusinessType.INSERT)
    @PostMapping("/addVisitor")
    @Anonymous
    public AjaxResult addVisitor(DfBizClue dfBizClue) {
        Date date = new Date();
        dfBizClue.setCreateTimeVo(date);
        dfBizClue.setTenantId(0L);
//        dfBizClue.setTenantId(SecurityUtils.getTenantId());
        return toAjax(dfBizClueMapper.insertClue(dfBizClue));
    }


    /**
     * 修改业务线索
     */
    @ApiOperation("修改业务线索")
    @Log(title = "业务线索修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfBizClue dfBizClue) {
        return toAjax(dfBizClueService.updateById(dfBizClue));
    }

    /**
     * 修改经纪人ID
     */
    @ApiOperation("经纪人ID")
    @PostMapping("/changeUserId")
    public AjaxResult changeUserId(@RequestBody DfBizClue dfBizClue) {
        List<DfBizClue> list = dfBizClueService.list(new LambdaQueryWrapper<DfBizClue>()
                .eq(DfBizClue::getShareUser, dfBizClue.getOldUserId()));
        if (list.size() > 0) {
            for (DfBizClue dfBizClueNew : list) {
                dfBizClueNew.setShareUser(dfBizClue.getNewUserId());
            }
            dfBizClueService.updateBatchById(list);
        }
        List<DfUserBroker> userBrokerList = dfUserBrokerService.list(new LambdaQueryWrapper<DfUserBroker>()
                .eq(DfUserBroker::getBrokerId, dfBizClue.getOldUserId()));
        if (userBrokerList.size() > 0) {
            for (DfUserBroker dfUserBroker : userBrokerList) {
                dfUserBroker.setBrokerId(Long.valueOf(dfBizClue.getNewUserId()));
            }
            dfUserBrokerService.updateBatchById(userBrokerList);
        }
        return toAjax(true);
    }

    /**
     * 删除业务线索
     */
    @ApiOperation("删除业务线索")
    @Log(title = "业务线索删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(dfBizClueService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<DfBizClue> queryWrapper,DfBizClue dfBizClue){


        //id
        if(Validator.isNotEmpty(dfBizClue.getId())){
            queryWrapper.eq(DfBizClue::getId,dfBizClue.getId());
        }

        //数据类型0客户1经纪
        if(Validator.isNotEmpty(dfBizClue.getDataType())){
            queryWrapper.eq(DfBizClue::getDataType,dfBizClue.getDataType());
        }

        //线索类型
        if(Validator.isNotEmpty(dfBizClue.getClueType())){
            queryWrapper.eq(DfBizClue::getClueType,dfBizClue.getClueType());
        }

        //用户id
        if(Validator.isNotEmpty(dfBizClue.getUserId())){
            queryWrapper.eq(DfBizClue::getUserId,dfBizClue.getUserId());
        }

        //用户昵称
        if(Validator.isNotEmpty(dfBizClue.getNickName())){
            queryWrapper.like(DfBizClue::getNickName,dfBizClue.getNickName());
        }

        //头像链接
        if(Validator.isNotEmpty(dfBizClue.getAvatarLink())){
            queryWrapper.eq(DfBizClue::getAvatarLink,dfBizClue.getAvatarLink());
        }

        //手机号
        if(Validator.isNotEmpty(dfBizClue.getPhone())){
            queryWrapper.eq(DfBizClue::getPhone,dfBizClue.getPhone());
        }


        //浏览时间
        if(Validator.isNotEmpty(dfBizClue.getBrowseTime())){
            queryWrapper.eq(DfBizClue::getBrowseTime,dfBizClue.getBrowseTime());
        }

        if(Validator.isNotEmpty(dfBizClue.getParams().get("beginTime"))){
            queryWrapper.ge(DfBizClue::getBrowseTime,dfBizClue.getParams().get("beginTime"));
        }

        if(Validator.isNotEmpty(dfBizClue.getParams().get("endTime"))){
            queryWrapper.le(DfBizClue::getBrowseTime,dfBizClue.getParams().get("endTime"));
        }


        //创建部门
        if(Validator.isNotEmpty(dfBizClue.getCreateDept())){
            queryWrapper.eq(DfBizClue::getCreateDept,dfBizClue.getCreateDept());
        }

        //创建人员
        if(Validator.isNotEmpty(dfBizClue.getCreateBy())){
            queryWrapper.eq(DfBizClue::getCreateBy,dfBizClue.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(dfBizClue.getCreateTime())){
            queryWrapper.eq(DfBizClue::getCreateTime,dfBizClue.getCreateTime());
        }

        //修改人员
        if(Validator.isNotEmpty(dfBizClue.getUpdateBy())){
            queryWrapper.eq(DfBizClue::getUpdateBy,dfBizClue.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(dfBizClue.getUpdateTime())){
            queryWrapper.eq(DfBizClue::getUpdateTime,dfBizClue.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(dfBizClue.getDelFlag())){
            queryWrapper.eq(DfBizClue::getDelFlag,dfBizClue.getDelFlag());
        }

        //租户id
        if(Validator.isNotEmpty(dfBizClue.getTenantId())){
            queryWrapper.eq(DfBizClue::getTenantId,dfBizClue.getTenantId());
        }

        //${column.columnComment}
        if(Validator.isNotEmpty(dfBizClue.getBusinessLinks())){
            queryWrapper.eq(DfBizClue::getBusinessLinks,dfBizClue.getBusinessLinks());
        }

        }

}
