package com.iamberry.wechat.handles.qrcode;

import com.iamberry.app.tool.util.HttpUtility;
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.machineNumber.MachineNumber;
import com.iamberry.wechat.core.entity.machineNumber.WarrantyCard;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.machineNumber.MachineNumberService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.tools.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
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.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import org.apache.http.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by liuzhiwei on 2017/7/21.
 * 上海
 */
@Controller
@RequestMapping("/wechat/qrcode")
public class MachineQrCodeHandler {

    @Autowired
    private MachineNumberService machineNumberService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private SystemService systemService;

    /**
     * 查询我的机器列表
     * @param request
     * @param pageNO
     * @param pageSize
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_admin_machine")
    public ResultMsg selectAdminMachine(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();
        MachineNumber machineNumber = new MachineNumber();
        Member member  = WechatUtils.getUserBySession(request);

        machineNumber.setPage(null);
        machineNumber.setNumberOpenId(member.getUserOpenid());
        machineNumber.setNumberStatus(1);//启用状态

        //分页查询机器编号集合
        List<MachineNumber> numberList = machineNumberService.listMachineNumber(machineNumber);

        msg.setData(numberList);
        msg.setStatus(true);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        return msg;
    }

    /**
     * 关注watero公众号后，进入修改用户机器信息页面
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/_update_machine")
    public ResultMsg updateMachineUI(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        MachineNumber machineNumber = new MachineNumber();
        String machineId = request.getParameter("machineId");
        Member memberInfo = WechatUtils.getUserBySession(request);

        if (machineId == null || "".equals(machineId)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("机器信息不存在,请重新进入!");
            return msg;
        }

        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在,请重新关注!");
            return msg;
        }
        machineNumber.setNumberId(Integer.parseInt(machineId));
        //根据条形码查询该机器信息
        List<MachineNumber> machineList = machineNumberService.listMachineNumber(machineNumber);
        if (machineList == null || machineList.size() == 0) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("机器信息不存在,请重新进入!");
            return msg;
        }
        MachineNumber machine = machineList.get(0);
        Map map = new HashMap();
        map.put("machine",machine);
        map.put("memberInfo",memberInfo);
        msg.setData(map);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 关注watero公众号后，完善用户信息
     * @param member
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_user_info")
    public ResultMsg updateUserInfo(Member member,HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Date date=null;
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        String numberSalesTime = request.getParameter("numberSalesTime");
        MachineNumber machineNumber = new MachineNumber();
        Member memberInfo = WechatUtils.getUserBySession(request);
        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在!");
            return msg;
        }

        //验证手机验证码是否正确
        ResponseJson json = codeService.validCode(member.getUserTel(),member.getPhoneCode());
        if (json.getReturnCode() != 200) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("验证码不正确,请重新输入!");
            return msg;
        }
        member.setUserId(memberInfo.getUserId());

       /* machineNumber.setNumberBarcode(member.getNumberBarcode());

        //根据条形码查询该机器信息
        List<MachineNumber> machineList = machineNumberService.listMachineNumber(machineNumber);
        if (machineList == null || machineList.size() == 0) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该机器信息不存在,请重新扫描条形码!");
            return msg;
        }

        MachineNumber machine = machineList.get(0);
        if (machine.getNumberOpenId() != null && !"".equals(machine.getNumberOpenId())) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该机器信息已被绑定，不能重复绑定!");
            return msg;
        }*/

        machineNumber.setNumberOpenId(memberInfo.getUserOpenid());
        machineNumber.setNumberSalesTime(formatter.parse(numberSalesTime));
        machineNumber.setNumberSubTime(new Date());

