package com.gic.haoban.manage.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.authcenter.commons.util.IgnoreLogin;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.manage.api.enums.OpenStaffOfflineEnum;
import com.gic.haoban.manage.api.enums.QwOpenStepEnum;
import com.gic.haoban.manage.api.service.OpenStaffApiService;
import com.gic.haoban.task.manage.api.dto.open.OpenQwMessageDTO;
import com.gic.haoban.task.manage.api.enums.OpenQwMsgTypeEnum;
import com.gic.mq.sdk.GicMQClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class QywxCallbackController extends WebBaseController {

    private static final Logger logger = LoggerFactory.getLogger(QywxCallbackController.class);
    GicMQClient gicMQClient = GICMQClientUtil.getClientInstance();

    @Autowired
    private OpenStaffApiService openStaffApiService ;
    @Autowired
    private com.gic.haoban.task.manage.api.service.OpenQwApiService  openQwApiService ;

    @RequestMapping("qywx-msg-notice")
    @IgnoreLogin
    public Object callback(HttpServletRequest request , HttpServletResponse response) {
        try {
            String body = IOUtils.toString(request.getInputStream()) ;
            logger.info("企微消息下发={}",body);
            JSONObject jsonObject = JSONObject.parseObject(body) ;
            int type = jsonObject.getIntValue("type") ;
            String uuid = jsonObject.getString("uuid") ;
            Long qwStaffId = jsonObject.getLong("vid") ;
            JSONObject json = jsonObject.getJSONObject("json") ;
            this.post(type,uuid,json , qwStaffId);
            Map<String,String> map = new HashMap<>() ;
            map.put("errcode","0") ;
            map.put("errmsg","ok") ;
            return map ;
        }catch (Exception e) {
            logger.info("异常",e);
        }
        return "ok" ;
    }

    private void post(int type , String uuid , JSONObject json , Long qwStaffId) {
        switch (type) {
            case 116002:
                this.addFriend(json , qwStaffId) ;
                break;
            case 102000:
                this.chat(uuid,json) ;
                break;
            case 100001 :
                this.v100001(uuid,json) ;
                break;
            case 100002 :
                this.v100002(uuid,json) ;
                break;
            case 100003 :
                this.v100003(uuid,json) ;
                break;
            case 100004 :
                this.v100004(uuid,json) ;
                break;
            case 100005 :
                this.close(uuid,OpenStaffOfflineEnum.OFFLINE3) ;
                break;
            case 104001 :
                this.loginSuccess(uuid,json) ;
                break;
            case 100012 :
                this.v100012(uuid,json) ;
                break;
            case 100009 :
                this.v100009(uuid,json) ;
                break;
            case 100008:
                this.close(uuid,OpenStaffOfflineEnum.OFFLINE4);
                break;
            case 100007:
                this.close(uuid,OpenStaffOfflineEnum.OFFLINE2);
                break;
            default:
                break;
        }
    }

    // 加好友
    private void addFriend(JSONObject json, Long qwStaffId) {
        logger.info("加好友、删好友");
        JSONArray array = json.getJSONArray("list");
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            int status = jsonObject.getIntValue("status");
            if (status == 2057 || status == 9) {
                Long qwUserId = jsonObject.getLong("user_id");
                list.add(qwUserId);
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        JSONObject mq = new JSONObject();
        mq.put("qwStaffId", qwStaffId);
        mq.put("qwUserIdList", list);
        try {
            gicMQClient.sendMessage("addFriendSuccessNoticeMQ", mq.toJSONString());
        } catch (Exception e) {
            logger.info("异常", e);
        }

    }

    private void chat(String uuid, JSONObject json) {
        int msgtype = json.getIntValue("msgtype");
        // 群发任务
        if (msgtype == 573) {
            json.put("uuid", uuid);
            this.openQwApiService.saveNotice(json.toJSONString());
            return;
        }
        // 6 位置
        // 41 名片
        // 40 语音视频通话时常消息通知
        // 503 语音或者视频通话，未接听消息
        // 16 语音消息
        // 14 101 图片
        // 23 103(微信) 视频消息
        // 15 102(微信) 文件消息
        // 104 gif表情消息类型
        // 26 红包
        // 78 小程序
        // 13 链接
        List<String> msgList = Arrays.asList("0","2","101","6","41","40","14","16","23","103","15","102","104","26","78","13") ;
        if(!msgList.contains(msgtype+"")) {
            logger.info("不处理的消息");
            return ;
        }
        logger.info("处理消息");
        int isRoom = json.getIntValue("is_room") ;
        Long receiver = json.getLong("receiver") ;
        Long sender = json.getLong("sender") ;
        String content = json.getString("content") ;
        String fileId = json.getString("file_id") ;
        Long roomId = json.getLong("room_conversation_id") ;
        Integer fileSize = json.getInteger("file_size") ;
        OpenQwMessageDTO msg = new OpenQwMessageDTO();
        msg.setFileSize(fileSize);
        msg.setIsRoom(isRoom);
        msg.setUuid(uuid);
        msg.setReceiver(receiver);
        msg.setSender(sender);
        msg.setContent(content);
        msg.setRoomId(roomId);
        msg.setFileId(fileId);
        msg.setSendTime(json.getLong("send_time"));
        msg.setOpenimCdnAuthkey(json.getString("openim_cdn_authkey"));
        if(msgtype==101 || msgtype==14) {
            if(msgtype==101) {
                msg.setAeskey(json.getString("aeskey"));
            }
            if(msgtype==14) {
                msg.setAeskey(json.getString("aes_key"));
            }
            msg.setMsgtype(OpenQwMsgTypeEnum.IMAGE);
        }else if(msgtype==13) {
            msg.setMsgtype(OpenQwMsgTypeEnum.LINK);
            msg.setContent(json.getString("url"));
        }else if(msgtype==78) {
            msg.setMsgtype(OpenQwMsgTypeEnum.WXA);
            msg.setContent(json.getString("desc"));
        }else if(msgtype == 26) {
            msg.setMsgtype(OpenQwMsgTypeEnum.RED);
            msg.setContent(json.getString("remark"));
        }else if(msgtype==104) {
            msg.setMsgtype(OpenQwMsgTypeEnum.GIF);
            msg.setContent(json.getString("url"));
        }else if(msgtype==23 || msgtype==103){
            msg.setMsgtype(OpenQwMsgTypeEnum.VIDEO);
            msg.setAeskey(json.getString("aes_key"));
        }else if(msgtype==15 || msgtype==102){
            msg.setMsgtype(OpenQwMsgTypeEnum.FILE);
            msg.setAeskey(json.getString("aes_key"));
        }else if(msgtype==6) {
            msg.setMsgtype(OpenQwMsgTypeEnum.LOCAL);
            msg.setContent(json.getString("address"));
        }else if (msgtype==41) {
            msg.setMsgtype(OpenQwMsgTypeEnum.NAME_CARD);
            msg.setContent(json.getString("nickname"));
        }else if (msgtype==16) {
            msg.setMsgtype(OpenQwMsgTypeEnum.VOICE);
            msg.setContent(json.getString("语音消息"));
            msg.setFileSize(json.getInteger("voice_size"));
            msg.setAeskey(json.getString("aes_key"));
            msg.setFileId(json.getString("voice_id"));
        }else if (msgtype==40) {
            // 2语音电话  1视频电话
            int callType = json.getIntValue("invitetype") ;
            if(!this.setTelType(callType,msg)) {
                return;
            }
            // //1代表对方取消 5代表语音结束
            int recordtype = json.getIntValue("recordtype") ;
            if(recordtype==5) {
                msg.setContent(json.getString("recordwording"));
            }else if(recordtype==1) {
                msg.setContent("对方已取消");
            }
        }else if (msgtype==503) {
            // 2语音  1视频
            int callType = json.getIntValue("invitetype") ;
            if(!this.setTelType(callType,msg)) {
                return;
            }
            int type = json.getIntValue("type") ;
            //3是未接听  1是正在打电话
            if(type != 3) {
                return ;
            }
            msg.setContent(json.getString("未接通"));
        } else {
            msg.setMsgtype(OpenQwMsgTypeEnum.text);
        }
        this.setSendType(msgtype, msg);
        try {
            gicMQClient.sendMessage("saveChatLogMQ", JSONObject.toJSONString(msg));
        } catch (Exception e) {
            logger.info("异常", e);
        }
    }

    private boolean setTelType( int callType , OpenQwMessageDTO msg) {
        if(callType==1) {
            msg.setMsgtype(OpenQwMsgTypeEnum.VIDEO_TEL);
        }else if(callType==2) {
            msg.setMsgtype(OpenQwMsgTypeEnum.VOICE_TEL);
        }else {
            return false;
        }
        return true ;
    }

    private void setSendType(int msgtype , OpenQwMessageDTO msg) {
        if(msgtype==101) {
            msg.setSendType(2);
        }else if(msgtype==14) {
            msg.setSendType(1);
        }else {
            msg.setSendType(0);
        }
    }

    private void v100012(String uuid , JSONObject json) {
        logger.info("需要二次扫码");
        this.openStaffApiService.update2QrcodeFlag(uuid) ;
    }
    private void v100009(String uuid , JSONObject json) {
        logger.info("超时未扫码关闭");
        this.openStaffApiService.updateLoginStep(uuid, QwOpenStepEnum.step3.getStep()) ;
    }
    private void v100001(String uuid , JSONObject json) {
        logger.info("用户扫码={}",uuid);
        this.openStaffApiService.updateLoginStep(uuid,QwOpenStepEnum.step1.getStep()) ;
    }
    private void v100004(String uuid , JSONObject json) {
        logger.info("需要输入验证码校验={}",uuid);
        this.openStaffApiService.updateValiFlag(uuid) ;
    }
    private void v100002(String uuid , JSONObject json) {
        logger.info("验证码校验成功返回={}",uuid);
        this.openStaffApiService.updateLoginStep(uuid,QwOpenStepEnum.step4.getStep()) ;
    }
    private void loginSuccess(String uuid , JSONObject json) {
        logger.info("登录成功={}",uuid);
        Long qwCorpId = json.getLong("corp_id") ;
        Long qwUserid = json.getLong("user_id") ;
        String corpName = json.getString("corp_name") ;
        this.openStaffApiService.login(uuid,qwCorpId,corpName,qwUserid) ;
    }
    private void close(String uuid , OpenStaffOfflineEnum offlineEnum) {
        logger.info("退出={}",uuid);
        this.openStaffApiService.logout(uuid, offlineEnum) ;
    }
    private void v100003(String uuid , JSONObject json) {
        logger.info("取消登录={}",uuid);
        this.openStaffApiService.updateLoginStep(uuid,QwOpenStepEnum.step2.getStep()) ;
    }

}
