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.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 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);

    @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);
            }
        }
        this.openQwApiService.addFriendSuccessNotice(qwStaffId,list);
    }

    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 ;
        }
        List<String> msgList = Arrays.asList("0","2","101") ;
        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") ;
        OpenQwMessageDTO msg = new OpenQwMessageDTO();
        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"));
        if(msgtype==101) {
            msg.setAeskey(json.getString("aeskey"));
        }
        if(msgtype==14) {
            msg.setAeskey(json.getString("aes_key"));
        }
        msg.setOpenimCdnAuthkey(json.getString("openim_cdn_authkey"));
        if(msgtype==101 || msgtype==14) {
            msg.setMsgtype(OpenQwMsgTypeEnum.IMAGE);
        }else {
            msg.setMsgtype(OpenQwMsgTypeEnum.text);
        }
        this.setSendType(msgtype,msg);
        this.openQwApiService.saveChatLog(msg) ;
    }

    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()) ;
    }

}
