package cn.com.countrygarden.bi.main.service.mediaResource.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageRowBounds;

import cn.com.countrygarden.bi.main.constant.mediaResource.MediaResourceConstant;
import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.dao.mediaResource.BasicInfoMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.CustomerMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.ScheduleBasicInfoMapper;
import cn.com.countrygarden.bi.main.dto.CustomerDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.mediaResource.Customer;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.mediaResource.BasicInfoService;
import cn.com.countrygarden.bi.main.service.mediaResource.CustomerService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.ExcelUtil;
import cn.com.countrygarden.bi.main.util.PageUtil;
import cn.com.countrygarden.bi.main.util.SnowflakeUtil;

@Service
@Transactional
public class CustomerServiceImpl extends AbstractService<Customer> implements CustomerService{

	@Autowired
	private CustomerMapper customerMapper;
	
	@Autowired
    private TbSysUserService tbSysUserService;
	
	@Autowired
	private AccessTokenService accessTokenService;
	
	@Autowired
	private ScheduleBasicInfoMapper scheduleBasicInfoMapper;
	
	
	@Autowired
	private BasicInfoMapper basicInfoMapper;
	
	@Autowired
	private BasicInfoService basicInfoService;
	

	@Override
	public PageData findCustomerByPage(String accesstoken,CustomerDto dto) {
		dto.setPageIndex(dto.getPageIndex()==null?1:dto.getPageIndex());
		dto.setPageSize(dto.getPageSize()==null?10:dto.getPageSize());
		int pageOffset = PageUtil.getPageOffset(dto.getPageIndex(),dto.getPageSize());
		dto.setPageOffset(pageOffset);
		
		TbSysUser user = basicInfoService.findErpUser(accesstoken);
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(), MediaResourceConstant.roleCode);
		if (count==0) {
			dto.setCreateBy(user.getUserCode());
		}

