package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.TimeUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.qw.domain.QwUserbehaviorData;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.mapper.QwUserbehaviorDataMapper;
import com.fs.qw.param.QwUserListParam;
import com.fs.qw.param.QwUserbehaviorDataParams;
import com.fs.qw.service.IQwUserbehaviorDataService;
import com.fs.qw.vo.CompanyUserQwVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.qw.vo.QwUserbehaviorDataVO;
import com.fs.qwApi.Result.QwUserBehaviorDataResult;
import com.fs.qwApi.param.QwUserBehaviorDataParam;
import com.fs.qwApi.service.QwApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企微联系客户统计数据Service业务层处理
 *
 * @author fs
 * @date 2024-08-05
 */
@Service
public class QwUserbehaviorDataServiceImpl implements IQwUserbehaviorDataService
{
    @Autowired
    private QwUserbehaviorDataMapper qwUserbehaviorDataMapper;

    @Autowired
    private ICompanyUserService userService;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 查询企微联系客户统计数据
     *
     * @param id 企微联系客户统计数据主键
     * @return 企微联系客户统计数据
     */
    @Override
    public QwUserbehaviorData selectQwUserbehaviorDataById(Long id)
    {
        return qwUserbehaviorDataMapper.selectQwUserbehaviorDataById(id);
    }

    /**
     * 查询企微联系客户统计数据列表
     *
     * @param params 企微联系客户统计数据
     * @return 企微联系客户统计数据
     */
    @Override
    public R selectQwUserbehaviorDataList(QwUserbehaviorDataParams params)
    {

        if(StringUtils.isNotEmpty(params.getUserIds())){
            String[] userIds=params.getUserIds().split(",");
            params.setUsers(userIds);
        }
        else{
            //获取部门下的所有用户
            CompanyUser usermap=new CompanyUser();
            usermap.setDeptId(params.getDeptId());
            usermap.setCompanyId(params.getCompanyid());

            List<CompanyUserQwVO> userQwVOS = userService.getUserListByDeptIdToQwUserid(usermap);

            List<String> userIds = userQwVOS.stream().map(element -> element.getQwId().trim()).collect(Collectors.toList());

            params.setUsers(userIds.toArray(new String[userIds.size()]));
        }

        if(params.getUsers()!=null&&params.getUsers().length>0){


            List<QwUserbehaviorDataVO> qwUserbehaviorDataVOS = qwUserbehaviorDataMapper.selectQwUserbehaviorDataListVO(params);

            TimeUtils.TimeEntity timeEntity= TimeUtils.parseTime(params.getType().toString(),params.getStartTime(),params.getEndTime());

            timeEntity.setCompanyId(params.getCompanyid());

            Integer cycleNum = timeEntity.getCycleNum();
            Integer beginTime = timeEntity.getBeginTime();
            List<Integer> timeList = new ArrayList<>();
            for (int i = 1; i <= cycleNum; i++) {
                timeList.add(beginTime);
                beginTime = TimeUtils.formatTime(beginTime);
            }

            List<JSONObject> jsonObjectList = qwUserbehaviorDataMapper.selectQwUserbehaviorDataListVOCount(timeEntity.toMap(),params.getUsers());

                return R.ok().put("list",qwUserbehaviorDataVOS).put("charts",jsonObjectList);
        }
        else {
            return R.ok("未查找到数据");
        }

    }

    /**
     * 新增企微联系客户统计数据
     *
     * @param qwUserbehaviorData 企微联系客户统计数据
     * @return 结果
     */
    @Override
    public int insertQwUserbehaviorData(QwUserbehaviorData qwUserbehaviorData)
    {
        return qwUserbehaviorDataMapper.insertQwUserbehaviorData(qwUserbehaviorData);
    }

    /**
     * 修改企微联系客户统计数据
     *
     * @param qwUserbehaviorData 企微联系客户统计数据
     * @return 结果
     */
    @Override
    public int updateQwUserbehaviorData(QwUserbehaviorData qwUserbehaviorData)
    {
        return qwUserbehaviorDataMapper.updateQwUserbehaviorData(qwUserbehaviorData);
    }

    /**
     * 批量删除企微联系客户统计数据
     *
     * @param ids 需要删除的企微联系客户统计数据主键
     * @return 结果
     */
    @Override
    public int deleteQwUserbehaviorDataByIds(Long[] ids)
    {
        return qwUserbehaviorDataMapper.deleteQwUserbehaviorDataByIds(ids);
    }

    /**
     * 删除企微联系客户统计数据信息
     *
     * @param id 企微联系客户统计数据主键
     * @return 结果
     */
    @Override
    public int deleteQwUserbehaviorDataById(Long id)
    {
        return qwUserbehaviorDataMapper.deleteQwUserbehaviorDataById(id);
    }


    /**
     * 定时任务，每天定时从企业微信获取联系客户统计的更新数据
     */
    @Override
    public void updateQwUserbehaviorDataByTimer() {
        //复用 空的QwUserParam
        QwUserListParam qwUserParam=new QwUserListParam();

        //更新或插入数据
        QwUserbehaviorData qwUserbehaviorData=new QwUserbehaviorData();

        //请求API参数
        QwUserBehaviorDataParam param= new QwUserBehaviorDataParam();

        // 获取当前时区的昨天的同一时间的时间戳
        long timestamp = ZonedDateTime.now().minusDays(1).toEpochSecond();

        param.setStart_time(String.valueOf(timestamp));
        param.setEnd_time(String.valueOf(timestamp));

        List<QwUserVO> list = qwUserMapper.selectQwUserListVO(qwUserParam);
        for (QwUserVO qwUserVO : list) {
            param.setUserid(Collections.singletonList(qwUserVO.getQwUserId()));

            QwUserBehaviorDataResult userBehaviorData = qwApiService.getUserBehaviorData(param, qwUserVO.getCorpId());
            if (userBehaviorData.getErrcode()==0) {
                List<QwUserBehaviorDataResult.BehaviorData> behaviorData = userBehaviorData.getBehavior_data();
                qwUserbehaviorData.setUserid(qwUserVO.getQwUserId());
                qwUserbehaviorData.setCorpId(qwUserVO.getCorpId());
                qwUserbehaviorData.setStatTime(behaviorData.get(0).getStat_time());
                qwUserbehaviorData.setChatCnt(Long.valueOf(behaviorData.get(0).getChat_cnt()));
                qwUserbehaviorData.setMessageCnt(Long.valueOf(behaviorData.get(0).getMessage_cnt()));
                qwUserbehaviorData.setReplyPercentage(behaviorData.get(0).getReply_percentage());
                qwUserbehaviorData.setAvgReplyTime(Long.valueOf(behaviorData.get(0).getAvg_reply_time()));
                qwUserbehaviorData.setNegativeFeedbackCnt(Long.valueOf(behaviorData.get(0).getNegative_feedback_cnt()));
                qwUserbehaviorData.setNewApplyCnt(Long.valueOf(behaviorData.get(0).getNew_apply_cnt()));
                qwUserbehaviorData.setNewContactCnt(Long.valueOf(behaviorData.get(0).getNew_contact_cnt()));
                qwUserbehaviorDataMapper.insertOrUpdateQwUserbehaviorData(qwUserbehaviorData);
            }
        }


    }
}
