package com.iamberry.rent.service.machine;

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

import com.iamberry.rent.face.efast.EfastRentService;
import com.iamberry.wechat.core.entity.rent.*;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.iamberry.exception.ServiceException;
import com.iamberry.rent.face.machine.MachineService;
import com.iamberry.rent.face.rebate.OrderRebateService;
import com.iamberry.rent.service.machine.mapper.MachineMapper;
import com.iamberry.rent.service.order.mapper.RentOrderMapper;
import com.iamberry.rent.service.order.mapper.ServiceCouponMapper;
import com.iamberry.rent.service.rebate.mapper.OrderRebateMapper;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.wechat.ConfigService;
import com.iamberry.wechat.iot.WechatIotUtils;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;

import net.sf.json.JSONObject;
/**
 * 机器业务实现类
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author  献
 * @tel     18271840547
 * @date    2017年3月9日
 */
@Service
public class MachineServiceImpl implements MachineService {

    @Autowired
    private MachineMapper machineMapper;
    @Autowired
    private RentOrderMapper rentOrderMapper;
    @Autowired
    private ConfigService configService;
    private static final Logger LOGGER = LoggerFactory.getLogger(MachineService.class);
    @Autowired
    private ServiceCouponMapper couponMapper;
    @Autowired
    private PayService payService;
    @Autowired
    private OrderRebateService orderRebateService;
    @Autowired
    private OrderRebateMapper orderRebateMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private EfastRentService efastRentService;

    @Override
    public int initBefore(MachineInfo machineInfo) throws ServiceException {
        // TODO Auto-generated method stub
        if (machineInfo == null || machineInfo.getMachineDeviceId() == null
                || machineInfo.getMachineOpenid() == null) {
            return 0;
        }

    	// 激活时间
    	Date nowDate = new Date();

        // 查询机器信息 , 只有没有激活的机器才能绑定
        String openid = machineInfo.getMachineOpenid();
        machineInfo.setMachineOpenid(null);
        List<MachineInfo> infos = machineMapper.list(machineInfo);
        if (infos == null || infos.isEmpty()) {
            LOGGER.error("{'errorCode':{}, 'msg':'机器信息不存在，请管理员审核!', 'deviceid':'{}'}", 500, machineInfo.getMachineDeviceId());
            return 0;
        }
        MachineInfo temp = infos.get(0);
        if (temp.getMachineInitState() != 2) {
            return 500;         // 已经激活的机器不能做激活使用，留待优化：查询续费记录中没有下发成功的命令,如果存在，则下发续费指令
        }

        // 激活
        machineInfo.setMachineOpenid(openid);
        List<RentOrderItem> list = rentOrderMapper.listInitCode(machineInfo.getMachineOpenid()); // 自己拥有订单
        RentOrderItem item = null;
        if (list != null && !list.isEmpty()) {
            item = list.get(0); // 从订单中选择第一个做激活使用
        } else {
            item = rentOrderMapper.getWaitInit(machineInfo.getMachineOpenid()); // 别人分享的订单
        }
        if (item == null) {
            return 0;
        }

        // 修改订单激活码状态
        item.setItemInitCodeOldState(1);
        item.setItemCodeState(2);
        Integer res = rentOrderMapper.update(item);
        if (res == null || res <= 0) {
            LOGGER.error("{'method':'{}', 'deviceId':'{}', 'openid':'{}', 'itemId':{}}",
            		"修改订单项中状态失败", machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), item.getItemId());
            return 0;
        }

        // 准备命令
        // 计算下发的小时数:结束时间 - 当前时间 / 1000 = x 秒  / 60 = y 分 / 60 = z 小时
        long hour = (DateTimeUtil.addMonth(item.getItemUseYears()).getTime() - nowDate.getTime()) / 1000 / 60 / 60;
        String hourStr = WechatIotUtils.align(Long.toString(hour));							// 补0
        String waterNum = WechatIotUtils.align(item.getItemMachineNum().toString());		// 补0
        String message = String.format(WechatIotUtils.INIT_MACHINE_COMMAND, hourStr, waterNum);

