package com.iamberry.rent.handlers.machine;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.iamberry.rent.face.efast.EfastRentService;
import com.iamberry.wechat.core.entity.rent.*;
import com.iamberry.wechat.face.member.MemberService;
import org.apache.commons.lang3.StringUtils;
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 com.iamberry.rent.face.machine.MachineService;
import com.iamberry.rent.face.order.RentOrderService;
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.face.admin.SystemService;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * 机器handler
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author  献
 * @tel     18271840547
 * @date    2017年3月10日
 */
@Controller
@RequestMapping("/wechat/machine")
public class MachineHandler {
    @Autowired
    private MachineService machineService;
    @Autowired
    private RentOrderService rentOrderService;
    @Autowired
    private SystemService systemService;
	@Autowired
    private EfastRentService efastRentService;
    @Autowired
    private MemberService memberService;

    /**
     * 获取机器信息
     * @return
     * @author LJK
     * @Time   2017年3月10日
     */
    @ResponseBody
    @RequestMapping("/machine_info")
    public ResultMsg getMachine(@RequestParam(value = "pageNO", required = false, defaultValue = "1") Integer pageNO,
            HttpServletRequest request) {
        Member member = WechatUtils.getUserBySession(request);
        MachineInfo info = new MachineInfo();
        ResultMsg rm = new ResultMsg();
       info.setMachineOpenid(member.getUserOpenid());
		//  info.setMachineOpenid("o-icas0dRzE7WYAEAmcX4BQCUyFo");
        info.setMachineInitState(1);
        List<MachineInfo> list = machineService.list(info);
        if (list == null || list.isEmpty()) {
            rm.setStatus(false);
            rm.setResultCode(ResultInfo.ERRORCODE);
            rm.setMessage("没有机器信息!");
            return rm;
        }
        rm.setStatus(true);
        rm.setResultCode(ResultInfo.SUCCESSCODE);
        rm.setMessage("");
        rm.setData(list);
        return rm;
    }
    
    /**
     * 同步机器信息：TDS、总水量
     * @return
     * @author 献
     * @Time   2017年3月10日
     */
    @RequestMapping("/sync_machine")
    @ResponseBody
    public ResponseJson syncMachineInfo(@RequestParam("tds") Integer tds, 
            @RequestParam("water_num") Integer water_num,
            @RequestParam("deviceId") String machineDeviceId,
            @RequestParam("state") Integer state,
            HttpServletRequest request) {
    	 Member member = WechatUtils.getUserBySession(request);
        MachineInfo info = new MachineInfo();
        info.setMachineTDS(tds);
        info.setMachineHaveWater(water_num);
        info.setMachineState(state);
		//info.setMachineOpenid("o-icas0dRzE7WYAEAmcX4BQCUyFo");
		info.setMachineOpenid(member.getUserOpenid());
        info.setMachineDeviceId(machineDeviceId);
        Integer res = machineService.syncMachine(info);
        if (res == null || res <= 0) {
            return new ResponseJson(200, "同步失败，请重试!", 500);
        }
        return new ResponseJson(200, "SUCCESS", 200);
    }
    
