package cn.timer.api.controller.zpgl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.timer.api.bean.qyzx.QyzxEmpLogin;
import cn.timer.api.bean.yggl.YgglMainEmp;
import cn.timer.api.bean.zpgl.ZpglRcxx;
import cn.timer.api.bean.zpgl.ZpglWxgzptEmpRcxx;
import cn.timer.api.controller.zpgl.sevice.ZpglWxgzptServiceImpl;
import cn.timer.api.dto.template.TemplateData;
import cn.timer.api.dto.wxgzh.LoginDto;
import cn.timer.api.dto.wxgzh.MessageQueueDto;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import cn.timer.api.utils.redis.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author longys
 * @date 2022/3/25 17:18
 */
@Api(tags = "微信公众平台")
@RestController
@RequestMapping(value = "/wxgzpt")
public class ZpglWxgzptController {

    @Value("${wxgzh.appid}")
    private String appid;
    @Value("${wxgzh.appSecret}")
    private String appSecret;
    @Value("${config-8timer.authentication-code}")
    public String authentication_code;
    @Value("${h5.url}")
    public String h5Url;

    public static final String OAUTH_GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    @Resource
    private ZpglWxgzptServiceImpl zpglWxgzptService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 重定向到绑定登录页面
     * @param request
     * @return
     */
    @RequestMapping("/toLoginPage")
    @ApiOperation(value = "重定向到绑定登录页面", httpMethod = "GET", notes = "重定向到绑定登录页面")
    public ModelAndView toLoginPage(HttpServletRequest request){
        String state = request.getParameter("state");
        String code = request.getParameter("code");
        //用code获取openid
        String url = OAUTH_GET_ACCESS_TOKEN_URL.replace("APPID",appid).replace("SECRET",appSecret).replace("CODE",code);
        String s = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");

        //查询是否已绑定人才信息
        ZpglWxgzptEmpRcxx wxgzptEmpRcxx = ZpglWxgzptEmpRcxx.builder().build()
                .selectOne(new QueryWrapper<ZpglWxgzptEmpRcxx>().lambda()
                        .eq(ZpglWxgzptEmpRcxx::getOpenid, openid));

        ModelAndView mav = new ModelAndView();
        mav.addObject("openid",openid);
        if (wxgzptEmpRcxx != null){
            mav.setViewName("redirect:"+h5Url+"/#/wxgzhIndex");
        }else {
            mav.setViewName("redirect:"+h5Url+"/#/wxgzhLogin");
        }
        return mav;
    }

    /**
     * 重定向到绑定登录页面
     * @param request
     * @return
     */
    @RequestMapping("/basic_info")
    @ApiOperation(value = "重定向到面试申请页面", httpMethod = "GET", notes = "重定向到面试申请页面")
    public ModelAndView basicInfo(HttpServletRequest request){
        String mobile = request.getParameter("mobile");
        String orgId = request.getParameter("orgId");
        ModelAndView mav = new ModelAndView();
        mav.addObject("mobile",mobile);
        mav.addObject("orgId",Integer.valueOf(orgId));
        mav.setViewName("redirect:"+h5Url+"/#/basicInfo");
        return mav;
    }



    /**
     * 查询是否已绑定人才信息
     * @param openid
     * @return
     */
    @RequestMapping("/checkBind")
    @ApiOperation(value = "查询是否已绑定人才信息", httpMethod = "GET", notes = "查询是否已绑定人才信息")
    public Result<Object> checkBind(String openid){
        ZpglWxgzptEmpRcxx wxgzptEmpRcxx = ZpglWxgzptEmpRcxx.builder().build()
                .selectOne(new QueryWrapper<ZpglWxgzptEmpRcxx>().lambda()
                        .eq(ZpglWxgzptEmpRcxx::getOpenid, openid)
                        .eq(ZpglWxgzptEmpRcxx::getDeleteFlag, 0));
        if (wxgzptEmpRcxx == null)
            return ResultUtil.error("25001","未绑定");
        return ResultUtil.success("已绑定.");
    }