        //修改用户信息
        boolean flag = machineNumberService.addUserAndNumber(member,machineNumber);
        if (flag) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
            msg.setMessage("恭喜您,信息已完善!");
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("机器编码不存在,请重新扫描条形码!");
        }
        return msg;
    }

    /**
     * 关注watero公众号后，修改用户信息
     * @param member
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_user_machine_info")
    public ResultMsg updateMachineUserInfo(Member member,HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Date date=null;
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        String numberSalesTime = request.getParameter("numberSalesTime");
        MachineNumber machineNumber = new MachineNumber();
        Member memberInfo = WechatUtils.getUserBySession(request);
        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在!");
            return msg;
        }

        //验证手机验证码是否正确
        ResponseJson json = codeService.validCode(member.getUserTel(),member.getPhoneCode());
        if (json.getReturnCode() != 200) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("验证码不正确,请重新输入!");
            return msg;
        }
        member.setUserId(memberInfo.getUserId());

        machineNumber.setNumberBarcode(member.getNumberBarcode());

        //根据条形码查询该机器信息
        List<MachineNumber> machineList = machineNumberService.listMachineNumber(machineNumber);
        if (machineList == null || machineList.size() == 0) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改失败,请重新进入该页面!");
            return msg;
        }

        /*MachineNumber machine = machineList.get(0);
        if (machine.getNumberOpenId() != null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该机器信息已被绑定，不能重复绑定!");
            return msg;
        }*/

        machineNumber.setNumberOpenId(memberInfo.getUserOpenid());
        machineNumber.setNumberSalesTime(formatter.parse(numberSalesTime));
        machineNumber.setNumberSubTime(new Date());

        //修改用户信息
        boolean flag = machineNumberService.updateUserAndNumber(member,machineNumber);
        if (flag) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
            msg.setMessage("恭喜您,信息已修改!");
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改失败,请重新进入该页面!");
        }
        return msg;
    }

    @RequestMapping("/_add_warranty")
    public void addWarrantyUI(HttpServletRequest request,HttpServletResponse res) throws ServletException, IOException {
        Member memberInfo = WechatUtils.getUserBySession(request);
        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo != null && memberInfo.getUserStatus() == 2) {
            request.getRequestDispatcher("/view/warranty_card.html").forward(request,res);
        } else {
            request.getRequestDispatcher("/view/guanzhu.html").forward(request,res);
        }
    }

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 获取ip地址, 若多级代理,第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 获取地址信息
     * @param ip
     * @return
     */
    public static Map<String,Object> getLocation(String ip) {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            JSONObject json = new JSONObject(
                    HttpUtility.httpsGet(MessageFormat.format(NameUtils.getConfig("SINA_IP_URL"),ip)));
            String province = json.getString("province");
            String city = json.getString("city");
            String district = json.getString("district");
            map.put("province",province);
            map.put("city",city);
            map.put("district",district);
        } catch (ParseException | IOException | JSONException e) {
            System.out.println("------------获取地址出错------------");
        }
        return map;
    }

    /**
     * 发送手机验证码
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/send_phone_code")
    public ResultMsg sendPhoneCode(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        String phone = request.getParameter("phone");
        if (phone == null || "".equals(phone)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("手机号码不能为空!");
            return msg;
        }
        //发送手机验证码
        ResponseJson json = codeService.sms(phone);
        if (json.getReturnCode() == 200) {
            msg.setStatus(true);
        } else {
            msg.setStatus(false);
        }
        msg.setResultCode(json.getReturnCode().toString());
        return msg;
    }

    /**
     * 根据经纬度通过腾讯地址位置
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/get_location_by_qq")
    public ResultMsg getLocationByQq(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();
        //纬度
        String latitude = request.getParameter("latitude");
        //经度
        String longitude = request.getParameter("longitude");
        if (!StringUtils.isNotEmpty(latitude)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("纬度不能为空!");
            return msg;
        }
        if (!StringUtils.isNotEmpty(longitude)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("经度不能为空!");
            return msg;
        }
        JSONObject json = new JSONObject(
                HttpUtility.httpsGet(MessageFormat.format(NameUtils.getConfig("LOCATION_QQ_URL"),latitude,longitude)));
        JSONObject resultJson = json.getJSONObject("result");
        JSONObject locationJson = resultJson.getJSONObject("ad_info");
        String numberProvince = locationJson.getString("province");
        String numberCity = locationJson.getString("city");
        String numberDistrict = locationJson.getString("district");
        System.out.println("locationJson="+locationJson);
        map.put("numberProvince",numberProvince);
        map.put("numberCity",numberCity);
        map.put("numberDistrict",numberDistrict);
        msg.setData(map);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 查询百胜订单信息
     * @param request
     * @param member
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_efast_order_num")
    public ResultMsg selectEfastOrderNum(HttpServletRequest request, Member member) throws Exception {
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();
        StringBuilder txtTime = new StringBuilder();
        int num = 0;
        //获取cookie值
        ShopSystemRule rule =  systemService.selectOneShopRuleById(244);

        String url = NameUtils.getConfig("efast_order_url") + member.getUserTel();
        Map<String,String> params = new HashMap<String,String>();
        String cookie = rule.getRuleDesc();
        //查询百胜订单信息
        String str = HttpClient431Util.doGet(params,url,null,null,cookie);
        Document html = Jsoup.parse(str);
        Elements trs = html.body().getElementsByTag("tr");
        for (Element tr : trs) {
            Elements tds = tr.getElementsByTag("td");
            for (Element td : tds) {
                //校验时间格式正则表达式
                String timeTag = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-9]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
                String tdText = td.html().toString();
                if (tdText.length() > 24) {
                    tdText = tdText.substring(4, 24).trim();
                } else {
                    tdText = tdText.substring(0, tdText.length() - 1).trim();
                }
                Pattern p = Pattern.compile(timeTag);
                Matcher matcher = p.matcher(tdText);
                boolean flag = matcher.matches();
                if (flag) {
                    num++;
                    txtTime.append(tdText);
                    txtTime.append(",");
                }
            }
        }
        map.put("num",num);
        map.put("txtTime",txtTime.toString());
        msg.setData(map);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 添加质保卡信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_warranty_card")
    public ResultMsg addWarrantyCard(HttpServletRequest request, Member member) throws Exception {
        ResultMsg msg = new ResultMsg();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String numberWatero = request.getParameter("numberWatero");
        String numberProvince = request.getParameter("numberProvince");
        String numberCity = request.getParameter("numberCity");
        String numberDistrict = request.getParameter("numberDistrict");

        List<MachineNumber> list = new ArrayList<MachineNumber>();
        Member memberInfo = WechatUtils.getUserBySession(request);
        String txtTime = request.getParameter("txtTime");
        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在!");
            return msg;
        }
        member.setUserId(memberInfo.getUserId());

        if (!StringUtils.isNotEmpty(numberProvince)) {
            String ip = getIp(request);
            Map<String,Object> locations = getLocation(ip);
            if (StringUtils.isNotEmpty((String)locations.get("province"))) {
                numberProvince = (String)locations.get("province");
                numberCity = (String)locations.get("city");
                numberDistrict = (String)locations.get("district");
            }
        }

        if (!StringUtils.isNotEmpty(numberWatero)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("水质范围为空,请重新填写水质范围!");
            return msg;
        }

        //验证手机验证码是否正确
        ResponseJson code = codeService.validCode(member.getUserTel(),member.getPhoneCode());
        if (code.getReturnCode() != 200) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("验证码不正确,请重新输入!");
            return msg;
        }

        //循环添加机器信息
        if (txtTime != null && !"".equals(txtTime)) {
            txtTime = txtTime.substring(0,txtTime.lastIndexOf(","));
            String[] times = txtTime.split(",");
            for (int i = 0;i < times.length;i++) {
                MachineNumber machineNumber = new MachineNumber();
                machineNumber.setNumberOpenId(memberInfo.getUserOpenid());
                machineNumber.setNumberSalesTime(format.parse(times[i]));
                machineNumber.setNumberWatero(Integer.parseInt(numberWatero));
                machineNumber.setNumberProvince(numberProvince);
                machineNumber.setNumberCity(numberCity);
                machineNumber.setNumberDistrict(numberDistrict);
                list.add(machineNumber);
            }
        }

        //添加机器信息
        boolean flag = machineNumberService.addMachineNumberList(list, memberInfo.getUserOpenid(), member);
        if (flag) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
        }
        return msg;
    }

    /**
     * 查询质保卡信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_warranty_card_list")
    public ResultMsg selectWarrantyCardList(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        Member memberInfo = WechatUtils.getUserBySession(request);
        List<WarrantyCard> cardList = new ArrayList<WarrantyCard>();
        //查询用户信息
        memberInfo = memberService.getMemberByUserOpenId(memberInfo.getUserOpenid());
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在!");
            return msg;
        }

        //获取换新时间期限
        ShopSystemRule renewRule =  systemService.selectOneShopRuleById(242);
        //获取质保时间期限
        ShopSystemRule endRule =  systemService.selectOneShopRuleById(243);

        MachineNumber machineNumber = new MachineNumber();
        machineNumber.setPage(null);
        machineNumber.setNumberOpenId(memberInfo.getUserOpenid());
        machineNumber.setNumberStatus(1);//启用状态

        //分页查询机器编号集合
        List<MachineNumber> numberList = machineNumberService.listMachineNumber(machineNumber);

        if (numberList == null && numberList.size() <= 0) {
            msg.setStatus(false);
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setMessage("您没有质保卡信息!");
            return msg;
        }

        //将查出的机器信息存入质保卡信息列表中
        for (MachineNumber number : numberList) {
            WarrantyCard card = new WarrantyCard();
            card.setCardName("美国WaterO净饮水一体机");
            card.setCardDes("一年换新,十年质保");
            card.setCardBarcode(number.getNumberBarcode());
            card.setCardId(number.getNumberId());
            card.setCardTel(memberInfo.getUserTel());
            card.setCardSaleTime(number.getNumberSalesTime());
            card.setCardEndTime(updateDate(number.getNumberSalesTime(),endRule.getRuleNum().intValue()));
            card.setCardRenewTime(updateDate(number.getNumberSalesTime(),renewRule.getRuleNum().intValue()));
            cardList.add(card);
        }

        msg.setData(cardList);
        msg.setStatus(true);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        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();
    }
}