    /**
     * 用户获取：
     * 1.服务费抵扣券下拉框数据
     * 2.机器信息
     * @date 2017年3月22日
     * @author muzx
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_coupons_machine")
    public ResponseJson getServiceCouponSelect(HttpServletRequest req,
            @RequestParam(value = "machineId", required = false, defaultValue = "")String machineId){
        return machineService.listServiceCoupon(WechatUtils.getUserBySession(req).getUserOpenid(), machineId);
        /*return machineService.listServiceCoupon("o-icas0dRzE7WYAEAmcX4BQCUyFo", machineId);*/
    }
    
    /**
     * 续费支付,获取预支付id(第一次支付)
     * @return
     * @author 献
     * @Time   2017年3月13日
     */
    @ResponseBody
    @RequestMapping("/machine_pay")
    public ResponseJson machinePay(
            @RequestParam("machineId") Integer machineId,
            @RequestParam("year_num") Integer year,
            @RequestParam(value = "couponId", required = false) Integer couponId,
            HttpServletRequest request
            ) {
        Member member = WechatUtils.getUserBySession(request);
        MachineRecharge machineRecharge = new MachineRecharge();
        machineRecharge.setRechargeMachineId(machineId);
        machineRecharge.setRechargeDuration(year);
        machineRecharge.setRechargeOpenId(member.getUserOpenid());
        return machineService.requestPay(machineRecharge, couponId);
    }
    
    /**
     * 根据续费支付id 继续续费(第一次支付中断后,继续发起支付)
     * @param orderId
     * @return
     * @author 献
     * @Time   2017年3月13日
     */
    @RequestMapping("/recharge_pay")
    @ResponseBody
    public ResponseJson rechargeOrderIdPay(@RequestParam("orderId") String orderId) {
        return machineService.rechargeOrderIdPay(orderId);
    }
    
    /**
     * 根据 续费订单id 查询支付结果(是否支付成功,完成支付回调)
     * @date 2017年3月22日
     * @author muzx
     * @param rechargeOrderId
     * @return
     */
    @ResponseBody
    @RequestMapping("/check_recharge_pay_status")
    public ResultMsg checkRechargeStatus(
            @RequestParam(value = "rechargeOrderId", defaultValue = "", required = false) String rechargeOrderId){
        ResultMsg rm = new ResultMsg();
        rm.setMessage("参数错误!请刷新重试!");
        rm.setStatus(false);
        if(StringUtils.isEmpty(rechargeOrderId)){
            return rm;
        }
        MachineRecharge recharge = new MachineRecharge();
        recharge.setRechargeOrderId(rechargeOrderId);
        recharge = machineService.getRechargeByIdOrOrderId(recharge);
        if(recharge == null){
            return rm;
        }
        rm.setData(recharge);
        rm.setMessage("");
        rm.setStatus(true);
        return rm;
    }
    /**
     * 续费记录
     * @param request
     * @return
     * @author LJK
     * @Time   2017年3月13日
     */
    @RequestMapping("/recharge_list")
    @ResponseBody
    public ResultMsg rechargeList(HttpServletRequest request) {
        String rechargeMachineId = request.getParameter("rechargeMachineId");
        List<MachineRecharge> recharges = machineService.listRecharge(Integer.valueOf(rechargeMachineId));
        ResultMsg rm = new ResultMsg();
        if (recharges == null || recharges.isEmpty()) {
            rm.setStatus(false);
            rm.setResultCode(ResultInfo.ERRORCODE);
            rm.setMessage("");
            return rm;
        }
        rm.setStatus(true);
        rm.setResultCode(ResultInfo.SUCCESSCODE);
        rm.setMessage("");
        rm.setData(recharges);
        return rm;
    }
    
    /**
     * 订单详情中的送人接口
     * 2017年3月17日
     * @author muzx
     * @return
     */
    @ResponseBody
    @RequestMapping("/present_other")
    public ResultMsg presentOther(
            @RequestParam(value = "orderItemId", defaultValue = "", required = false) String orderItemId,
            HttpServletRequest request){
        return machineService.presentMachine(orderItemId, WechatUtils.getUserBySession(request).getUserOpenid());
    }
    
    /**
     * 查询用户的所有机器
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_machine_list")
    public ResultMsg selectMachineList(HttpServletRequest request) throws Exception {
    	ResultMsg msg = new ResultMsg();
    	MachineInfo machine = new MachineInfo();
    	Member member = WechatUtils.getUserBySession(request);
    	machine.setMachineOpenid(member.getUserOpenid());
    	List<MachineInfo> machineList = machineService.list(machine);
    	if (machineList != null && machineList.size() > 0) {
    		msg.setResultCode(ResultInfo.SUCCESSCODE);
    		msg.setStatus(true);
    		msg.setData(machineList);
    	} else {
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setMessage("您没有可用的机器!");
    	}
    	return msg;
    }
    
    /**
     * 收到的设备前台接口
     * 2017年3月17日
     * @author muzx
     * @return
     */
    @ResponseBody
    @RequestMapping("/received_machine")
    public ResultMsg receivedMachine(
            @RequestParam(value = "shareId", defaultValue = "", required = false)String shareId,
            HttpServletRequest request){
        return machineService.receiveMachine(shareId, WechatUtils.getUserBySession(request).getUserOpenid());
    }
    
    @ResponseBody
    @RequestMapping("/select_machineByDeviceId")
    public ResultMsg select_machineByDeviceId(
            @RequestParam(value = "deviceId", defaultValue = "", required = false)String deviceId,
            HttpServletRequest request){
    	ResultMsg msg = new ResultMsg();
    	MachineInfo machineinfo = new MachineInfo();
    	machineinfo.setMachineDeviceId(deviceId);
    	machineinfo = machineService.selectMachineById(machineinfo);
    	msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		msg.setData(machineinfo);
        return msg;
        
    }
    /**
     * 修改机器连接状态
     * @param deviceId
     * @param state
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateByDeviceId")
    public ResultMsg updateByDeviceId(
            @RequestParam(value = "deviceId", defaultValue = "", required = false)String deviceId,
            @RequestParam(value = "state", defaultValue = "", required = false)Integer state,
            HttpServletRequest request){
    	ResultMsg msg = new ResultMsg();
    	MachineInfo machineinfo = new MachineInfo();
    	machineinfo.setMachineDeviceId(deviceId);
    	machineinfo.setMachineConnectState(state);
    	Integer info = machineService.update(machineinfo);
    	if(1 == info){
    		msg.setResultCode(ResultInfo.SUCCESSCODE);
    		msg.setStatus(true);
    		msg.setData(machineinfo);
    	}else{
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setData(machineinfo);
    	}
        return msg;
        
    }
    
    /**
     * 检查四个滤芯是否达到更换标准
     * @param request
     * @param deviceId
     * @param filterT1		T1滤芯是否可更换  1：可以更换，2：不可以更换
     * @param filterT2
     * @param filterT3
     * @param filterT4
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/check_change_filter")
    public ResultMsg checkChangeFilter(HttpServletRequest request,
    		@RequestParam("deviceId") String deviceId,
    		@RequestParam("filterT1") Integer filterT1,
            @RequestParam("filterT2") Integer filterT2,
            @RequestParam("filterT3") Integer filterT3,
            @RequestParam("filterT4") Integer filterT4
            ) throws Exception {
    	ResultMsg msg = new ResultMsg();
    	Member member = WechatUtils.getUserBySession(request);
    	Map<String,Object> map = new HashMap<String,Object>();
    	MachineInfo machineinfo = new MachineInfo();
    	List<Integer> typeList = new ArrayList<Integer>();//用于存放因时间间隔不达标而不能更换滤芯的类型
    	RentChangeLogs rentChangeLogs = new RentChangeLogs();
    	rentChangeLogs.setLogsMachineDeviceId(deviceId);
    	rentChangeLogs.setLogsOpenid(member.getUserOpenid());
    	machineinfo.setMachineDeviceId(deviceId);
    	if (filterT1 == null || filterT2 == null || filterT3 == null || filterT4 == null) {
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setMessage("机器同步状态有误");
    		return msg;
    	}
    	//根据机器id查询机器信息
    	machineinfo = machineService.selectMachineById(machineinfo);
    	if (machineinfo == null) {
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setMessage("您没有可用的机器");
    		return msg;
    	}
    	//如果可用水量小于等于0，则租赁期限已到，不可再换滤芯
    	if (machineinfo.getMachineSurplusWater().intValue() <= 0) {
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setMessage("租赁期限已到，不可再换滤芯");
    		return msg;
    	}
    	//如果到期时间小于等于当前时间，则租赁期限已到，不可再换滤芯
    	if (machineinfo.getMachineStopDate().getTime() <= new Date().getTime()) {
    		msg.setResultCode(ResultInfo.ERRORCODE);
    		msg.setStatus(false);
    		msg.setMessage("租赁期限已到，不可再换滤芯");
    		return msg;
    	}
    	//获取滤芯更换间隔时间
    	ShopSystemRule shopSystemRuleOne = systemService.selectOneShopRuleById(235);
    	int num = shopSystemRuleOne.getRuleNum().intValue() * 24 * 60 * 60; //将滤芯更换间隔时间换算为秒为单位
    	//根据条件查询该机器换滤芯记录
    	List<RentChangeLogs> changeList = machineService.listSelectChangeLogs(rentChangeLogs);
    	if (changeList != null && changeList.size() > 0) {
    		for (RentChangeLogs changeLogs : changeList) {
    			//计算更换滤芯的当前时间与之前申请的时间之间的间隔是否大于滤芯更换间隔时间
    			if (new Date().getTime() - changeLogs.getLogsCreateTime().getTime() < num) {
    				typeList.add(changeLogs.getLogsFilterType());
    			}
    		}
    	}
    	//循环排除不能更换的滤芯
    	for (int i = 0;i < typeList.size();i++) {
    		int filterType = typeList.get(i);
    		switch (filterType) {
				case 1:filterT1 = 2;break;
				case 2:filterT2 = 2;break;
				case 3:filterT3 = 2;break;
				case 4:filterT4 = 2;break;
			}
    	}
		map.put("T1", filterT1);
    	map.put("T2", filterT2);
    	map.put("T3", filterT3);
    	map.put("T4", filterT4);
    	msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		msg.setData(map);
    	return msg;
    }

	/**
	 * 保存更换滤芯记录
	 * @param request
	 * @param losgsDTO
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/save_change_filter")
	public ResultMsg saveChangeFilter(HttpServletRequest request,
									  RentChangeLosgsDTO losgsDTO) throws Exception {
		MachineInfo machineinfo = new MachineInfo();
		ResultMsg msg = new ResultMsg();
		RentOrder rentOrder = new RentOrder();
		List<RentChangeLogs> list = new ArrayList<RentChangeLogs>();
		Member member = new Member();//WechatUtils.getUserBySession(request);
		machineinfo.setMachineDeviceId(losgsDTO.getLogsMachineDeviceId());
		//根据机器id查询机器信息
		machineinfo = machineService.selectMachineById(machineinfo);
		rentOrder.setRentOrderId(machineinfo.getMachineOrderId());
		//通过orderId查询租赁订单信息
		rentOrder = rentOrderService.getRentOrderByOrderId(rentOrder);
		if (losgsDTO.getFilterT1() != null && losgsDTO.getFilterT1().intValue() == 1) {
			RentChangeLogs logs = new RentChangeLogs();
			logs.setLogsOpenid(member.getUserOpenid());
			logs.setLogsOrderId(machineinfo.getMachineOrderId());
			logs.setLogsMachineDeviceId(losgsDTO.getLogsMachineDeviceId());
			logs.setLogsFilterType(1);
			logs.setLogsStatus(1);
			logs.setLogsRentType(rentOrder.getRentTypeId());
			logs.setLogsAddressInfo(losgsDTO.getLogsAddressInfo());
			logs.setLogsAddressName(losgsDTO.getLogsAddressName());
			logs.setLogsAddressTel(losgsDTO.getLogsAddressTel());
			list.add(logs);
		}
		if (losgsDTO.getFilterT2() != null && losgsDTO.getFilterT2().intValue() == 1) {
			RentChangeLogs logs = new RentChangeLogs();
			logs.setLogsOpenid(member.getUserOpenid());
			logs.setLogsOrderId(machineinfo.getMachineOrderId());
			logs.setLogsMachineDeviceId(losgsDTO.getLogsMachineDeviceId());
			logs.setLogsFilterType(2);
			logs.setLogsStatus(1);
			logs.setLogsRentType(rentOrder.getRentTypeId());
			logs.setLogsAddressInfo(losgsDTO.getLogsAddressInfo());
			logs.setLogsAddressName(losgsDTO.getLogsAddressName());
			logs.setLogsAddressTel(losgsDTO.getLogsAddressTel());
			list.add(logs);
		}
		if (losgsDTO.getFilterT3() != null && losgsDTO.getFilterT3().intValue() == 1) {
			RentChangeLogs logs = new RentChangeLogs();
			logs.setLogsOpenid(member.getUserOpenid());
			logs.setLogsOrderId(machineinfo.getMachineOrderId());
			logs.setLogsMachineDeviceId(losgsDTO.getLogsMachineDeviceId());
			logs.setLogsFilterType(3);
			logs.setLogsStatus(1);
			logs.setLogsRentType(rentOrder.getRentTypeId());
			logs.setLogsAddressInfo(losgsDTO.getLogsAddressInfo());
			logs.setLogsAddressName(losgsDTO.getLogsAddressName());
			logs.setLogsAddressTel(losgsDTO.getLogsAddressTel());
			list.add(logs);
		}
		if (losgsDTO.getFilterT4() != null && losgsDTO.getFilterT4().intValue() == 1) {
			RentChangeLogs logs = new RentChangeLogs();
			logs.setLogsOpenid(member.getUserOpenid());
			logs.setLogsOrderId(machineinfo.getMachineOrderId());
			logs.setLogsMachineDeviceId(losgsDTO.getLogsMachineDeviceId());
			logs.setLogsFilterType(4);
			logs.setLogsStatus(1);
			logs.setLogsRentType(rentOrder.getRentTypeId());
			logs.setLogsAddressInfo(losgsDTO.getLogsAddressInfo());
			logs.setLogsAddressName(losgsDTO.getLogsAddressName());
			logs.setLogsAddressTel(losgsDTO.getLogsAddressTel());
			list.add(logs);
		}
		//批量添加滤芯更换记录
		int sum = machineService.saveChangeLogs(list,rentOrder);
		if (sum > 0) {
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
		} else {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
		}
		return msg;
	}

	/**
	 * 根据机器id和openid查询更换过的滤芯集合
	 * @param request
	 * @param deviceId	设备（微信）id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/select_change_filter_list")
	public ResultMsg selectChangeFilterList(HttpServletRequest request,
						@RequestParam("deviceId") String deviceId) throws Exception {

		ResultMsg msg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);
		if (deviceId == null || "".equals(deviceId)) {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("没有该设备信息");
			return msg;
		}
		RentChangeLogs logs = new RentChangeLogs();
		logs.setLogsOpenid(member.getUserOpenid());
		logs.setLogsMachineDeviceId(deviceId);
		//根据机器id和openid查询更换过的滤芯集合
		List<RentChangeLogs> filterList = machineService.listChangeFilterLogs(logs);
		msg.setStatus(true);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setData(filterList);
		return msg;
	}

	/**
	 * 比拼水质(查询机器信息)
	 * @param request
	 * @param machineDeviceId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/waterCompete")
    public ResultMsg waterCompete(HttpServletRequest request,
				@RequestParam("deviceId") String machineDeviceId) throws Exception {
    	ResultMsg msg = new ResultMsg();
		if (machineDeviceId == null || machineDeviceId.equals("")){
			msg.setStatus(false);
			msg.setResultCode("500");
			return msg;
		}
		MachineInfo machineinfo = new MachineInfo();
		machineinfo.setMachineDeviceId(machineDeviceId);
		machineinfo = machineService.selectMachineById(machineinfo);
		msg.setResultCode("200");
		msg.setStatus(true);
		msg.setData(machineinfo);
    	return msg;

	}

	/**
	 * 新增水质比拼记录
	 * @param request
	 * @param machineDeviceId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/addCompetingRecords")
	public ResultMsg addCompetingRecords(HttpServletRequest request,
						@RequestParam("deviceId") String machineDeviceId) throws Exception{
		ResultMsg msg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);
		MachineInfo machineinfo = new MachineInfo();
		machineinfo.setMachineDeviceId(machineDeviceId);
		CompeteWaterInfo competeWaterInfo = new CompeteWaterInfo();
        member = memberService.getMemberByUserOpenId(member.getUserOpenid());
		//封装数据
		competeWaterInfo.setShareOneOpenId(member.getUserOpenid());
		competeWaterInfo.setShareMachineId(String.valueOf(machineinfo.getMachineId()));
		competeWaterInfo.setShareNickname(member.getUserNickname());
		competeWaterInfo.setMachineWaterTDS(machineinfo.getMachineTDS());
		competeWaterInfo.setMachineAmountWater(machineinfo.getMachineHaveWater());
        competeWaterInfo.setShareUserHead(member.getUserHead());
		Integer results = machineService.addCompeteWater(competeWaterInfo);
		if(results == 1){
			msg.setStatus(true);
			msg.setResultCode("200");
			msg.setData(competeWaterInfo.getShareId());
		}else{
			msg.setStatus(false);
			msg.setResultCode("500");
		}
		return msg;
	}

	/**
	 * 查询比拼水质记录
	 * @param request
	 * @param shareId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectCompeteWater")
	public ResultMsg selectCompeteWater(HttpServletRequest request,
							@RequestParam("shareId") String shareId){
		ResultMsg msg = new ResultMsg();
		if (shareId == null || shareId.equals("")){
			msg.setStatus(false);
			msg.setResultCode("500");
			return msg;
		}
		CompeteWaterInfo competeWaterInfo = machineService.selectCompeteWater(shareId);
		msg.setResultCode("200");
		msg.setStatus(true);
		msg.setData(competeWaterInfo);
		return msg;
	}
}