    /**
     * 查询已绑定信息
     * @param openid
     * @return
     */
    @RequestMapping("/getBindInfo")
    @ApiOperation(value = "查询已绑定信息", httpMethod = "GET", notes = "查询已绑定信息")
    public Result<LoginDto> getBindInfo(String openid){
        //查询是否已绑定人才信息
        ZpglWxgzptEmpRcxx wxgzptEmpRcxx = ZpglWxgzptEmpRcxx.builder().build()
                .selectOne(new QueryWrapper<ZpglWxgzptEmpRcxx>().lambda()
                        .eq(ZpglWxgzptEmpRcxx::getOpenid, openid)
                        .eq(ZpglWxgzptEmpRcxx::getDeleteFlag, 0));

        if (wxgzptEmpRcxx != null){
            LoginDto loginDao = new LoginDto();
            YgglMainEmp userInfo = new YgglMainEmp();
            //判断是否有人才信息表id
            if(wxgzptEmpRcxx.getZpglRcxxId() != null && wxgzptEmpRcxx.getZpglRcxxId() != 0){
                //查询人才信息表
                ZpglRcxx zpglRcxx = ZpglRcxx.builder().build().selectOne(new QueryWrapper<ZpglRcxx>()
                        .lambda().eq(ZpglRcxx::getId, wxgzptEmpRcxx.getZpglRcxxId()));
                userInfo.setPhone(zpglRcxx.getMobile());
                userInfo.setName(zpglRcxx.getName());
            }
            //判断员工档案ID不等于空
            if(wxgzptEmpRcxx.getYgglMainEmpId() != null){
                userInfo = userInfo.builder().build().selectOne(new QueryWrapper<YgglMainEmp>().lambda()
                        .select(YgglMainEmp::getId,YgglMainEmp::getEmpNum, YgglMainEmp::getName, YgglMainEmp::getPhone, YgglMainEmp::getBmgwId, YgglMainEmp::getOrgCode)
                        .eq(YgglMainEmp::getId, wxgzptEmpRcxx.getYgglMainEmpId())
                        .eq(YgglMainEmp::getOrgCode, wxgzptEmpRcxx.getOrgCode()));
                loginDao.setUserName(userInfo.getName());
                loginDao.setPhone(userInfo.getPhone());
                loginDao.setAvatar(userInfo.getHeadUrl());
            }else {
                loginDao.setPhone(wxgzptEmpRcxx.getMobile());
            }
            return ResultUtil.data(loginDao);
        }
        return null;
    }


    /**
     * 公众号登录绑定
     */
    @RequestMapping("/login")
    @ApiOperation(value = "公众号登录绑定", httpMethod = "POST", notes = "公众号登录绑定")
    public Result<Object> login(@RequestBody LoginDto loginDao, HttpServletRequest request){
        System.out.println(loginDao);
        HttpSession session = request.getSession();
        String code = loginDao.getCode();
        String phone = loginDao.getPhone();
        String openid = loginDao.getOpenid();
        if (StringUtils.isEmpty(code)) {
            return ResultUtil.error("请输入验证码");
        }
        //String codeRedis = session.getAttribute(phone) != null ? session.getAttribute(phone).toString() : "";
        String codeRedis = redisUtil.get(session.getId()+phone) != null ? redisUtil.get(session.getId()+phone).toString() : null;
        if(authentication_code !=null && !("").equals(authentication_code)) {
            if (authentication_code.equals(code)) {
                return loginhan(phone,openid);
            }
        }

        if (codeRedis == null || !code.equals(codeRedis)){
            return ResultUtil.error("验证码不符");
        }
        return loginhan(phone,openid);
    }

