package io.renren.service.impl;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.renren.common.constant.Constant;
import io.renren.common.entity.RdSmsTestEntity;
import io.renren.common.exception.ErrorCode;
import io.renren.common.redis.RedisKeys;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.Result;
import io.renren.common.utils.security.SM4Utils;
import io.renren.dao.CompaniesDao;
import io.renren.dao.CustomersDao;
import io.renren.dao.LandingPagesDao;
import io.renren.dao.RdSmsTestDao;
import io.renren.dto.CustomersDTO;
import io.renren.entity.CompaniesEntity;
import io.renren.entity.CustomersEntity;
import io.renren.entity.LandingPagesEntity;
import io.renren.service.CustomersService;
import io.renren.util.CacheUtils;
import lombok.extern.log4j.Log4j2;

/**
 * 客户表
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-29
 */
@Log4j2
@Service
public class CustomersServiceImpl extends CrudServiceImpl<CustomersDao, CustomersEntity, CustomersDTO> implements CustomersService {
	
	/**
	 * 加解密秘钥
	 */
	@Value("${encrypt.token}")
	private String TRANSMIT_KEY;
	
	@Autowired
	private CacheUtils cacheUtils;

	@Autowired
	private RdSmsTestDao rdSmsTestDao;

	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private LandingPagesDao landingPagesDao;
	@Autowired
	private CompaniesDao companiesDao;
	

	@Override
	public QueryWrapper<CustomersEntity> getWrapper(Map<String, Object> params) {
		return null;
	}
	
	@Override
	public Result<String> inserCustomer(CustomersDTO dto) throws Exception{
		log.info("新增客户表请求参数"+JSONObject.toJSONString(dto));
		//1、验证码验证

		if (StringUtils.isEmpty(dto.getVerifyCode())) {
			return new Result<String>().error(ErrorCode.VERIFICATION_CODE_ERROR,"验证码不正确");
		}
		String code = cacheUtils.get(RedisKeys.getVerificationCodeKey(dto.getMobile()))!=null?cacheUtils.get(RedisKeys.getVerificationCodeKey(dto.getMobile())).toString():null;

		if (StringUtils.isNotEmpty(code)){
			if( ! dto.getVerifyCode().equals(code)){
				RdSmsTestEntity rdSmsTestEntity = rdSmsTestDao.selectOne(new QueryWrapper<RdSmsTestEntity>()
						.eq("mobile", dto.getMobile()).eq("status", Constant.Status.ENABLE.getValue()).last("limit 1"));
				if(null == rdSmsTestEntity || ! rdSmsTestEntity.getCode().equalsIgnoreCase(code)) {
					return new Result<String>().error(ErrorCode.VERIFICATION_CODE_ERROR,"验证码不正确");
				}
				//return new Result<String>().error(ErrorCode.VERIFICATION_CODE_ERROR,"验证码不正确");
			}else {
				cacheUtils.remove(RedisKeys.getVerificationCodeKey(dto.getMobile()));
			}
		}else{
			RdSmsTestEntity rdSmsTestEntity = rdSmsTestDao.selectOne(new QueryWrapper<RdSmsTestEntity>()
					.eq("mobile", dto.getMobile()).eq("status", Constant.Status.ENABLE.getValue()).last("limit 1"));
			if(null == rdSmsTestEntity || ! rdSmsTestEntity.getCode().equalsIgnoreCase(dto.getVerifyCode())) {
				return new Result<String>().error(ErrorCode.VERIFICATION_CODE_ERROR,"验证码不正确");
			}
		}

		//2验证page_id
		if (dto.getPageId()==0l) {
			return new Result<String>().error(ErrorCode.NOT_FOUND_PAGE,"页面不存在");
		}

		 QueryWrapper<LandingPagesEntity> pageWrapper = new QueryWrapper<>();
		 pageWrapper.eq(StringUtils.isNotBlank(dto.getPageId().toString()), "id", dto.getPageId())
        		.eq("status",Constant.Status.ENABLE.getValue());
        LandingPagesEntity landingPage= landingPagesDao.selectOne(pageWrapper);
        
        if (landingPage==null) {
			return new Result<String>().error(ErrorCode.NOT_FOUND_PAGE,"页面不存在");
		}else {
			dto.setChannelId(landingPage.getChannelId());
        	dto.setOperationId(landingPage.getOperationId());
		}
        
        if (true) {  //直投
        	QueryWrapper<CompaniesEntity> companyWrapper = new QueryWrapper<>();
            companyWrapper.eq(StringUtils.isNotBlank(landingPage.getCompanyIds()), "id", landingPage.getCompanyIds())
            		.eq("status",Constant.Status.ENABLE.getValue());
            CompaniesEntity company= companiesDao.selectOne(companyWrapper);
           
            if(company==null) {
            	//todo 去重处理
            	return new Result<String>().error(ErrorCode.NOT_FOUND_COMPANY,"公司不存在");
            }
            
            if (mobileIsExsit(dto,company)) {
            	return new Result<String>().error(ErrorCode.DUPLICATION_CODE_ERROR,"请勿重复提交！");
            }
    	        
            dto.setCompanyId(company.getId());
        }else {
        	//3验证城市
    		if (StringUtils.isEmpty(dto.getCity())) {
    			return new Result<String>().error(ErrorCode.NOT_FOUND_CITY,"城市不存在");
    		}
        }
        
        
      //TODO  page_id + city 是否有未配置

		CustomersEntity customers = new CustomersEntity();
		BeanUtils.copyProperties(dto, customers);

		if (StringUtils.isNotEmpty(dto.getTransId())) {
			customers.setStatus(Constant.Status.DISABLE.getValue());
		}else{
			customers.setStatus(Constant.Status.ENABLE.getValue());
		}


		customers.setMobile(SM4Utils.encryptData_ECB(customers.getMobile(), TRANSMIT_KEY));//手机号加密
		customers.setCompanyId(0L);
		customers.setCreateDate(new Date());

		customers.setIsPush(Constant.PushStatus.UN_PUSH.getValue());
		baseDao.insert(customers);

		return new Result<String>().pageOk(ErrorCode.SUCCESS_CODE,"提交成功");

	}

