/**
 * Description: CmSmsCodeWS接口
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-07-06 下午 14:00:59
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-07-06   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.CmSmsCodeEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.SmsUtils;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.CmSmsCodeListRequest;
import com.house365.ws.beans.request.CmSmsCodeRequest;
import com.house365.ws.beans.response.CmSmsCodeListResponse;
import com.house365.ws.beans.response.CmSmsCodeResponse;
import com.house365.ws.interfaces.server.ICmSmsCode;
import com.house365.ws.service.interfaces.ICmSmsCodeService;
import com.house365.ws.system.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * CmSmsCodeWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-07-06
 * @see
 * @since 1.0
 */
@Service("cmSmsCode")
public class CmSmsCodeImpl implements ICmSmsCode {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CmSmsCodeImpl.class);

    /**
     * 验证码有效时间（分钟）
     */
    private static final int AUTH_CODE_TIME = 60;
    private static final int ONE_MINUTES = 1;
    private static final int FIVE_MINUTES = 5;
    private static final int SIX_MINUTES = 6;

    /**
     * 接口参数手机号码
     */
    private static final String PHONE = "phone";

    /**
     * 接口参数城市
     */
    private static final String CITY = "city";

    /**
     * 参数列表
     */
    private static final String[] PARAMS = {PHONE, CITY};

    /**
     * CmSmsCode服务对象
     */
    @Autowired
    private ICmSmsCodeService<CmSmsCodeEntity> cmSmsCodeService;

    /**
     * 当前时间距离验证码发送时间，是否在有效时间以内。
     *
     * @param sendTime 例：2015-07-14 16:17:33
     *                 minute 分钟数  例：60 即一小时
     * @return 如果在有效时间内，返回true；否则返回false。
     */
    public static boolean exitInMinuteTime(Date sendTime, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sendTime);
        calendar.add(Calendar.MINUTE, minute);

        if (Calendar.getInstance().after(calendar)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * CmSmsCode列表查询
     *
     * @param request CmSmsCode列表查询请求
     * @return CmSmsCode列表查询响应
     */
    @Override
    public CmSmsCodeListResponse getCmSmsCodeList(CmSmsCodeListRequest request) {
        CmSmsCodeListResponse response = new CmSmsCodeListResponse();
        try {
            QueryParams<CmSmsCodeEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            List<CmSmsCodeEntity> list = cmSmsCodeService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存CmSmsCode
     *
     * @param request CmSmsCode请求
     * @return 保存CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse addCmSmsCode(CmSmsCodeRequest request) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        try {
            CmSmsCodeEntity entity = request.getEntity();
            cmSmsCodeService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除CmSmsCode通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse deleteCmSmsCodeById(Integer id) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        try {
            cmSmsCodeService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改CmSmsCode
     *
     * @param request 修改CmSmsCode请求
     * @return 修改CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse updateCmSmsCode(CmSmsCodeRequest request) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        try {
            cmSmsCodeService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取CmSmsCode
     *
     * @param id 唯一标识
     * @return 通过ID获取CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse getCmSmsCodeById(Integer id) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        try {
            CmSmsCodeEntity entity = cmSmsCodeService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 发送短信
     *
     * @param req 请求
     * @return CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse sendSms(CmSmsCodeRequest req) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        CmSmsCodeEntity entity = req.getEntity();
        try {
            // 发送短信城市通道
            String city = entity.getCity();
            // 发送手机号
            String phone = entity.getPhone();
            // 校验当日手机号码发送验证码次数
            validTodaySmsTimes(phone);
            // 生成六位短信验证码
            String authCode = getSmsCode(phone, city);
            // 根据短信模板生成的短信内容
            String smsInfo = getSmsTemplet(authCode);

            // 取得短信接口URL
            String smsUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.default.smsUrl");

            // 发送短信操作
            SmsUtils.sendSms(smsUrl, city, phone, smsInfo, authCode);

            // 封装返回对象
            CmSmsCodeEntity smsCodeEntity = new CmSmsCodeEntity();
            smsCodeEntity.setAuthCode(authCode);
            response.setEntity(smsCodeEntity);

            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("汇客宝365后台，获取验证码接口系统异常！");
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 提交验证
     *
     * @param req 请求
     * @return CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse getByPhone(CmSmsCodeRequest req) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        CmSmsCodeEntity entity = req.getEntity();
        try {
            // 发送手机号
            String phone = entity.getPhone();
            CmSmsCodeEntity cmSmsCodeEntity = cmSmsCodeService.getByPhone(phone);
            response.setEntity(cmSmsCodeEntity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("汇客宝365后台，获取验证码接口系统异常！");
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

    /**
     * 修改密码成功后，手机验证码失效
     *
     * @param phone 请求
     * @return CmSmsCode响应
     */
    @Override
    public CmSmsCodeResponse modifyComplete(String phone) {
        CmSmsCodeResponse response = new CmSmsCodeResponse();
        try {
            CmSmsCodeEntity entity = cmSmsCodeService.getByPhone(phone);
            // 生成六位随机验证码
            String authCode = (Math.random() * 900000 + 100000 + "").substring(0, 6);
            // 修改密码成功后，修改手机验证码使手机验证码失效
            entity.setAuthCode(authCode);
            entity.setSendTime(new Date());
            cmSmsCodeService.update(entity);
            CmSmsCodeEntity entity1 = cmSmsCodeService.getByPhone(phone);
            response.setEntity(entity1);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("汇客宝365后台，获取验证码接口系统异常！");
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

    /**
     * 校验当日短信发送次数
     *
     * @return true or false
     * @throws ServiceRunException
     * @author jiangzhou
     */
    private void validTodaySmsTimes(String phone) throws ServiceRunException {
        Map<String, Object> allRecord = cmSmsCodeService.findAllSmsRecord(phone);
        Integer smsRecordCount = allRecord == null ? 0 : Integer.parseInt(allRecord.get("smscount").toString());
        // 短信发送时间
        String sendTime = allRecord == null ? "" : allRecord.get("sendTime").toString();
        // 当前系统时间
        String curServerTime = DateTimeUtils.getCurrentDateString();
        // 短信次数配置
        Integer curCount = Integer.parseInt(MemoryPropertyPlaceholderConfigurer.getContextProperty("sms.count"));
        // 比较时间和短信发送次数 如满足规则则提示
        if (smsRecordCount >= curCount && curServerTime.equals(sendTime)) {
            throw new ServiceRunException("短信验证码今日已超出限制");
        }
        if ((smsRecordCount >= curCount || smsRecordCount < curCount) && !curServerTime.equals(sendTime)) {
            // 重置次数
            Map<String, Object> param = new HashMap<>(10);
            param.put("resetCount", "0");
            param.put("phone", phone);
            cmSmsCodeService.recordSmsTimes(param);
        }
    }

    /**
     * 取得验证码，并进行数据相关操作。 1、如果该手机号存在，则判定时间。 一小时内取值直接返回，超过一小时则重新生成验证码，并更新数据库记录。 2、如果不存在，则插入相应记录
     *
     * @return 验证码短信内容
     */
    private String getSmsCode(String phone, String city) {
        CmSmsCodeEntity cmSmsCodeEntity = cmSmsCodeService.getByPhone(phone);
        Map<String, Object> param = new HashMap<>(5);
        param.put("phone", phone);
        // 生成六位随机验证码
        String authCode = (Math.random() * 900000 + 100000 + "").substring(0, 6);
        // 如果不存在，插入相应记录，返回验证码。
        if (null == cmSmsCodeEntity) {
            cmSmsCodeEntity = new CmSmsCodeEntity();
            cmSmsCodeEntity.setPhone(phone);
            cmSmsCodeEntity.setAuthCode(authCode);
            cmSmsCodeEntity.setSmsCount(0);
            cmSmsCodeEntity.setSendTime(new Date());
            cmSmsCodeEntity.setTodayDate(new Date());
            cmSmsCodeEntity.setCreateTime(new Date());
            cmSmsCodeEntity.setCity(city);
            cmSmsCodeService.save(cmSmsCodeEntity);
            cmSmsCodeService.recordSmsTimes(param);
            // 返回验证码
            return authCode;
        } else {
            // 如果该手机号存在，则判定时间。(超过一小时则重新生成验证码，并更新数据库记录。)
            cmSmsCodeEntity.setAuthCode(authCode);
            cmSmsCodeEntity.setSendTime(new Date());
            cmSmsCodeService.update(cmSmsCodeEntity);
            cmSmsCodeService.recordSmsTimes(param);
            return authCode;

        }
    }

    //校验手机验证码是否过期（n分钟内有效）
    public String validOverdue(String phone) {
        CmSmsCodeEntity cmSmsCodeEntity = cmSmsCodeService.getByPhone(phone);
        // 如果不存在，插入相应记录，返回验证码。
        if (null != cmSmsCodeEntity) {
            // 判定时间。(n分钟内有效)，超过n分钟的情况
            if (!exitInMinuteTime(cmSmsCodeEntity.getSendTime(), ONE_MINUTES)) {
                // 生成六位随机验证码
                String authCode = (Math.random() * 900000 + 100000 + "").substring(0, 6);
                // 如果该手机号存在，则判定时间。(超过n分种则重新生成验证码，并更新数据库记录。)
                cmSmsCodeEntity.setAuthCode(authCode);
                cmSmsCodeService.update(cmSmsCodeEntity);
                return authCode;
            }

        }
        return null;
    }

    /**
     * 短信内容模板
     *
     * @return 验证码短信内容
     */
    private String getSmsTemplet(String smsCode) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("【三六五网】尊敬的网友，您正在进行修改密码操作，验证码为");
        stringBuffer.append(smsCode);
        stringBuffer.append("，请于5分钟内在页面输入，工作人员不会向您索取，请勿泄露。");
        return stringBuffer.toString();
    }


    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }

}
