package io.hmit.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.hmit.common.constant.Constant;
import io.hmit.common.exception.ErrorCode;
import io.hmit.common.exception.HmitException;
import io.hmit.common.page.PageData;
import io.hmit.common.service.impl.BaseServiceImpl;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.common.utils.SubListForPageUtil;
import io.hmit.common.validator.AssertUtils;
import io.hmit.dao.UserDao;
import io.hmit.dto.*;
import io.hmit.entity.TokenEntity;
import io.hmit.entity.UserEntity;
import io.hmit.modules.serviceOrder.dto.UserAddressDTO;
import io.hmit.modules.serviceOrder.dto.UserRoleInfoDTO;
import io.hmit.modules.serviceOrder.service.PensionOldFamilyService;
import io.hmit.modules.serviceOrder.service.RoleUserService;
import io.hmit.service.TokenService;
import io.hmit.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PensionOldFamilyService pensionOldFamilyService;

    @Autowired
    private RoleUserService roleUserService;

    @Override
    public UserEntity getByMobile(String mobile) {
        return baseDao.getUserByMobile(mobile);
    }

    @Override
    public UserEntity getByOpenId(String openId) {
        return baseDao.getUserByOpenId(openId);
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public UserInfoDTO getUserDetails(Long userId) {
        UserEntity user = userDao.getUserByUserId(userId);
        UserInfoDTO userInfoDTO = ConvertUtils.sourceToTarget(user, UserInfoDTO.class);
        userInfoDTO.setPensionOldFamilyDTOList(pensionOldFamilyService.findByOldId(userId));
        return userInfoDTO;
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        AssertUtils.isNull(user, ErrorCode.ACCOUNT_PASSWORD_ERROR);

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(dto.getPassword()))) {
            throw new HmitException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }

    /**
     * 用户登录
     *
     * @param openId 免登
     * @return 返回登录信息
     */
    @Override
    public Map<String, Object> login(String openId) {
        UserEntity user = getByOpenId(openId);
        AssertUtils.isNull(user, ErrorCode.WECHAT_OPENID_NOT_REGISTER);

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());
        List<UserRoleInfoDTO> roles = userDao.getUserRoleInfo(user.getId());
        roles = roles.stream().distinct().collect(Collectors.toList());
        map.put("roles", roles);

        return map;
    }

    @Override
    public PageData<UserEntity> getOrganizationAllUsers(Map<String, Object> params, Long userId) {
        IPage<UserEntity> page = getPage(params, Constant.CREATE_DATE, false);
        List<Long> serviceIds = userDao.getAllOrganizationStaff(userId);
        List<UserEntity> list = new ArrayList<>();
        for (Long id : serviceIds) {
            UserEntity userEntity = userDao.selectById(id);
            list.add(userEntity);
        }
        page.setTotal(list.size());
        return getPageData(list, page.getTotal(), UserEntity.class);
    }

    @Override
    public PageData<UserInfoDTO> getOrganizationStaff(Map<String, Object> params, Long userId) {
        List<UserEntity> list = userDao.getOrgStaff(userId);
        return getPageData(SubListForPageUtil.getSubList(params, list), list.size(), UserInfoDTO.class);
    }

    @Override
    public OrgUserInfoDTO getOrgUserByUserId(Long userId) {
        return userDao.getOrgUserByUserId(userId);
    }

    @Override
    public ServiceUserInfoDTO getServiceUserByUserId(Long userId) {
        return userDao.getServiceUserByUserId(userId);
    }

    @Override
    public UserRegisterDTO getUserInfoByIdCardNo(Long idCardNo) {
        return userDao.getUserInfoByIdCardNo(idCardNo);
    }

    @Override
    public void registerUser(UserRegisterDTO dto) {
        UserEntity reRegister = getByOpenId(dto.getOpenid());
        if (null != reRegister) {
            reRegister.setOpenid("");
            updateById(reRegister);
        }
        UserRegisterDTO userRegisterDTO = getUserInfoByIdCardNo(dto.getIdCardNo());
        UserEntity userEntity;
        if (null != userRegisterDTO) {
            userEntity = getUserByUserId(userRegisterDTO.getId());
            userEntity.setOpenid(dto.getOpenid());
            updateById(userEntity);
            roleUserService.addRelation(dto.getUserRole(), userRegisterDTO.getId());
        }else {
            userEntity = new UserEntity();
            userEntity.setUsername(dto.getUsername());
            userEntity.setMobile(dto.getMobile());
            if (null != userEntity.getPassword()) {
                userEntity.setPassword(DigestUtils.sha256Hex(dto.getIdCardNo().toString()));
            }
            userEntity.setAddress(dto.getAddress());
            userEntity.setAddressArea(dto.getAddressArea());
            userEntity.setCommunityId(dto.getCommunityId());
            userEntity.setCreateDate(new Date());
            userEntity.setIdCardNo(dto.getIdCardNo());
            userEntity.setCommunityName(dto.getCommunityName());
            userEntity.setHealthStatus("良好"); //TODO
            if (null != dto.getIdCardNo()) {
                String year = dto.getIdCardNo().toString().substring(6, 10);
                String month = dto.getIdCardNo().toString().substring(10, 12);
                String day = dto.getIdCardNo().toString().substring(12, 14);
                String time = year+"-"+month+"-"+day;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                try {
                    date = sdf.parse(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                userEntity.setBirthday(date);
                userEntity.setGender(Integer.parseInt(dto.getIdCardNo().toString().substring(16, 17)) % 2 == 1 ? "男" : "女");
            }
            userEntity.setOpenid(dto.getOpenid());
            insert(userEntity);
            UserEntity byOpenId = getByOpenId(dto.getOpenid());
            roleUserService.addRelation(dto.getUserRole(), byOpenId.getId());
        }
    }

    @Override
    public List<UserAddressDTO> findUserAddressByUsernameOrMobile(String str) {
        List<UserAddressDTO> userAddress = null;
        String mobile = null;
        if (str.length()==11){
            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            Matcher matcher = p.matcher(str);
            if (matcher.matches()) {
                mobile = str;
                str = null;
            }
        }
        userAddress = userDao.findUserAddressByUsernameOrMobile(str, mobile);
        return userAddress;
    }

}