package com.duiba.tuia.youtui.web.biz.land;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.duiba.tuia.youtui.web.biz.land.param.LandExtendParam;
import com.duiba.tuia.youtui.web.biz.land.param.RequestParamFactory;
import com.duiba.tuia.youtui.web.model.req.LandUserInfo;

import cn.com.duiba.intersection.serivce.api.remoteservice.RemotePhoneService;
import cn.com.duiba.intersection.serivce.api.remoteservice.dto.PhoneAttributionDto;
import cn.com.duiba.tuia.activity.center.api.dto.LandUserInfoDto;
import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteLandService;
import cn.com.duiba.wolf.dubbo.DubboResult;
import cn.com.duiba.wolf.utils.BeanUtils;

@Component
public class LandInfoOpt {

	@Autowired
	private RemoteLandService remoteLandService;
	
	@Autowired
    private RemotePhoneService remotePhoneService;

	/**
	 * 保存用户信息
	 * @param info
	 * @param extendParam
	 */
	public void save(LandUserInfo info, LandExtendParam extendParam){
		LandUserInfoDto dto = BeanUtils.copy(info, LandUserInfoDto.class);
		dto.setAppId(extendParam.getAppId());
		dto.setConsumerId(extendParam.getConsumerId());
		if(info.getBirthday() != null){
			dto.setBirthday(new Date(info.getBirthday()));
		}
		if(isHandlePhone(info.getChannel())){
			PhoneAttributionDto ownership = getPhoneOwnership(info.getUserPhone());
			if(ownership != null){
				dto.setPhoneProvince(ownership.getProvince());
				dto.setPhoneCity(ownership.getCity());
			}
		}
		info.setUserId(remoteLandService.insertUserInfo(dto).getResult());
	}
	
	/**
	 * update:(更新用户信息). <br/>
	 * @param info
	 */
	public void update(LandUserInfo info) {
	    LandUserInfoDto dto = BeanUtils.copy(info, LandUserInfoDto.class);
	    dto.setId(info.getUserId());
        if(info.getBirthday() != null){
            dto.setBirthday(new Date(info.getBirthday()));
        }
        this.remoteLandService.updateUserInfo(dto);
	}
	
	public boolean isExist(Long landId, String phone){
		Boolean exist = remoteLandService.selectUserPhoneExist(phone, landId).getResult();
		return exist;
	}
	
	/**
     * 获取手机号归属
     * @param phone 手机号
     * @return
     */
    private PhoneAttributionDto getPhoneOwnership(String phone){
    	DubboResult<PhoneAttributionDto> ret = remotePhoneService.find(phone);
    	if(!ret.isSuccess() || ret.getResult() == null){
    		return null;
    	}
    	return ret.getResult();
    }
    
    private boolean isHandlePhone(String channel){
    	if(RequestParamFactory.SJD_CHANNEL.equals(channel)){
    		return true;
    	}
    	return false;
    }
}
