package com.goafanti.customer.service.impl;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.IdentityProcess;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.*;
import com.goafanti.customer.service.UserClueService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserClueServiceImpl extends BaseMybatisDao<UserMapper> implements UserClueService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserMidMapper userMidMapper;
    @Resource
    private UserTransferLogMapper userTransferLogMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private UserLockReleaseMapper userLockReleaseMapper;
    @Resource
    private UserNamesMapper userNamesMapper;
    @Resource
    private OrganizationContactBookMapper organizationContactBookMapper;
    @Resource
    private OrganizationIdentityMapper organizationIdentityMapper;


    @Resource(name = "passwordUtil")
    private PasswordUtil					passwordUtil;

    @Override
    public Pagination<OutUserClueList> list(InputUserClueList in) {
        if (TokenManager.hasRole(AFTConstants.SUPERADMIN)){
            in.setShiroType(0);
        }
        if (in.getShiroType()==null){
            in.setShiroType(2);
        }
        in.setAid(TokenManager.getAdminId());
        if(in.getEndTime()!=null)in.setEndTime(in.getEndTime()+ " 23:59:59");
        return pushReleaseUser((Pagination<OutUserClueList>) findPage("selectUserClueList", "selectUserClueCount", in));
    }

    private Pagination<OutUserClueList> pushReleaseUser(Pagination<OutUserClueList> page) {
        List<OutUserClueList> list = (List<OutUserClueList>) page.getList();
        LocalDateTime now = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime clueTime = null;
        if (!list.isEmpty()){
            for (OutUserClueList e : list) {
                clueTime=e.getClueTransferTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                clueTime = clueTime.withHour(0).withMinute(0).withSecond(0).plusDays(AFTConstants.CLUE_USER_MAX);
                long between = ChronoUnit.DAYS.between(now,clueTime);
                e.setDays((int) between);
            }
        }
        return page;
    }
    @Override
    public Object add(InputUserClueBo in) throws BusinessException{
        Admin admin = adminMapper.selectById(TokenManager.getAdminId());
        String mobile = "";
        List<String> mobileList = new ArrayList<>();
        if (in.getContactMobile().equals("-")){
            if (in.getContactMobileMore().equals("-")){
                throw new BusinessException("手机号不能为空");
            }else {
                String[] split = in.getContactMobileMore().split(";");
                mobile=split[0];
                mobileList.addAll(Arrays.asList(split));
            }
        }else {
            String[] split = in.getContactMobile().split(";");
            mobile=split[0];
            mobileList.addAll(Arrays.asList(split));
            if (!in.getContactMobileMore().equals("-")){
                String[] split2 = in.getContactMobileMore().split(";");
                mobileList.addAll(Arrays.asList(split2));
            }
        }
        return add(in,admin,mobileList,mobile);
    }

    public Object add(InputUserClueBo in,Admin admin,List<String> mobileList,String mobile) throws BusinessException{
        User user = new User();
        Date now = new Date();
        String aid= TokenManager.getAdminId();
        String uid = UUID.randomUUID().toString();
        String identifyId = UUID.randomUUID().toString();
        user.setId(uid);
        user.setSource(1);// 客户来源为录入
        user.setIdentifyName(in.getUserName());
        user.setNickname(in.getUserName());
        user.setUsername(in.getUserName());
        user.setStatus(AFTConstants.USER_STATUS_NORMAL);
        user.setShareType(5);
        user.setAid(TokenManager.getAdminId());
        user.setClueAid(TokenManager.getAdminId());
//		user.setAid("1");
        user.setType(1);
        user.setLvl(UserLevel.CERTIFIED.getCode());
        user.setCreateTime(now);
        user.setTransferTime(now);
        user.setUpdateTime(now);
        user.setSignBills(0);
        user.setNewChannel(0);
        user.setMobile(mobile);
        user.setPassword(AFTConstants.INITIALPASSWORD);
        user.setInformationMaintainer(TokenManager.getAdminId());
        double f = 0;
        user.setIntegrity(f);
//		user.setInformationMaintainer("1");
        user.setChannel(0);
        user.setClueProcess(0);
        user.setClueStatus(1);
        user.setClueTime(now);
        user.setClueTransferTime(now);
        passwordUtil.encryptPassword(user);
        UserMid um=new UserMid();
        um.setAid(user.getAid());
        um.setUid(uid);
        userMidMapper.insertSelective(um);
        // 创建企业认证信息
        OrganizationIdentity oi = new OrganizationIdentity();
        oi.setUnitName(in.getUserName());
        oi.setId(identifyId);
        oi.setUid(uid);
        oi.setContacts(in.getContacts());
        oi.setContactMobile(mobile);
        oi.setHighTechZone(AFTConstants.NO);
        oi.setInternational(AFTConstants.NO);
        oi.setListed(AFTConstants.NO);
        oi.setAuditStatus(IdentityProcess.SUCCESS.getCode()); // 实名企业
        organizationIdentityMapper.insert(oi);
        userMapper.insertSelective(user);
        UserNames un=new UserNames();
        un.setUid(uid);
        un.setAid(aid);
        un.setName(user.getNickname());
        userNamesMapper.insertSelective(un);
        // 新增企业联系人
        iterContactBook(in.getContacts(),mobileList,admin.getName(),uid,mobile);
        addUserTransferLog(user,22,null);
        return 1;
    }

    private void iterContactBook(String name,List<String> mobileList, String aname, String uid,String mobile) {
        organizationContactBookMapper.updateSubContact(uid);
            for (String s : mobileList) {
                if (StringUtils.isNotBlank(s)) {
                    OrganizationContactBook cob2 = new OrganizationContactBook();
                    cob2.setAid(TokenManager.getAdminId());
                    cob2.setAname(aname);
                    cob2.setId(UUID.randomUUID().toString());
                    cob2.setUid(uid);
                    cob2.setName(name);
                    cob2.setMobile(s);
                    if (s.equals(mobile)){
                        cob2.setMajor(AFTConstants.YES);
                    }else {
                        cob2.setMajor(AFTConstants.NO);
                    }
                    organizationContactBookMapper.insert(cob2);
                }
            }
        }

    @Override
    public Map<String, Object> pushImportUserClue(List<OutUserClueExcel> list) {
        StringBuilder msg = new StringBuilder();
        int size=0;
        for (OutUserClueExcel e : list) {
            User user = null;
            try {
                checkMobile(e.getContactMobile());
                checkMobile(e.getContactMobileMore());
                checkContacts(e.getContacts());
                //判定客户名称
                user = checkUserName(e.getNickname());
            }catch (BusinessException ex){
                size++;
                msg.append("<br/>客户[").append(e.getNickname()).append("]导入失败，原因：").append(ex.getMessage()).append(" ");
                continue;
            }

            InputUserClueBo inUserClueBo = new InputUserClueBo();
            inUserClueBo.setUserName(e.getNickname());
            inUserClueBo.setContactMobile(e.getContactMobile());
            inUserClueBo.setContacts(e.getContacts());
            inUserClueBo.setContactMobileMore(e.getContactMobileMore());
            try {
                if (user==null){
                    add(inUserClueBo);
                }else {
                    update(inUserClueBo,user);
                }
            }catch (Exception ex){
                size++;
                msg.append("<br/>客户[").append(e.getNickname()).append("]新增异常。 ");
            }
        }

        Map<String,Object> map = new HashMap();
        map.put("errorCount",size);
        if (size==0){
            msg.append("客户导入成功.");
        }
        map.put("msg",msg);
        return map;
    }

    private void update(InputUserClueBo in,User user) {
        Admin admin = adminMapper.selectById(TokenManager.getAdminId());
        String mobile = "";
        List<String> mobileList = new ArrayList<>();
        if (in.getContactMobile().equals("-")){
            if (in.getContactMobileMore().equals("-")){
                throw new BusinessException("手机号不能为空");
            }else {
                String[] split = in.getContactMobileMore().split(";");
                mobile=split[0];
                mobileList.addAll(Arrays.asList(split));
            }
        }else {
            String[] split = in.getContactMobile().split(";");
            mobile=split[0];
            mobileList.addAll(Arrays.asList(split));
            if (!in.getContactMobileMore().equals("-")){
                String[] split2 = in.getContactMobile().split(";");
                mobileList.addAll(Arrays.asList(split2));
            }
        }
        Date now = new Date();
        User newUser =new User();
        newUser.setId(user.getId());
        newUser.setClueProcess(0);
        newUser.setClueStatus(1);
        newUser.setClueTime(now);
        newUser.setAid(admin.getId());
        newUser.setClueAid(admin.getId());
        newUser.setShareType(5);
        newUser.setTransferTime(now);
        newUser.setClueTransferTime(now);
        userMapper.update(newUser);
        // 新增企业联系人
        iterContactBook(in.getContacts(),mobileList,admin.getName(),user.getId(),mobile);
    }

    private void checkContacts(String contacts) throws BusinessException {
        String nameReg="[\\u4e00-\\u9fa5]+.*";
        Pattern  pattern =Pattern.compile(nameReg);
        Matcher matcher = pattern.matcher(contacts);
        if (!matcher.matches()){
            throw new BusinessException("联系人名称名称格式不正确");
        }
    }

    private void checkMobile(String contactMobile) throws BusinessException{
        if (!contactMobile.equals("-")){
            String[] split = contactMobile.split(";");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)){
                    String mobileReg="[1-9]\\d{10}";
                    String mobileReg2="^0\\d{2,3}-?\\d{7,8}$";
                    Pattern  pattern =Pattern.compile(mobileReg);
                    Matcher matcher = pattern.matcher(s);
                    if (!matcher.matches()){
                        Pattern  pattern2 =Pattern.compile(mobileReg2);
                        Matcher matcher2 = pattern2.matcher(s);
                        if (!matcher2.matches()){
                            throw new BusinessException("手机号格式不正确");
                        }
                    }
                }

            }
        }


    }



    @Override
    public Object updateTransfer(InputUserClueTransferBo in) {
        String[] split = in.getUid().split(",");
        for (String uid : split) {
            userTransfer(uid,in);
        }
        return 1;
    }

    private void userTransfer(String uid,InputUserClueTransferBo in) {
        User user = userMapper.queryById(uid);
        Date date = new Date();
        if (!user.getAid().equals(TokenManager.getAdminId())){
            throw new BusinessException("只能操作所属客户");
        }
        String aid=in.getTransferId();
        int type = 0;
        if (in.getType()==0){
            user.setAid(in.getTransferId());
            user.setClueProcess(1);
            type=23;
        }else if (in.getType()==1){
            user.setClueProcess(2);
            user.setAid(user.getClueAid());
            type=24;
            aid=user.getClueAid();
        }else if (in.getType()==2){
            user.setClueProcess(3);
            userMapper.update(user);
            type=25;
        }else if (in.getType()==3){
            user.setClueProcess(4);
            user.setShareType(0);

            type=26;
            if (userLockReleaseMapper.selectByUidGetCount(aid,user.getId())==0){
                UserLockRelease ulr=new UserLockRelease();
                ulr.setId(UUID.randomUUID().toString());
                ulr.setAid(TokenManager.getAdminId());
                ulr.setUid(user.getId());
                ulr.setLockTime(date);
                ulr.setStatus(0);
                ulr.setType(0);
                userLockReleaseMapper.insert(ulr);
            }
            organizationContactBookMapper.updateAdmin(user.getId(),TokenManager.getAdminId());
        }
        user.setTransferTime(date);
        userMapper.update(user);
        addUserTransferLog(user,type,aid);
    }

    /**
     *
     * @param user 客户信息
     * @param type  22=导入线索客户，23=转交线索客户，24=退回线索客户，25=移除线索客户，26=领取线索客户
     */
    private void addUserTransferLog(User user,Integer type,String transferId) {
        UserTransferLog u = new UserTransferLog();
        u.setUid(user.getId());
        u.setAid(TokenManager.getAdminId());
        if (type==23||type==24){
            u.setTakeAid(transferId);
        }
        u.setType(type);
        userTransferLogMapper.insertSelective(u);
    }


    private User checkUserName(String name) throws BusinessException{
//        if (!userMapper.checkUser("", name, "", 1, null, null).isEmpty())
//            throw new BusinessException("客户已经存在");
        String name2=null;
        if (name.contains("(")){
            name2=name.replace("(","（").replace(")","）");
        }else if (name.contains("（")){
            name2=name.replace("（","(").replace("）",")");
        }
//        if (name2!=null){
//            if (!userMapper.checkUser("", name2, "", 1, null, null).isEmpty())
//                throw new BusinessException("客户已经存在");
//        }
        User user = userMapper.selectByName(name);
        if (user==null){
            user = userMapper.selectByName(name2);
        }
        if (user!=null){
            if (user.getShareType()==0){
                throw new BusinessException("客户已经存在私有客户");
            }else if (user.getShareType()==2){
                throw new BusinessException("客户已经存在签单客户");
            }else if (user.getShareType()==5){
                throw new BusinessException("客户已经存在线索客户");
            }
            return user;
        }
        return null;
    }
}
