package com.hwrj.cloud.portal.service.impl;


import com.hwrj.cloud.portal.domain.MemberDetails;
import com.hwrj.cloud.portal.domain.UmsMemberCert;
import com.hwrj.cloud.portal.domain.UmsMemberPlaformDo;
import com.hwrj.cloud.portal.mapper.UmsCompanyInfoMapper;
import com.hwrj.cloud.portal.mapper.UmsCompanyShareMapper;
import com.hwrj.cloud.portal.mapper.UmsMemberMapper;
import com.hwrj.cloud.portal.mapper.UmsMemberPlatformMapper;
import com.hwrj.cloud.portal.model.*;
import com.hwrj.cloud.portal.service.UmsMemberCacheService;
import com.hwrj.cloud.portal.service.UmsMemberPlatformService;
import com.hwrj.cloud.portal.service.UmsMemberService;
import com.hwrj.cloud.security.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class UmsMemberPlatformServiceImpl implements UmsMemberPlatformService {
    @Autowired
    private UmsMemberPlatformMapper umsMemberPlatformMapper;

    @Autowired
    private UmsMemberMapper umsMemberMapper;

    @Autowired
    private UmsCompanyInfoMapper umsCompanyInfoMapper;

    @Autowired
    private UmsMemberCacheService memberCacheService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${forest.wx.password}")
    private String password;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UmsCompanyShareMapper umsCompanyShareMapper;

    @Autowired
    private UmsMemberService umsMemberService;
    @Override
    @Transactional
    public String addUmsMemberPlatformService(UmsMemberPlatform umsMemberPlatform) {
        String token = null;
        UmsMemberPlatformExample example= new UmsMemberPlatformExample();
        UmsMemberPlatformExample.Criteria criteria = example.createCriteria();
        criteria.andOpenidEqualTo(umsMemberPlatform.getOpenid());
        if (!StringUtils.isEmpty(umsMemberPlatform.getUnionid())){
            criteria.andUnionidEqualTo(umsMemberPlatform.getUnionid());
        }
        List<UmsMemberPlatform> umsMemberPlatforms = umsMemberPlatformMapper.selectByExample(example);
        if (umsMemberPlatforms != null && umsMemberPlatforms.size()>0){
            UmsMemberPlatform umsMemberPlatform1 = umsMemberPlatforms.get(0);
            UmsMember umsMember1 = insetOrGetMemberPlatform(umsMemberPlatform1);
            UserDetails userDetails = new MemberDetails(umsMember1);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            memberCacheService.delToken(userDetails.getUsername());
            memberCacheService.setToken(token,userDetails.getUsername());
        }else {
            int insert = umsMemberPlatformMapper.insert(umsMemberPlatform);

            if (insert>0){
                UmsMemberPlatformExample example1= new UmsMemberPlatformExample();
                UmsMemberPlatformExample.Criteria criteria1 = example.createCriteria();
                criteria1.andOpenidEqualTo(umsMemberPlatform.getOpenid());
                if (!StringUtils.isEmpty(umsMemberPlatform.getUnionid())){
                    criteria1.andUnionidEqualTo(umsMemberPlatform.getUnionid());
                }
                List<UmsMemberPlatform> umsMemberPlatforms1 = umsMemberPlatformMapper.selectByExample(example);
                UmsMemberPlatform umsMemberPlatform1 = umsMemberPlatforms1.get(0);
                UmsMember umsMember1 = insetOrGetMemberPlatform(umsMemberPlatform1);
                UserDetails userDetails = new MemberDetails(umsMember1);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                token = jwtTokenUtil.generateToken(userDetails);
                memberCacheService.setToken(token,userDetails.getUsername());
            }
        }
        return token;
    }
    @Override
    public void certMember(UmsMemberCert cert) {
        UmsMember umsMember = new UmsMember();
        umsMember.setId(cert.getId());
        umsMember.setPhone(cert.getPhone());
        umsMember.setMail(cert.getMail());
        umsMember.setAddress(cert.getAddress());
        umsMember.setNickname(cert.getNickname());
        if("供应商".equals(cert.getType())){
            String companyName = cert.getCompanyName();
            String certNo = cert.getCertNo();
            UmsCompanyShare share = getCompanyShareByShareCode(certNo, companyName);
            if (share == null){
                throw new RuntimeException("供应商认证失败,请检查供应商名称和邀请码!");
            }
            int days = numDays(share.getCreateTime());
            if (days>7){
                throw new RuntimeException("认证失败");
            }
            share.setMemberId(cert.getId());
            share.setMember(cert.getNickname());
            umsMember.setCompId(share.getCompId());
            umsMember.setCompanyInfo(companyName);
            umsMember.setCert(2);
            umsMember.setType(companyName);
            umsMember.setWay("供应商");
            updateShare(share);
        }else{
            umsMember.setWay(cert.getWay());
            umsMember.setType(cert.getType());
        }
        umsMemberMapper.updateByPrimaryKeySelective(umsMember);

    }

    public UmsMemberPlaformDo loadUmsMemberPlatform(UmsMemberPlatform umsMemberPlatform){
        if (umsMemberPlatform != null){
            return new UmsMemberPlaformDo(umsMemberPlatform);
        }
        throw new UsernameNotFoundException("微信登录失败");
    }

    /**
     * 根据分享code和供应商名称来获取分享信息
     * @param shareCode
     * @param compName
     * @return
     */
    public UmsCompanyShare getCompanyShareByShareCode(String shareCode,String compName){
        if (StringUtils.isEmpty(shareCode)){
            return null;
        }
        UmsCompanyShareExample example = new UmsCompanyShareExample();
        UmsCompanyShareExample.Criteria criteria = example.createCriteria();
        criteria.andShareCodeEqualTo(shareCode);
        if (!StringUtils.isEmpty(compName)){
            criteria.andCompNameLike("%"+compName+"%");
        }
        criteria.andStatusEqualTo(0);
        List<UmsCompanyShare> shares = umsCompanyShareMapper.selectByExample(example);
        if (shares != null && shares.size()>0){
            return shares.get(0);
        }
        return  null;
    }
    public void updateShare(UmsCompanyShare share){
        UmsCompanyShare ums = new UmsCompanyShare();
        ums.setId(share.getId());
        ums.setUpdateTime(new Date());
        ums.setStatus(1);
        ums.setMemberId(share.getMemberId());
        ums.setMember(share.getMember());
        umsCompanyShareMapper.updateByPrimaryKeySelective(share);
    }

    public  int numDays(Date fromDate){
        Date toDate1 = new Date();
        long from1 = fromDate.getTime();
        long to1 = toDate1.getTime();
        int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));
        return days;
    }

    /**
     * 添加用户并获取返回id
     * @param umsMemberPlatform
     * @return
     */
    public UmsMember insetOrGetMemberPlatform(UmsMemberPlatform umsMemberPlatform){
        UmsMember umsMember = new UmsMember();
        if (umsMemberPlatform.getMemberId()==null){
            umsMember.setNickname(umsMemberPlatform.getNickname());
            umsMember.setUsername(umsMemberPlatform.getOpenid());
            umsMember.setPassword(passwordEncoder.encode(password));
            umsMember.setMemberLevelId(4L);
            umsMember.setStatus(1);
            umsMember.setCreateTime(new Date());
            umsMember.setIcon(umsMemberPlatform.getHeadimgurl());
            int i = umsMemberMapper.insertSelective(umsMember);
            UmsMemberExample example = new UmsMemberExample();
            UmsMemberExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameEqualTo(umsMemberPlatform.getOpenid());
            List<UmsMember> umsMembers = umsMemberMapper.selectByExample(example);
            if (umsMembers==null||umsMembers.size()<1){
                throw new RuntimeException("登录失败003");
            }
            UmsMember ums = umsMembers.get(0);
            UmsMemberPlatform ff = new UmsMemberPlatform();
            ff.setId(umsMemberPlatform.getId());
            umsMemberPlatform.setMemberId(ums.getId());
            ff.setMemberId(ums.getId());
            umsMemberPlatformMapper.updateByPrimaryKeySelective(ff);
            return ums;

        }else {
            boolean flag = false;
            Long memberId = umsMemberPlatform.getMemberId();
            UmsMember umsMemberRe = umsMemberMapper.selectByPrimaryKey(memberId);
            String nickname = umsMemberRe.getNickname();
            String nicknameParm = umsMemberPlatform.getNickname();
            if(!nickname.equals(nicknameParm)){
                umsMemberRe.setNickname(nicknameParm);
                flag = true;
            }
            String openidRe = umsMemberRe.getUsername();
            String openidParm = umsMemberPlatform.getOpenid();
            if(!openidRe.equals(openidParm)){
                umsMemberRe.setUsername(openidParm);
                flag = true;
            }
            //有昵称变化就更新数据库
            if(flag){
                umsMemberMapper.updateByPrimaryKeySelective(umsMemberRe);
            }
            return umsMemberRe;
        }
    }


}
