package com.chinacreator.video.restful.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.dto.DataOutPipe;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.AqyDrawDao;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.restful.service.AqyDrawService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.PushbackReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 爱奇艺20元抽奖活动侧接口
 * zhengrong.yan
 * 20201105
 */
@RestController
public class AqyDrawController {

    private static Logger logger = Logger.getLogger(String.valueOf(AqyDrawController.class));

    private static Logger log = Logger.getLogger("aqydraw");

    @Autowired
    private AqyDrawService service;

    @Autowired
    private  AqyDrawDao aqyDrawDao;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    RedisService redisService;

    public static void main(String[] args) throws Exception {
        String str = DesUtil.encode("18602518932", "qwer1234");
        System.out.println(str);
        str=URLEncoder.encode(str,"utf-8");
        System.out.println(str);
        System.out.println(DesUtil.decode(URLDecoder.decode(str,"utf-8"),"qwer1234"));
        System.out.println(DesUtil.decode("Emb2XhPwsj+PnKGSJ0qJZw==","qwer1234"));
    }
    /**
     * POST方式办理业务
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/aqydraw", method = RequestMethod.POST, produces = "application/json")
    public DataOutPipe<?> order(@RequestBody(required = false) OrderInfo orderInfo, HttpServletRequest request) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        HashMap resmap = null;
        logmap.put("forward", "aqydraw");
        logmap.put("reqData", orderInfo);
        String pwd = channelDao.queryChannel("aqy20active").getPassword();
        orderInfo.setUserid(DesUtil.decode(URLDecoder.decode(orderInfo.getUserid(),"utf-8"), pwd));
        HashMap map = new HashMap();//记录用户抽奖记录（所有用户）
        map.put("ID", aqyDrawDao.getNo());
        map.put("USERID", orderInfo.getUserid());
        System.out.println("ID==>" + map.get("ID"));
        System.out.println("USERID==>" + map.get("USERID"));
        aqyDrawDao.addDrawLog(map);//将用户添加到表

        String resultcode = "";
        String errorinfo = "";
//		System.out.println(orderInfo);
        try {
            orderInfo.setTimes(System.currentTimeMillis() + "");
            orderInfo.setCpid("youtudraw");
            service.busiCheck(orderInfo);//验证
            System.out.println("已验证--------------------------------");
            resmap = service.busiOper(orderInfo);//开始抽奖
            if(resmap!=null) {
                System.out.println("resmap无数据--------------------------------");
                resultcode = resmap.get("resultcode").toString();
                errorinfo = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                errorinfo = "出现异常，" + e.getMessage();
            }
        } finally {
            //更新抽奖log表
            map.put("DETAIL", errorinfo);
            map.put("RESULTCODE", resultcode);
            try {
                if (resmap != null) {
                    map.put("DETAIL", resmap.get("detail") + "");
                }
                if (resultcode.equals("0")) {
                    map.put("DETAIL", "未中奖！");
                }
                aqyDrawDao.upDrawLog(map);
            } catch (Exception e) {
                e.printStackTrace();
                resultcode = "8000";
                errorinfo = e.getMessage();
            }
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
        }
        return outpipe;
    }

    /*保存中奖信息*/
    @RequestMapping(value = "/saveAqydrawinfo",  produces = "application/json")
    public DataOutPipe<?> save(@RequestBody(required = false) String params, HttpServletRequest request) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        HashMap map = new HashMap();
        logmap.put("forward", "saveAqydrawinfo");
        logmap.put("reqData", params);
        Map map1 = JSONObject.parseObject(params, Map.class);
        String resultcode = "";
        String errorinfo = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//月份作为副key
        Date d = new Date();
        String month = sdf.format(d);
        try {
            //查询中奖表
            String userid = String.valueOf(map1.get("userid"));
            String pwd = channelDao.queryChannel("aqy20active").getPassword();
            userid=URLDecoder.decode(userid,"utf-8");
            userid = DesUtil.decode(userid, pwd);
            logmap.put("userid", userid);
            //查询中奖表
            HashMap prizemap = aqyDrawDao.hasDrawPrizelist(userid, month);
            if (prizemap == null || prizemap.size() < 0) {//无中奖信息
                throw new BussinessException("8009", "您未中奖，无法获取该奖品！");
            }
                map.put("userid", userid);
                map.put("phone",  map1.get("phone"));
                map.put("username", map1.get("username"));
                map.put("address", map1.get("address"));
                map.put("goodscode", prizemap.get("PRIZEID").toString());
                map.put("prizemonth", month);
                map.put("idCard", map1.get("idCard"));
                try {
                    aqyDrawDao.addPrizeDetail(map);
                }catch (Exception e){
                    e.printStackTrace();
                    throw new BussinessException("8010", "您已填写过该表！"+e.getMessage());
                }

            resultcode = "0";
            errorinfo = "";
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            errorinfo = "出现异常，" + e.getMessage();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            }
        } finally {
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            return outpipe;
        }
    }


    /*抽奖前查询是否有抽奖资格*/
    @GetMapping(value = "/queryAqydrawQualifications")
    public DataOutPipe<?> query(@RequestParam Map params) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        logmap.put("forward", "queryAqydrawQualifications");
        logmap.put("reqData", params);
        String resultcode = "0";
        String errorinfo = "";
        try {
            String pwd = channelDao.queryChannel("aqy20active").getPassword().trim();
            String userid = String.valueOf(params.get("userid"));
            String spid = String.valueOf(params.get("spid"));
            userid = DesUtil.decode(userid, pwd);
            logmap.put("userid", userid);
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserid(userid);
            orderInfo.setCpid("youtudraw");
            orderInfo.setSpid(spid);
            //订购状态有效验证
            service.orderRelationVali(orderInfo);
            //本月是否已经抽过奖
            service.hasDraw(orderInfo);
            resultcode = "0";
            errorinfo = "";
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            errorinfo = "出现异常，" + e.getMessage();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            }
        } finally {
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            return outpipe;
        }
    }

    /*抽奖前查询是否有抽奖资格*/
    @GetMapping(value = "/deleteAqydraw")
    public DataOutPipe<?> delete(@RequestParam String userid) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        logmap.put("forward", "queryAqydrawQualifications");
        logmap.put("reqData", userid);
        String resultcode = "0";
        String errorinfo = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//月份作为副key
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d = new Date();
        String month = sdf.format(d);
        String day = sdf2.format(d);
        String now = sdf3.format(d);
        try {
            String pwd = channelDao.queryChannel("aqy20active").getPassword().trim();
            userid = DesUtil.decode(userid, pwd);
            //查询中奖表
            HashMap prizemap = aqyDrawDao.hasDrawPrizelist(userid, month);
            if (prizemap == null || prizemap.size() < 0) {//无中奖信息
                throw new BussinessException("8881", "您未中奖，无法获取该奖品！");
            }
            int cnt=aqyDrawDao.deleteDraw(userid,month);

            if (cnt>0){
                redisService.hincr("PPTVDRAW_MOHTH_" + month, userid, -1);
                redisService.hincr("PPTVDRAW_STOCK", month, -1);//总抽奖次数
                redisService.hincr("PPTVDRAW_REC", day, -1);//当天中奖次数回退
                redisService.hincr("TOTAL_GIFT_"+month,String.valueOf(prizemap.get("PRIZEID")),-1);//中奖礼物减1
                redisService.hincr("PPTVDRAW_SEQ", day, -1);
            }
            logmap.put("userid", userid);
            resultcode = "0";
            errorinfo = "";
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            errorinfo = "出现异常，" + e.getMessage();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            }
        } finally {
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            return outpipe;
        }
    }
    /*中奖信息填写查询是否已中奖*/
    @RequestMapping(value = "/queryAqydrawinfo", method = RequestMethod.GET, produces = "application/json")
    public DataOutPipe<?> query2( @RequestParam Map params) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        logmap.put("forward", "queryAqydrawinfo");
        logmap.put("reqData", params);
        String resultcode = "0";
        String errorinfo = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//月份作为副key
        Date d = new Date();
        String month = sdf.format(d);
        try {
            String userid = String.valueOf(params.get("userid"));
            //解密
            String pwd = channelDao.queryChannel("aqy20active").getPassword();
            userid = DesUtil.decode(userid, pwd);
            logmap.put("userid", userid);
            //查询中奖表
            HashMap map = aqyDrawDao.hasDrawPrizelist(userid, month);
            if (map == null || map.size() < 0) {//无中奖信息
                throw new BussinessException("8005", "未中奖！");
            }
            HashMap map2 = aqyDrawDao.hasDrawPrizeDetail(userid,month);//查看保存中奖地址等信息表是否有数据（此表只能一个月存一条用户数据）
            if (map2 != null && map2.size() > 0) {//有中奖信息
                outpipe.setData(map2);
                throw new BussinessException("8010", "您已填写过该表！");
            }
            resultcode = "0";
            errorinfo = "";
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            errorinfo = "出现异常，" + e.getMessage();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            }
        } finally {
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            return outpipe;
        }
    }

    /*40元查询是否已抽过奖*/
    @RequestMapping(value = "/queryAqy40drawinfo", method = RequestMethod.GET, produces = "application/json")
    public DataOutPipe<?> query3(String params, HttpServletRequest request) throws Exception {
        DataOutPipe outpipe = new DataOutPipe();
        Map<String, Object> logmap = new HashMap<String, Object>();
        logmap.put("forward", "queryAqy40drawinfo");
        logmap.put("reqData", params);
        String resultcode = "0";
        String errorinfo = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//月份作为副key
        Date d = new Date();
        String month = sdf.format(d);
        try {
            String userid = request.getParameter("userid");
            String spid = request.getParameter("spid");
            //解密
            String pwd = channelDao.queryChannel("aqy20active").getPassword();
            userid = DesUtil.decode(userid, pwd);
            logmap.put("userid", userid);
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserid(userid);
            orderInfo.setSpid(spid);
            orderInfo.setCpid("youtudraw");
            //订购状态有效验证
            service.orderRelationVali(orderInfo);
            HashMap map = aqyDrawDao.hasDraw(userid,spid);
            if (map == null || map.size() < 0) {//无中奖信息
                //添加到表
                HashMap hashMap = new HashMap();
                hashMap.put("ID",aqyDrawDao.getNo());
                hashMap.put("USERID",userid);
                hashMap.put("PRIZEMONTH",month);
                hashMap.put("SPID",spid);
                hashMap.put("DETAIL","未中奖");
                aqyDrawDao.addPrizeRec(hashMap);
            }else{
                throw new BussinessException("8003", "本月已抽过奖！无法再次抽奖！");
            }
            resultcode = "0";
            errorinfo = "";
        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            errorinfo = "出现异常，" + e.getMessage();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            }
        } finally {
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            logmap.put("rspData", outpipe.getData());
            log.info(JSON.toJSONString(logmap));
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            return outpipe;
        }
    }

}