    public Result<Object> loginhan(String phone, String openid) {

        //查询该手机号是否绑定了公众号
        ZpglWxgzptEmpRcxx wxgzptEmpRcxx = ZpglWxgzptEmpRcxx.builder().build()
                .selectOne(new QueryWrapper<ZpglWxgzptEmpRcxx>().lambda()
                        .eq(ZpglWxgzptEmpRcxx::getMobile, phone)
                        .eq(ZpglWxgzptEmpRcxx::getDeleteFlag,0));
        //如果绑定过其他微信openid  替换成当前的openid
        if (wxgzptEmpRcxx != null){
            wxgzptEmpRcxx.setOpenid(openid);
            wxgzptEmpRcxx.updateById();
        }else {
            //查询员工登录表
            QyzxEmpLogin qyzxEmpLogin = QyzxEmpLogin.builder().build()
                    .selectOne(new QueryWrapper<QyzxEmpLogin>().lambda()
                            .eq(!StrUtil.hasBlank(phone), QyzxEmpLogin::getPhone, phone));

            YgglMainEmp userInfo = null;
            if (qyzxEmpLogin != null){
                //查询员工档案表
                userInfo = YgglMainEmp.builder().build().selectOne(new QueryWrapper<YgglMainEmp>().lambda()
                        .select(YgglMainEmp::getId,YgglMainEmp::getEmpNum, YgglMainEmp::getName, YgglMainEmp::getPhone, YgglMainEmp::getBmgwId, YgglMainEmp::getOrgCode)
                        .eq(YgglMainEmp::getEmpNum, qyzxEmpLogin.getId())
                        .eq(YgglMainEmp::getOrgCode, qyzxEmpLogin.getOrgId()));
            }

            //查询人才信息表
            ZpglRcxx zpglRcxx = ZpglRcxx.builder().build().selectOne(new QueryWrapper<ZpglRcxx>()
                    .lambda().eq(!StrUtil.hasBlank(phone), ZpglRcxx::getMobile, phone));

            //没有加入企业
        /*if (userInfo == null && zpglRcxx == null){
            return ResultUtil.error("25002","没有找到匹配的企业");
        }*/

            ZpglWxgzptEmpRcxx empRcxx = new ZpglWxgzptEmpRcxx();
            empRcxx.setZpglRcxxId(zpglRcxx!=null?zpglRcxx.getId():null);
            empRcxx.setYgglMainEmpId(userInfo!=null?userInfo.getId():null);
            empRcxx.setOrgCode(userInfo!=null?userInfo.getOrgCode():null);
            empRcxx.setOpenid(openid);
            empRcxx.setMobile(phone);
            empRcxx.insert();
        }
        return ResultUtil.success();
    }

    /**
     *根据手机号查询绑定的openid
     * @return
     */
    @GetMapping(value = "/getOpenid")
    @ApiOperation(value = "获取openid", httpMethod = "POST", notes = "根据手机号查询绑定的openid")
    public Result<ZpglWxgzptEmpRcxx> getOpenid(String phone){
        //查询该手机号是否绑定了公众号
        ZpglWxgzptEmpRcxx wxgzptEmpRcxx = ZpglWxgzptEmpRcxx.builder().build()
                .selectOne(new QueryWrapper<ZpglWxgzptEmpRcxx>().lambda()
                        .eq(ZpglWxgzptEmpRcxx::getMobile, phone)
                        .eq(ZpglWxgzptEmpRcxx::getDeleteFlag,0));
        return ResultUtil.data(wxgzptEmpRcxx);
    }

    @RequestMapping("/addMessageQueue")
    public Result<Object> addMessageQueue(){
        //消息队列对象
        MessageQueueDto mqd = new MessageQueueDto();
        /**
         * 模板消息内容 start
         */
        List<TemplateData> templateData = new ArrayList<>();
        TemplateData key1 = new TemplateData("first", "您好,JAVA工程师张三已安排由您面试", "#000000");
        TemplateData key2 = new TemplateData("keyword1", "JAVA工程师", "#000000");
        TemplateData key3 = new TemplateData("keyword2", "2021-03-23 10:00", "#000000");
        TemplateData key4 = new TemplateData("remark", "点击填写面试申请", "#000000");
        templateData.add(key1);
        templateData.add(key2);
        templateData.add(key3);
        templateData.add(key4);
        //数据处理成固定好的json格式
        String content = mqd.getContentJson(templateData);
        /**
         * 模板消息内容 end
         */
        mqd.setContent(content);//消息内容模板消息 json格式  普通消息字符串类型
        mqd.setMobile("18212310017");//手机号
        mqd.setType(2);//类型(1 短信,2 邮件,3 微信模板消息)
        mqd.setWxgzhType(1);//公众号类型 1:8小时企业管理 2:优领人才网
        mqd.setTiming(1);//1 即时发送,2 定时发送
        mqd.setTemplateId("Uz6mVUYk9Tu7EO2V1pqiQ3x4EudDJTYWdaFtdf64h3M");//模板id
        mqd.setUrl(null);//网页地址
        mqd.setWxxcxPageId(null);//小程序页面地址

        Map map = JSON.parseObject(JSON.toJSONString(mqd), Map.class);
        String s = zpglWxgzptService.addMessageQueue(map);
        return ResultUtil.success(s);
    }



}