        // 封装数据 & 修改机器的状态 说明：通过行级锁保证正确性，一旦A 修改 deviceid='ABC'的记录后，那么后来者在A未提交事务之前，无法修改ABC记录,需要等待A将事务提交，释放行级锁
        temp.setMachineSurplusWater(item.getItemMachineNum());
        temp.setMachineTotalWater(item.getItemMachineNum());
        temp.setMachineStopDate(DateTimeUtil.addMonth(item.getItemUseYears()));
        temp.setMachineConnectState(1);         // 修改机器的状态为已连接
        temp.setMachineInitState(3);            // 激活中
        temp.setMachineActivationTime(nowDate);//激活时间
        temp.setMachineState(1);                // 修改为正常使用
        temp.setMachineOrderId(list.get(0).getItemOrderId());
        temp.setMachineOpenid(openid);
        temp.setMachineInitCode(list.get(0).getItemInitCode());
        temp.setMachineNextCommand(message);
        res = machineMapper.update(temp);
        if (res == null || res <= 0) {
            LOGGER.error("{'method':'{}', 'deviceId':'{}', 'openid':'{}', 'itemId':{}}",
            		"修改机器信息失败", machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), item.getItemId());
            throw new ServiceException(500, "修改机器信息失败！");
        }


        // 发送消息 : 注意，此处存在待优化的逻辑，在事务中使用HTTP，导致行锁长时间的被当前事务持有，其他事务必须等待