	@Override
	public Result<String> updateCustomer(CustomersDTO dto) throws Exception {
		log.info("更新客户表请求参数" + JSONObject.toJSONString(dto));
		//baseDao.selectOne()
		CustomersEntity customers = customersDao.selectOne(new QueryWrapper<CustomersEntity>()
				.eq("trans_id", dto.getTransId())
				.eq("mobile", SM4Utils.encryptData_ECB(dto.getMobile(), TRANSMIT_KEY))
				.eq("status", Constant.Status.DISABLE.getValue()).last("limit 1"));
		if(null == customers) {
			log.error("交易ID {}不存在或已停用",dto.getTransId());
			return new Result<String>().error(ErrorCode.NOT_FOUND_RECORD,"交易ID不存在或已停用");
		}
		BeanUtils.copyProperties(dto, customers);
		if(StringUtils.isEmpty(dto.getFlag())){
			customers.setStatus(Constant.Status.DISABLE.getValue());
		}else{
			customers.setStatus(Constant.Status.ENABLE.getValue());
		}
		customers.setMobile(SM4Utils.encryptData_ECB(dto.getMobile(), TRANSMIT_KEY));
		customers.setUpdateTime(new Date());
		customers.setIsPush(Constant.PushStatus.UN_PUSH.getValue());
		customersDao.updateById(customers);
		return new Result<String>().pageOk(ErrorCode.SUCCESS_CODE,"提交成功");
	}
	
	public boolean mobileIsExsit(CustomersDTO dto,CompaniesEntity company) throws Exception {
		boolean isExsit = false;
		   QueryWrapper<CustomersEntity> customerWrapper = new QueryWrapper<>();
		   customerWrapper.eq("mobile", dto.getMobile())
		   				.eq("companyId", company.getId())
	        		.eq("status",Constant.Status.ENABLE.getValue());
		   CustomersEntity customer= customersDao.selectOne(customerWrapper);
		   if (customer!=null) {
			   return true;
		   }
		
		return isExsit;
	}
}