package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.CustomerMapper;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("protectionPeriod")
public class IMProtectionImpl implements IMProtection {

    private static final Logger LOGGER = LoggerFactory.getLogger(IMProtectionImpl.class);

    @Autowired
    private CustomerMapper customermapper;
    @Autowired
    private CustomerMergeMapper customermergemapper;
    @Autowired
    private IUserService<UserEntity> userService;


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

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.AddCustomerParams4Protection);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doBusiness(map);
            response.setData(data);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

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

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

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

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private static String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    public static int differentDaysByDate(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;

    }


    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String cityCode = getMapValueByKey(Constant.CITY_CODE, map, "");
        Integer period = customermergemapper.getCityPeriod(cityCode);
        CustomerEntity ce = new CustomerEntity();
        ce.setPhone(phone);
        ce.setCityCode(cityCode);
        Date nowDate = new Date();
        List<CustomerEntity> list = customermapper.queryCustomerPeriod(ce);
        boolean protectPeriod = false;
        if (list != null && list.size() > 0) {
            for (CustomerEntity entity : list) {
                Date createTime = entity.getCreateTime();
                int days = differentDaysByDate(createTime, nowDate);
                if (days < period) {//仍在保护期内
                    protectPeriod = true;
                    ce.setProtectPeriod(protectPeriod);
                    UserEntity user = userService.getById(entity.getManagerId());
                    ce.setProtectMsg("咨询跟进保护中,跟进人:" + user.getDeptName() + "-" + entity.getManagerName());
                    ce.setManagerName(entity.getManagerName());
                    break;
                }
            }
        } else {
            ce.setProtectPeriod(protectPeriod);
        }
        restObject.setEntity(ce);
        return restObject;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(Map<String, Object> map, String[] checkParams) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

}
