package com.iamberry.wechat.handles.warranty;

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.member.Member;
import com.iamberry.wechat.core.entity.warrantyCard.WarrantyCard;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.phone.PhoneCodeService;
import com.iamberry.wechat.face.warranty.WarrantyService;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
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.http.HttpServletRequest;
import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 质保卡
 * Created by liuzhiwei on 2017/12/14.
 */
@Controller
@RequestMapping("/wechat/warranty")
public class WarrantyCardHandler {

    @Autowired
    private SystemService systemService;
    @Autowired
    private WechatUtils wechatUtils;
    @Autowired
    private PhoneCodeService phoneCodeService;
    @Autowired
    private WarrantyService warrantyService;


    /**
     * 查询个人质保卡集合信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_warranty_list")
    public ResultMsg selectWarrantyList(HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();
        WarrantyCard card = new WarrantyCard();
        Member member  = wechatUtils.getUserBySession(request);
        card.setUserOpenId(member.getUserOpenid());
        card.setCardTypeState(1);
        card.setPage(null);

        //查询质保卡集合
        List<WarrantyCard> cardList = warrantyService.listWarrantyCard(card);
        msg.setData(cardList);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 根据电话号码查询百胜订单信息
     * @param request
     * @param member
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_efast_by_tel")
    public ResultMsg selectEfastByTel(HttpServletRequest request, Member member) throws Exception {
        ResultMsg msg = new ResultMsg();
        String phone = member.getUserTel();//"13590159563";
        Map<String,Object> map = new HashMap<String,Object>();
        StringBuilder txtOrderId = new StringBuilder();
        int num = 0;
        //获取cookie值
        ShopSystemRule rule =  systemService.selectOneShopRuleById(244);

        String url = NameUtils.getConfig("efast_order_url") + phone;
        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");
        //System.out.println("trs="+trs);
        for (Element tr : trs) {
            Elements tds = tr.getElementsByTag("td");
            for (int i = 0; i < tds.size();i++) {
                Element td = tds.get(i);
                //校验时间格式正则表达式
                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) {
                    Element tdId = tds.get(i+1);
                    //获取下一个td中的span标签内的内容
                    Elements spans = tdId.getElementsByTag("span");
                    Element span = spans.get(0);
                    String spanText = span.html().toString();
                    spanText = span.html().toString().substring(0,spanText.indexOf("&lt;"));
                    num++;
                    txtOrderId.append(spanText);
                    txtOrderId.append(":");
                }
            }
        }
        map.put("num",num);
        map.put("txtOrderId",txtOrderId.toString());
        msg.setData(map);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 添加质保卡信息
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/add_warranty_card_list")
    public ResultMsg addWarrantyCardList(HttpServletRequest request, Member member) throws Exception {
        ResultMsg msg = new ResultMsg();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cardWatero = request.getParameter("cardWatero");
        String cardProvince = request.getParameter("cardProvince");
        String cardCity = request.getParameter("cardCity");
        String cardDistrict = request.getParameter("cardDistrict");
        String txtOrderId = request.getParameter("txtOrderId");
        //查询用户信息
        Member memberInfo = wechatUtils.getUserBySession(request);
        if (memberInfo == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该用户不存在!");
            return msg;
        }
        member.setUserId(memberInfo.getUserId());
        member.setUserOpenid(memberInfo.getUserOpenid());

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

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

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

        //添加机器信息
        boolean flag = warrantyService.addWarrantyList(txtOrderId,member,cardWatero,
                cardProvince,cardCity,cardDistrict);
        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("/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 = phoneCodeService.sms(phone);
        if (json.getReturnCode() == 200) {
            msg.setStatus(true);
        } else {
            msg.setStatus(false);
        }
        msg.setResultCode(json.getReturnCode().toString());
        return msg;
    }

    /**
     * 获取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("/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");
        map.put("numberProvince",numberProvince);
        map.put("numberCity",numberCity);
        map.put("numberDistrict",numberDistrict);
        msg.setData(map);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }
}