		List<Map<String, Object>> list = customerMapper.selectCustomer(dto);
		long total = customerMapper.selectCustomerCount(dto);
		PageRowBounds pageRowBounds = new PageRowBounds(dto.getPageIndex(), dto.getPageSize());
	    pageRowBounds.setTotal(total);
	    pageRowBounds.setCount(true);
        PageData pageData = new PageData(list, pageRowBounds);
        return pageData;
	}

	@Override
	public Result saveOne(Result rt,String accessToken,CustomerDto dto) {
		
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		
		String customerId = dto.getCustomerId();
		customerId = StringUtils.isNotBlank(customerId)?"0".equals(customerId)?null:customerId:null;
		/*String customerName = dto.getCustomerName();
		int verify = customerMapper.verifyCustomerName(customerName,customerId);
		if (verify!=0) {
			return rt.setResultCode(ResultCode.INTERNAL_SERVER_ERROR).setResultMsg("客户名称已存在");
		}*/
		
		Customer po = new Customer();
		po.setContactName(dto.getContactName());
		po.setContactPhone(dto.getContactPhone());
		po.setCustomerName(dto.getCustomerName());
		po.setCustomerType(Integer.parseInt(dto.getCustomerType()));
		po.setCustomerIndustry(Integer.parseInt(dto.getCustomerIndustry()));
		po.setRemark(dto.getRemark());
		
		if (StringUtils.isNotBlank(customerId)) {
			po.setCustomerId(Long.valueOf(customerId));
			Customer dbpo = customerMapper.selectByPrimaryKey(po.getCustomerId());
			if (!dbpo.getCreateBy().equals(user.getUserCode())) {
				return rt.setResultCode(ResultCode.INTERNAL_SERVER_ERROR).setResultMsg("客户信息只限创建者修改！");
			}
			po.setModBy(user.getUserCode());
			po.setModByName(user.getUserName());
			po.setModTime(new Date());
			return rt.setResultCode(ResultCode.OK).setResultMsg("OK").setData(customerMapper.updateOne(po));
		}
		
		String nextNo = getNextNo();
		po.setCustomerNo(nextNo);
		po.setCustomerId(SnowflakeUtil.INSTANCE.getId());
		po.setCreateBy(user.getUserCode());
		po.setCreateByName(user.getUserName());
		po.setCreateTime(new Date());
		return rt.setResultCode(ResultCode.OK).setResultMsg("OK").setData(customerMapper.insert(po));
	}

	@Override
	public Map<String,String> findOne(Customer po) {
		return customerMapper.findOne(po);
		
	}

	@Override
	public int del(CustomerDto dto) {
		String[] customerIds = dto.getCustomerIds();
		return customerMapper.dels((null==customerIds||0==customerIds.length)?null:customerIds);
	}

	@Override
	public Result exportIn(String accessToken,  Result rt, MultipartFile file) throws IOException {
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		List<ArrayList<String>> data = ExcelUtil.importData(file,0);
		String downloadTitle = "[客户名称, 客户类型, 行业类型, 联系人, 联系人电话, 备注]";
		String firstRow = data.get(0).toString();
		if (!downloadTitle.equals(firstRow)) {
			return rt.setResultCode(ResultCode.FAIL).setResultMsg("标题顺序错误，请下载模板文件或按照模板文件顺序。").setData(false);
		}
		data.remove(0);
		
		StringBuffer overAllStr = new StringBuffer();
		
		Map<Integer, String> errorMsgMap = new LinkedHashMap<>();
		
		List<Customer> successList = new ArrayList<>();
		String regex = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		
		Map<Integer, String> customerTypeMap = MediaResourceConstant.CUSTOMER_TYPE.DES;
		//MediaResourceConstant.INDUSTRY_TYPE.DES;
		Map<Integer, String> industryTypeMap = MediaResourceConstant.INDUSTRY_TYPE.DES;
		
		for (int i = 0; i < data.size(); i++) {
			ArrayList<String> rows = data.get(i);
			String customerName = rows.get(0);
			String customerType = rows.get(1);
			String industryType = rows.get(2);
			String contactName = rows.get(3);
			String contactPhone = rows.get(4);
			String remark = rows.get(5);
			
			boolean flag = false;
			overAllStr.append(StringUtils.isNotBlank(contactPhone)?"":"联系人电话为空，");
			if (StringUtils.isEmpty(overAllStr)) {
				int pLen = contactPhone.length();
				if (pLen<8 || pLen>12) {
					overAllStr.append("电话号码不正确，");
				}
				if (pLen==11) {
					flag = Pattern.matches(regex, contactPhone);
					if (!flag) {
						overAllStr.append("手机号码不正确，");
					}
				}
				if (!flag && StringUtils.isEmpty(overAllStr)) {
					regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
					flag = Pattern.matches(regex, contactPhone);
					if (!flag) {
						overAllStr.append("电话号码不正确，");
					}
				}
			}
			
			overAllStr.append(StringUtils.isNotBlank(customerName)?"":"客户名称为空，");
			overAllStr.append(StringUtils.isNotBlank(contactName)?"":"联系人名称为空，");
			overAllStr.append(StringUtils.isNotBlank(customerType)?customerTypeMap.containsValue(customerType)?"":"客户类型不存在，":"客户类型为空，");
			overAllStr.append(StringUtils.isNotBlank(industryType)?industryTypeMap.containsValue(industryType)?"":"行业类型不存在，":"行业类型为空，");
			
			
			if (StringUtils.isNotBlank(overAllStr)) {
				errorMsgMap.put(i+2, overAllStr.toString());
				overAllStr.setLength(0);
				continue;
			}
			
			Customer po = new Customer();
			po.setCustomerId(SnowflakeUtil.INSTANCE.getId());
			po.setCustomerName(customerName);
			po.setCustomerType(customerTypeMap.entrySet().stream().filter(t->t.getValue().equals(customerType)).findAny().get().getKey());
			po.setCustomerIndustry(industryTypeMap.entrySet().stream().filter(t->t.getValue().equals(industryType)).findAny().get().getKey());
			po.setContactName(contactName);
			po.setContactPhone(contactPhone);
			po.setRemark(remark);
			po.setCreateBy(user.getUserCode());
			po.setCreateByName(user.getUserName());
			po.setCreateTime(new Date());
			successList.add(po);
			
		}
		
		overAllStr.setLength(0);
		overAllStr.append("第");
		
		if (!CollectionUtils.isEmpty(errorMsgMap)) {
			List<String> resultErrorMsg = new ArrayList<>();
			errorMsgMap.forEach((i,v)->{
				resultErrorMsg.add(overAllStr.append(i+"行：").append(v.substring(0, v.length()-1)).toString());
				overAllStr.setLength(1);
			});
			return rt.setResultCode(ResultCode.FAIL).setResultMsg("导入失败").setData(resultErrorMsg);
		}
		
		List<String> insertFailList = new ArrayList<>();
		int accumulative = 0;
		try {
			for (int j = 0; j < successList.size(); j++) {
				accumulative = (j+1);
				Customer po = successList.get(j);
				/*int verify = customerMapper.verifyCustomerName(po.getCustomerName(),null);
				if (verify == 0) {
					String str = getNextNo();
					verify = customerMapper.verifyCustomerNo(str);
					str = verify == 0 ? str : String.valueOf((Integer.parseInt(str)+1));
					po.setCustomerNo(str);
					customerMapper.insert(po);
				}else {
					insertFailList.add(overAllStr.append(accumulative).append("行客户名称重复，新增失败！").toString());
					overAllStr.setLength(1);
				}*/
				String str = getNextNo();
				int verify = customerMapper.verifyCustomerNo(str);
				str = verify == 0 ? str : String.valueOf((Integer.parseInt(str)+1));
				po.setCustomerNo(str);
				customerMapper.insert(po);
			}
		} catch (Exception e) {
			insertFailList.add(overAllStr.append(accumulative).append("行新增失败").toString());
			overAllStr.setLength(1);
			e.printStackTrace();
		}
		
		return rt.setResultCode(ResultCode.OK).setResultMsg("导入"+(successList.size() - insertFailList.size())+"个数据成功")
				.setData(CollectionUtils.isEmpty(insertFailList)?null:insertFailList);
	}
	
	
	private String getNextNo() {
		String year = new SimpleDateFormat("YY").format(new Date());
		String nextOn = customerMapper.findNextOn(year);
		int len = nextOn.length() + year.length();
		if (len<6) {
			len = 6 - nextOn.length() - year.length();
			for (int i = 0; i < len; i++) {
				nextOn = "0"+nextOn;
			}
		}
		return year + nextOn;
	}
	
}
