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.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.apparatus.ApparatusService;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.payUtil.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
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.text.SimpleDateFormat;
import java.util.*;

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

    @Autowired
    private ApparatusService apparatusService;
    @Autowired
    private SystemService systemService;

    /**
     * 分页查询用户机器信息
     * @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
     * @param member
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("add_apparatus")
    public ResultMsg addApparatus(HttpServletRequest request,Member member) throws Exception {
        ResultMsg msg = new ResultMsg();
       /* String machinrJson =  HttpUtility.httpsGet("https://rst.iamberry.com/mcahine/getMachineInfo?barCode=AURORAA30180100005");*/

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Member memberInfo = WechatUtils.getUserBySession(request);
        //获取换新时间期限
        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)) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("注册数据为空，请重新提交!");
            return msg;
        }
        //拼接日期信息
        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) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("该机器已被绑定！");
            return msg;
        }
        //获取rst系统产品信息,根据获取到的产品id查出对呀的产品颜色id
        Integer productColorId = 0;
        String json =  HttpUtility.httpsGet(ResultInfo.GET_MACHINE_INFO+barCode);
        if(json == null){
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("会员注册失败，获取机器信息失败!");
            return msg;
        }
        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{
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("会员注册失败，未找到该机器!");
            return msg;
        }
        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) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("会员注册失败，请重新注册!");
            return msg;
        }
        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();
    }
}