//        JSONObject json = WechatIotUtils.send(configService.getAccessToken(), message, 
//                machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), "gh_2674097b2442");
//        if (json == null || json.toString().indexOf("errcode") != -1) {
//            LOGGER.error("{'method':{}, 'msg':{}}", "发送激活信息失败", json.toString());
//            throw new ServiceException(500, "激活命令下发成功，请重试!");
//        }
//        if (json.getInt("ret") != 0) {
//        	LOGGER.error("{'method':{}, 'msg':{}}", "发送激活信息失败", json.toString());
//        	throw new ServiceException(500, "激活命令下发失败，请重试!");
//        }
//        LOGGER.info("{'deviceId':'{}', 'method':'INIT_SEND_SUCCESS', 'send_msg':'{}'}", machineInfo.getMachineDeviceId(), json.toString());
        return 1;
    }

	@Override
	public int init(String openid, String deviceId) throws ServiceException {
		// TODO Auto-generated method stub
		// 抽象机器
		MachineInfo machineInfo = new MachineInfo();
		machineInfo.setMachineOpenid(openid);
		machineInfo.setMachineDeviceId(deviceId);

		// 查询机器是否存在
		List<MachineInfo> list = machineMapper.list(machineInfo);
		if (list.size() != 1) {
			return 0;
		}

		// 判断激活还是续费
		if (list.get(0).getMachineInitState() != 3 || list.get(0).getMachineInitState() == 1) {
			// 续费
            LOGGER.info(deviceId + ",续费流程");
			return rechargeAfter(openid, deviceId);
		}
		// 激活

		// 查询激活订单是否存在
		RentOrder orderIdByInitCode = rentOrderMapper.getOrderIdByInitCode(list.get(0).getMachineInitCode());
		if (orderIdByInitCode == null || StringUtils.isEmpty(orderIdByInitCode.getRentOrderId())) {
			return 0;
		}

		// 修改机器状态
		machineInfo.setMachineInitState(1);			// 已激活
		machineInfo.setMachineNextCommand("");		// 清空命令
		Integer res = machineMapper.update(machineInfo);
        if (res == null || res <= 0) {
            LOGGER.error("{'method':'{}', 'deviceId':'{}', 'openid':'{}', 'orderId':{}}",
            		"修改机器信息失败", machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), orderIdByInitCode);
            return 0;
        }

        // 成功 & 触发返利 !!! 注意，此处触发返利的订单所属人，非当前激活订单用户
        if (!orderRebateService.saveRentOrderRebate(orderIdByInitCode.getRentOrderId(), orderIdByInitCode.getRentOpenid())) {
        	throw new ServiceException(501, "init - 触发返利任务失败!");
        }

		return 1;
	}

    @Override
    public List<MachineInfo> list(MachineInfo info) {
        // TODO Auto-generated method stub
        return machineMapper.list(info);
    }

    @Override
    public Integer syncMachine(MachineInfo info) {
        // TODO Auto-generated method stub
        int state = info.getMachineState();
        info.setMachineState(null);
        List<MachineInfo> infos = machineMapper.list(info);
        if (infos == null || infos.size() != 1) {
            return 0;
        }
        // TDS
        if (info.getMachineTDS() <= -1) {
            info.setMachineTDS(null);
        }
        //计算剩余水量
        int surplusWater = infos.get(0).getMachineTotalWater() - info.getMachineHaveWater();

        // 不能修改机器所属人
        info.setMachineOpenid(null);
        info.setMachineState(state);
        info.setMachineId(infos.get(0).getMachineId());
        info.setMachineSurplusWater(surplusWater);
        info.setMachineConnectState(1);
        return machineMapper.update(info);
    }

    @Override
    public ResponseJson listServiceCoupon(String openId, String machineId) {
        ResponseJson rj = new ResponseJson();
        rj.setResultCode(200);
        rj.setReturnCode(500);
        rj.setResultMsg("参数有误!该机器不可以续费!");
        if(StringUtils.isEmpty(machineId)){
            return rj;
        }
        //服务费抵扣券下拉框
        ServiceCouponInfo couponInfo = new ServiceCouponInfo();
        couponInfo.setServiceStatus(1);         // 未使用的
        couponInfo.setServiceOpenId(openId);
        List<ServiceCouponInfo> couponList = couponMapper.list(couponInfo);

        //机器信息
        MachineInfo mac = new MachineInfo();
        mac.setMachineOpenid(openId);
        mac.setMachineId(Integer.parseInt(machineId));
        List<MachineInfo> list = machineMapper.list(mac);
        if(list == null || list.size() != 1){
            return rj;
        }
        rj.setResultMsg("SUCCESS");
        rj.setReturnCode(200);
        rj.addResponseKeyValue("couponList", couponList);
        rj.addResponseKeyValue("machine", list.get(0));
        return rj;
    }

    @Override
    public ResponseJson requestPay(MachineRecharge machineRecharge, Integer couponId) {
        // TODO Auto-generated method stub
        // 校验机器的状态
        MachineInfo info = new MachineInfo();
        info.setMachineId(machineRecharge.getRechargeMachineId());
        info.setMachineOpenid(machineRecharge.getRechargeOpenId());
        List<MachineInfo> infos = machineMapper.list(info);
        if (infos == null || infos.size() != 1) {
            // 没有找到机器
            return new ResponseJson(200, "NOT_FOUND", 404);
        }
        // 只有已激活 & 已连接的机器才能续费
        info = infos.get(0);
        if (info.getMachineConnectState() != 1 || info.getMachineInitState() != 1) {
            return new ResponseJson(200, "MACHINE_STATE_ERROR", 500);
        }

        // 拼装参数
        int discount = 0;
        ServiceCouponInfo couponInfo = null;
        if (couponId != null && couponId != 0) {
            couponInfo = new ServiceCouponInfo();
            couponInfo.setServiceId(couponId);
            couponInfo.setServiceStatus(1);         // 未使用的
            couponInfo.setServiceOpenId(machineRecharge.getRechargeOpenId());
            List<ServiceCouponInfo> couponInfos = couponMapper.list(couponInfo);
            if (couponInfos != null && !couponInfos.isEmpty()) {
                couponInfo = couponInfos.get(0);
                discount = couponInfo.getServiceMoney();
                couponInfo.setServiceStatus(2);
                couponMapper.update(couponInfo);    //改為已使用
            }
        }
        if (couponInfo == null) {
            machineRecharge.setRechargeCouponId(0);
        } else {
            machineRecharge.setRechargeCouponId(couponId);
        }
        // 保存数据库
        String orderId = "XF001" + OrderNOUtil.createOrderCode(info.getMachineId());
        machineRecharge.setRechargeOrderId(orderId);

        RentTypeInfo rentTypeInfo = getRentType(machineRecharge.getRechargeDuration());
        machineRecharge.setRechargeWater(rentTypeInfo.getTypeWaterNum());         // 充值水量
        machineRecharge.setRechargeAmount(rentTypeInfo.getTypeServiceMoney() - discount);   // 充值金额，单位为分
        machineRecharge.setRechargeDuration(rentTypeInfo.getTypeDuration());        // 充值时长
        machineRecharge.setRechargeMessageState(0);
        machineRecharge.setRechargeState(0);
        machineRecharge.setRechargeEndTime(DateTimeUtil.addMonth(info.getMachineStopDate(), machineRecharge.getRechargeDuration()));
        Integer res = machineMapper.addRecharge(machineRecharge);
        if (res == null || res <= 0) {
            return new ResponseJson(200, "SERVER_ERROR", 500);
        }

        // 请求预支付id
        PayResult payResult = payService.requestPay(machineRecharge.getRechargeOpenId(),
                orderId,
                rentTypeInfo.getTypeServiceMoney() - discount,
                "【租赁】美国watero净饮水一体机!", NameUtils.getConfig("WECHAT_RENT_RECHARGE_BACK"));
        if (payResult.isPaySuccess()) {
            // 修改抵扣券为已使用
            return new ResponseJson(200, "SUCCESS", 200).addResponseKeyValue(orderId)
                    .addResponseKeyValue("wechat_pay_id", payResult.getPayData());
        } else {
            return new ResponseJson(200, "REQUEST_PAY_ERROR", 501);
        }
    }

    /**
     * 根据年限查看对应的充值信息
     * 2017年3月28日
     * @author muzx
     * @param years 充值年数
     * @return
     */
    private RentTypeInfo getRentType(int years){
        RentTypeInfo rentType = new RentTypeInfo();
        rentType.setTypeId(years);
        rentType = orderRebateMapper.getRebateType(rentType);
        return rentType;
    }
    @Override
    public ResponseJson rechargeOrderIdPay(String orderId) {
        // TODO Auto-generated method stub
        MachineRecharge machineRecharge = new MachineRecharge();
        machineRecharge.setRechargeOrderId(orderId);
        machineRecharge.setRechargeState(0);
        List<MachineRecharge> listRecharge = machineMapper.listRecharge(machineRecharge);
        if (listRecharge == null || listRecharge.isEmpty() || listRecharge.size() != 1) {
            return new ResponseJson(200, "NOT_FOUND", 404);
        }
        // 请求预支付id
        PayResult payResult = payService.requestPay(listRecharge.get(0).getRechargeOpenId(), orderId,
                listRecharge.get(0).getRechargeAmount(),
                "【租赁】美国watero净饮水一体机!", NameUtils.getConfig("WECHAT_RENT_RECHARGE_BACK"));
        if (payResult.isPaySuccess()) {
            return new ResponseJson(200, "SUCCESS", 200).addResponseKeyValue(orderId)
                    .addResponseKeyValue("wechat_pay_id", payResult.getPayData());
        } else {
            return new ResponseJson(200, "REQUEST_PAY_ERROR", 501).addResponseKeyValue(payResult.getPayData());
        }
    }

    @Override
    public Integer rechargeOrderPayCallback(String orderId, String transactionId) {
        // TODO Auto-generated method stub
        // 校验续费记录是否存在
        MachineRecharge machineRecharge = new MachineRecharge();
        machineRecharge.setRechargeOrderId(orderId);
        machineRecharge.setRechargeState(0);
        List<MachineRecharge> listRecharge = machineMapper.listRecharge(machineRecharge);
        if (listRecharge == null || listRecharge.isEmpty() || listRecharge.size() != 1) {
            return 3;
        }
        machineRecharge.setRechargeId(listRecharge.get(0).getRechargeId());
        // 修改服务券状态
        Integer couponId = listRecharge.get(0).getRechargeCouponId();
        if (couponId != 0) {
            ServiceCouponInfo info = new ServiceCouponInfo();
            info.setServiceId(couponId);
            info.setServiceStatus(3);
            couponMapper.update(info);
        }

        // 查询机器信息
        MachineInfo info = new MachineInfo();
        info.setMachineId(listRecharge.get(0).getRechargeMachineId());
        List<MachineInfo> list = machineMapper.list(info);
        if (list == null || list.size() != 1) {
            return 2;
        }

        // 计算下发的小时数:结束时间 - 当前时间 / 1000 = x 秒  / 60 = y 分 / 60 = z 小时z
        long hour = (DateTimeUtil.addMonth(listRecharge.get(0).getRechargeDuration()).getTime() - new Date().getTime()) / 1000 / 60 / 60;

        // 发送续费消息 : 注意，此处存在待优化的逻辑，在事务中使用HTTP，导致行锁长时间的被当前事务持有，其他事务必须等待
        // 补0
        info = list.get(0);
        String hourStr = WechatIotUtils.align(Long.toString(hour));
        String waterNum = WechatIotUtils.align(String.valueOf(info.getMachineSurplusWater() + listRecharge.get(0).getRechargeWater()));

        String message = String.format(WechatIotUtils.INIT_MACHINE_COMMAND, hourStr, waterNum);
       /* JSONObject json = WechatIotUtils.send(configService.getAccessToken(), message,
                list.get(0).getMachineDeviceId(), list.get(0).getMachineOpenid(), "gh_2674097b2442");
        if (json == null || json.toString().indexOf("errcode") != -1) {
            LOGGER.error("{'method':{}, 'msg':{}}", "发送激活信息失败", json.toString());
            machineRecharge.setRechargeMessageState(2);
        } else {
            machineRecharge.setRechargeMessageState(1);
        }*/

        // 修改机器信息
        info.setMachineStopDate(listRecharge.get(0).getRechargeEndTime());
        info.setMachineSurplusWater(info.getMachineSurplusWater() + listRecharge.get(0).getRechargeWater());
        info.setMachineTotalWater(listRecharge.get(0).getRechargeWater() + info.getMachineSurplusWater());
        info.setMachineState(1);
        info.setMachineNextCommand(message);                            // 保存指令
        Integer res = machineMapper.update(info);
        if (res == null || res <= 0) {
            throw new IllegalArgumentException();
        }

        // 修改续费订单的状态：待确认下发命令 & 支付成功
        machineRecharge.setRechargeMessageState(2);
        machineRecharge.setRechargeState(1);
        machineRecharge.setRechargePayTime(new Date());
        machineRecharge.setRechargeWxOrderId(transactionId);
        res = machineMapper.updateRecharge(machineRecharge);
        return res;
    }

    /**
     * 续费以后 - 接受到续费成功命令后修改
     * @param openid
     * @throws ServiceException
     * @author 献
     * @Time   2017年4月5日
     */
    public int rechargeAfter(String openid, String deviceId) throws ServiceException {
        // 查询机器信息
        MachineInfo info = new MachineInfo();
        info.setMachineDeviceId(deviceId);
        // info = machineMapper.list(info).get(0);
        if (machineMapper.list(info) == null) {
            return 0;
        }

    	// 查询续费记录 : 查询所有支付成功，并且消息下发失败的
    	MachineRecharge machineRecharge = new MachineRecharge();
        machineRecharge.setRechargeOpenId(openid);
        machineRecharge.setRechargeState(1);
        machineRecharge.setRechargeMessageState(2);
        machineRecharge.setRechargeMachineId(info.getMachineId());
        List<MachineRecharge> listRecharge = machineMapper.listRecharge(machineRecharge);
        if (listRecharge == null || listRecharge.isEmpty()) {
            return 0;
        }

        // 修改续费订单的状态
        for (MachineRecharge machineRecharge2 : listRecharge) {
        	machineRecharge = new MachineRecharge();
        	machineRecharge.setRechargeId(machineRecharge2.getRechargeId());
        	machineRecharge.setRechargeMessageState(1);
            machineRecharge.setRechargePayTime(new Date());
            machineRecharge.setRechargeWxOrderId(machineRecharge2.getRechargeWxOrderId());
            machineRecharge.setRechargeState(1);
            machineMapper.updateRecharge(machineRecharge);
		}

		// 修改机器中的 下一条指令
        info.setMachineNextCommand("");
        machineMapper.update(info);
        
        return 1;
    }

    @Override
    public List<MachineRecharge> listRecharge(Integer machineId) {
        // TODO Auto-generated method stub
        MachineRecharge machineRecharge = new MachineRecharge();
        machineRecharge.setRechargeMachineId(machineId);
        machineRecharge.setRechargeState(1);
        return machineMapper.listRecharge(machineRecharge);
    }

    @Override
    public List<MachineInfo> selectEquipmentList(MachineInfo machineInfo) {
        // TODO Auto-generated method stub
        return machineMapper.selectEquipmentList(machineInfo);
    }

    @Override
    public Integer selectEquipmentCount(MachineInfo machineInfo) {
        // TODO Auto-generated method stub
        return machineMapper.selectEquipmentCount(machineInfo);
    }

    @Override
    public Integer add(MachineInfo info) {
        // TODO Auto-generated method stub
        return machineMapper.add(info);
    }

    @Override
    public MachineRecharge getRechargeByIdOrOrderId(MachineRecharge recharge) {
        // TODO Auto-generated method stub
        return machineMapper.getRechargeByIdOrOrderId(recharge);
    }

    @Override
    public ResultMsg presentMachine(String orderItemId, String openId) {
        ResultMsg rm = new ResultMsg();
        rm.setMessage(ResultInfo.ERRORCODE);
        rm.setStatus(false);
        if(StringUtils.isEmpty(orderItemId)){
            rm.setMessage("请选择正确的机器!");
            return rm;
        }
        RentOrderItem item = new RentOrderItem();
        item.setItemId(Integer.parseInt(orderItemId));
        item = rentOrderMapper.getOrderItemByInitCode(item);
        if(item == null || item.getItemProductType() != 1){
            rm.setMessage("该机器不可以送人!");
            return rm;
        }
        if(StringUtils.isEmpty(item.getItemInitCode()) || item.getItemCodeState() != 1){
            rm.setMessage("该激活码已经被激活,不可以送人!");
            return rm;
        }
        MachineShare machineShare = new MachineShare();
        machineShare.setShareOpenId(openId);
        machineShare.setShareTime(new Date());
        machineShare.setShareCode(item.getItemInitCode());
        if(machineMapper.insertMachineShare(machineShare) != null){
            rm.setStatus(true);
            rm.setResultCode(ResultInfo.SUCCESSCODE);
            rm.setMessage("");
            rm.setData(machineShare.getShareId());
        }else{
            rm.setMessage("赠送失败!请确认后重试!");
        }
        return rm;
    }

    @Override
    public ResultMsg receiveMachine(String shareId, String openId) {
        ResultMsg rm = new ResultMsg();
        rm.setMessage(ResultInfo.ERRORCODE);
        rm.setResultCode("500");
        rm.setStatus(false);

        if(StringUtils.isEmpty(shareId)){
            rm.setMessage("分享有误!请联系分享用户重新分享!");
            return rm;
        }
        MachineShare machineShare = machineMapper.getMachineShareById(shareId);
        if(machineShare == null){
            rm.setMessage("分享有误!请联系分享您的用户重新分享!");
            return rm;
        }

        Member member = memberService.getMemberByUserOpenId(machineShare.getShareOpenId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userName", member.getUserNickname());
        map.put("userHead", member.getUserHead());
        map.put("userDate", DateTimeUtil.format(machineShare.getShareTime()));
        map.put("isUsed", "0");
        rm.setData(map);
        rm.setResultCode("200");
        if(StringUtils.isNotEmpty(machineShare.getShareReOpenid())){
            rm.setMessage("这台净水机已经被人领取。");
            if(ObjectUtils.equals(machineShare.getShareReOpenid(), openId)){
            	map.put("isUsed", "1");
            }else{
            	map.put("isUsed", "2");
            }
        }
        if(ObjectUtils.equals(machineShare.getShareOpenId(), openId)){
        	rm.setResultCode("201");
        }else{
        	if(StringUtils.isEmpty(machineShare.getShareReOpenid())){
        		machineShare.setShareReOpenid(openId);
        		machineShare.setShareBindTime(new Date());
        		if(machineMapper.updateMachineShare(machineShare) > 0){
        			rm.setStatus(true);
        			rm.setMessage("");
        		}else{
        			rm.setMessage("领取机器失败,请联系分享您的用户重新分享!");
        		}
        	}
        }
        return rm;
    }

	@Override
	public int bindMachineToOpenId(String device_id, String openId) {
		// TODO Auto-generated method stub
		MachineInfo info = new MachineInfo();
		info.setMachineDeviceId(device_id);
		info.setMachineOpenid(openId);
		Integer res = machineMapper.update(info);
		return res == null ? 0 : res;
	}

	@Override
	public MachineInfo selectMachineById(MachineInfo machineInfo) {
		// TODO Auto-generated method stub
		return machineMapper.selectMachineById(machineInfo);
	}

    @Override
    public List<MachineShare> listMachineShareAdmin(MachineShare machineShare) {
        // TODO Auto-generated method stub
        machineShare.getPage().initRecordBegin();
        return machineMapper.listMachineShareAdmin(machineShare);
    }

    @Override
    public int countMachineShare(MachineShare machineShare) {
        // TODO Auto-generated method stub
        return machineMapper.countMachineShare(machineShare);
    }

	/*@Override
	@Scheduled(cron = "0/10 * * * * ?")//每10秒执行一次*/
	public synchronized void handlerNextCommand() {
		// TODO Auto-generated method stub
        List<MachineInfo> listNextCommandMachine = machineMapper.listNextCommandMachine();
		for (MachineInfo machineInfo : listNextCommandMachine) {
            // 第一条消息总是改变数据方向：Server
            String accessToken = configService.getAccessToken();
            WechatIotUtils.send(accessToken, "*setDir0#", machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), "gh_2674097b2442");
			// 接着发送正式的命令
            JSONObject json = WechatIotUtils.send(accessToken, machineInfo.getMachineNextCommand(),
					machineInfo.getMachineDeviceId(), machineInfo.getMachineOpenid(), "gh_2674097b2442");
	        if (json == null || json.toString().contains("errcode")) {
                LOGGER.error("{'method':'{}', 'msg':'{}'}", "发送激活信息失败", json.toString());
	        } else {
                LOGGER.info("{'device_id':'{}', 'msg':'{}'}", machineInfo.getMachineDeviceId(), "发送激活信息成功");
            }
		}
	}

	@Override
	public Integer update(MachineInfo info) {
		// TODO Auto-generated method stub
		return machineMapper.update(info);
	}

	@Override
	public List<RentChangeLogs> listSelectChangeLogs(
			RentChangeLogs rentChangeLogs) {
		// TODO Auto-generated method stub
		return machineMapper.listSelectChangeLogs(rentChangeLogs);
	}

	@Override
	public Integer saveChangeLogs(List<RentChangeLogs> list, RentOrder rentOrder) throws Exception {
		// TODO Auto-generated method stub
        int id = 0;
        if (list != null && list.size() > 0) {
            //循环插入更换滤芯表中，返回id并推送到百胜系统
            for (RentChangeLogs rentChangeLogs : list) {
                int colorId = 0;
                switch (rentChangeLogs.getLogsFilterType().intValue()) {
                    case 1:colorId = 7;break;
                    case 2:colorId = 8;break;
                    case 3:colorId = 8;break;
                    case 4:colorId = 8;break;
                    default:colorId = 7;break;
                }
                id = machineMapper.insertFilterLogs(rentChangeLogs);
                if (id > 0) {
                    efastRentService.sendRentFilter(rentChangeLogs.getLogsAddressInfo(),"RF00000000"+id,colorId,
                            rentChangeLogs.getLogsAddressName(),rentChangeLogs.getLogsAddressTel(),rentOrder.getRentOpenid());
                }
            }
        }
		return id;
	}

	@Override
	public List<RentChangeLogs> listChangeFilterLogs(
			RentChangeLogs rentChangeLogs) {
		// TODO Auto-generated method stub
		return machineMapper.listChangeFilterLogs(rentChangeLogs);
	}

	@Override
	public Integer getChangeFilterCount(RentChangeLogs rentChangeLogs) {
		// TODO Auto-generated method stub
		int count = machineMapper.getChangeFilterCount(rentChangeLogs);
		int pageCount =  count % rentChangeLogs.getPage().getPageSize() == 0 ? count/rentChangeLogs.getPage().getPageSize():(count/rentChangeLogs.getPage().getPageSize()) + 1;
		return pageCount;
	}

    @Override
    public Integer addCompeteWater(CompeteWaterInfo competeWaterInfo) {
        return machineMapper.addCompeteWater(competeWaterInfo);
    }

    @Override
    public CompeteWaterInfo selectCompeteWater(String shareId) {
        return machineMapper.selectCompeteWater(shareId);
    }

    @Override
    public boolean updateChangeLogsById(RentChangeLogs rentChangeLogs) {
        int num = machineMapper.updateChangeLogsById(rentChangeLogs);
        if (num > 0) {
            return true;
        } else {
            return false;
        }
    }
}
