package com.iamberry.wechat.handles.apparatus;

import com.iamberry.app.tool.util.HttpUtility;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.apparatus.Apparatus;
import com.iamberry.wechat.core.entity.integral.IntegralConfig;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.apparatus.ApparatusService;
import com.iamberry.wechat.face.integral.UseIntegralService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.service.ImberryConfig;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.SendMessageUtil;
import com.iamberry.wechat.tools.payUtil.RandomUtil;
import com.iamberry.wechat.tools.payUtil.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liuzhiwei on 2017/12/28.
 */
@Controller
@RequestMapping("/wechat/apparatus")
public class ApparatusHandler {

    private Logger logger = LoggerFactory.getLogger(ApparatusHandler.class);

    @Autowired
    private SendMessageUtil sendMessageUtil;
    @Autowired
    private ApparatusService apparatusService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MemberService memberService;

    /**
     * 分页查询用户机器信息
     * @param request
     * @param pageNO
     * @param pageSize
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_apparatus_page")
    public ResultMsg selectApparatusPage(HttpServletRequest request,
                                         @RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
                                         @RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize) throws Exception {
        ResultMsg msg = new ResultMsg();
        Member member = WechatUtils.getUserBySession(request);
        Apparatus apparatus = new Apparatus();
        apparatus.setUserOpenid(member.getUserOpenid());
        apparatus.setApparatusStatus(1);
        PageBean page = new PageBean();
        page.setPageNumber(pageNO);
        page.setPageSize(pageSize);
        page.initRecordBegin();
        apparatus.setPage(page);
        //分页查询用户绑定机器信息
        List<Apparatus> apparatusList = apparatusService.listApparatusPage(apparatus);
        msg.setData(apparatusList);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 发送短信
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/send_phone")
    public ResultMsg sendPhone(HttpServletRequest request,String phone) throws Exception {
        ResultMsg msg = new ResultMsg();

        if(phone.length() != 11){
            msg.setMessage("电话号码错误!");
            return msg;
        }

        //获取验证码
        String num = RandomUtil.getRandom();

        //使用request对象的getSession()获取session，如果session不存在则创建一个
        HttpSession session = request.getSession();

        String text = MessageFormat.format(ImberryConfig.SEND_VERIFICATION_PHONE, num);
        String result = codeService.informShipping(phone, text);

        //将数据存储到session中
        session.setAttribute("verification_code",num );
        session.setAttribute("verification_tel",phone );
        session.setAttribute("verification_date",new Date());

        if ("SUCCESS".equals(result)) {
            logger.info("短信发送成功，验证码为：" + num);
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            logger.info("短信发送失败：" + result);
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("短信发送失败");
            return msg;
        }
        return msg;
    }

    /**
     * 注册会员
     * @param request
     * @param member  userBirthDate
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_apparatus")
    public ResultMsg addApparatus(HttpServletRequest request,Member member,String code,String userBirthDateString) throws Exception {
        ResultMsg msg = new ResultMsg();
        Member memberInfo = WechatUtils.getUserBySession(request);
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        boolean isRegistered = false;
        if(memberInfo.getUserIdentity() == 1){
            isRegistered = true;
        }

        if(userBirthDateString != null && userBirthDateString != "" ){
            String[] ubds = userBirthDateString.split("-");
            Calendar calendar = Calendar.getInstance();
            calendar.set(Integer.valueOf(ubds[0]),Integer.valueOf(ubds[1])-1,Integer.valueOf(ubds[2]));
            calendar.set(Calendar.HOUR_OF_DAY, 0);//时
            calendar.set(Calendar.MINUTE, 0);//分
            calendar.set(Calendar.SECOND, 0);//秒
            member.setUserBirthDate(calendar.getTime());
        }

        if(memberInfo.getUserTel() == null || !memberInfo.getUserTel().equals(member.getUserTel())){
            //判断验证码
            //使用request对象的getSession()获取session，如果session不存在则创建一个
            HttpSession session = request.getSession();
            String verificationTel = (String) session.getAttribute("verification_tel");
            if(member.getUserTel() == null || !member.getUserTel().equals(verificationTel)){
                return new ResultMsg(false, ResultInfo.ERRORCODE, "手机验证失败!",null);
            }

            String verificationCode = (String) session.getAttribute("verification_code");
            if(code == null){
                return new ResultMsg(false, ResultInfo.ERRORCODE, "未填写验证码!",null);
            }
            code = code.trim();
            Date verificationDate = (Date) session.getAttribute("verification_date");
            Calendar nowTime = Calendar.getInstance();
            nowTime.setTime(verificationDate);
            nowTime.add(Calendar.MINUTE, 5);
            Date verData = nowTime.getTime();
            if(!verificationCode.equals(code) || (verData.getTime() < new Date().getTime())  ){
                return new ResultMsg(false, ResultInfo.ERRORCODE, "验证码不正确或已失效，请重新获取!",null);
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取换新时间期限
        ShopSystemRule renewRule =  systemService.selectOneShopRuleById(246);
        member.setUserOpenid(memberInfo.getUserOpenid());
        String barCode = request.getParameter("barCode");
        String apparatusStore = request.getParameter("apparatusStore");
        String buyDate = request.getParameter("buyDate");

        if (!StringUtil.isNotEmpty(barCode)
                ||!StringUtil.isNotEmpty(apparatusStore)
                ||!StringUtil.isNotEmpty(buyDate)) {
            return new ResultMsg(false, ResultInfo.ERRORCODE, "注册数据为空，请重新提交!",null);
        }
        //拼接日期信息
        buyDate = buyDate+" 00:00:00";
        Apparatus apparatus = new Apparatus();
        apparatus.setApparatusStatus(1);
        apparatus.setApparatusBarcode(barCode);
        //获取机器信息
        List<Apparatus> apparatusList = apparatusService.listApparatusPage(apparatus);
        if (apparatusList != null && apparatusList.size() > 0) {
            return new ResultMsg(false, ResultInfo.ERRORCODE, "该机器已被绑定!",null);
        }
        //获取rst系统产品信息,根据获取到的产品id查出对呀的产品颜色id
        Integer productColorId = 0;
        String json =  HttpUtility.httpsGet(ResultInfo.GET_MACHINE_INFO+barCode);
        if(json == null){
            return new ResultMsg(false, ResultInfo.ERRORCODE, "会员注册失败，获取机器信息失败!",null);
        }
        JSONObject machineJson = JSONObject.fromObject(json);
        JSONObject message = machineJson.getJSONObject("message");
        String isBeing = message.getString("isBeing");
        if(isBeing.equals("1")){
            String productId = message.getString("productId");//产品id
            productColorId = apparatusService.getColorIdByProductId(productId);
        }else{
            return new ResultMsg(false, ResultInfo.ERRORCODE, "会员注册失败，未找到该机器!",null);
        }
        apparatus.setColorId(productColorId);
        apparatus.setUserOpenid(memberInfo.getUserOpenid());
        apparatus.setApparatusBuyDate(format.parse(buyDate));
        apparatus.setApparatusWarrantyDate(updateDate(format.parse(buyDate),renewRule.getRuleNum().intValue()));
        apparatus.setApparatusStore(Integer.valueOf(apparatusStore));
        //注册会员
        boolean flag = apparatusService.registerMember(apparatus,member);
        if (flag) {

            if(!isRegistered){
                logger.info("新用户注册推送信息，用户openid为"+memberInfo.getUserOpenid());
                Date date = new Date();
                String dataText = format.format(date);
                try {
                    sendMessageUtil.registeredTemplate(
                            ResultInfo.REGISTERED_TITLE,
                            memberInfo.getUserNickname(),
                            "100",
                            dataText,
                            ResultInfo.REGISTERED,
                            memberInfo.getUserOpenid(),
                            ResultInfo.INDEX_DETAIL);
                } catch (Exception e) {
                    logger.info("注册推送信息失败，用户openid为"+memberInfo.getUserOpenid());
                }
            }

            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            return new ResultMsg(false, ResultInfo.ERRORCODE, "会员注册失败，请重新注册!",null);
        }
        return msg;
    }

    /**
     * 修改日期 增加月
     * @param date
     * @param month
     * @return
     * @throws Exception
     */
    public Date updateDate(Date date,int month) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }


    /**
     * 注册会员
     * @param request
     * @param code
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/del_tooth")
    public ResultMsg addApparatus(HttpServletRequest request,String code) throws Exception {
        if(code == null){
            return new ResultMsg(false, ResultInfo.ERRORCODE, "删除失败，牙刷编号为空",null);
        }
        Integer flag = apparatusService.delTooth(code);
        return new ResultMsg(false, ResultInfo.ERRORCODE, "会员注册失败，请重新注册!",null);
    }

}
