package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.OperationType;
import com.mvc.dao.CustomUserMapper;
import com.mvc.entity.*;
import com.mvc.model.CustomUserModel;
import com.mvc.model.TAffiliatedunitModel;
import com.mvc.model.TRgeAuthModel;
import com.mvc.service.TAffiliatedunitService;
import com.mvc.service.log.OperationLogService;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

//客户登录Service
@Service
@Transactional
public class CustomUserService {

    @Resource
    private CustomUserMapper customUserMapper;

    @Resource
    private TAffiliatedunitService tAffiliatedunitService;

    @Resource
    private OperationLogService operationLogService;

    public Map<String, Object> findAllCustomUser(CustomUserModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        List<CustomUserModel> resList = new ArrayList<>();
        if (queryModel.getAdminFlag() == null || !queryModel.getAdminFlag().equals("1")) {
            CustomUserModel customUserModel = findCustomUserModelByUserId(queryModel.getUserId());
            if (customUserModel == null) {
                resMap.put("total", 0);
                resMap.put("list", resList);
                return resMap;
            } else {
                if (customUserModel.getAdminFlag() == null || !customUserModel.getAdminFlag().equals("1")) {//查询的用户不是管理员,只返回自己的数据
                    resList.add(customUserModel);
                    resMap.put("total", 1);
                    resMap.put("list", resList);
                    return resMap;
                }
            }
        }

        CustomUserExample example = new CustomUserExample();
        CustomUserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getUserName())) {
            criteria.andUserNameLike("%" + queryModel.getUserName() + "%");
        }

        if (StringUtils.isNotEmpty(queryModel.getUnitCode())) {
            criteria.andUnitCodeEqualTo(queryModel.getUnitCode());
        }
        example.setOrderByClause("ID desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<CustomUser> CustomUsers = customUserMapper.selectByExample(example);
        for (CustomUser CustomUser : CustomUsers) {
            CustomUserModel model = new CustomUserModel();
            BeanUtils.copyProperties(CustomUser, model);
            if (StringUtils.isNotEmpty(model.getUnitCode())) {
                TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(model.getUnitCode());
                if (unitModel != null) {
                    model.setUnitName(unitModel.getUnitName());
                }
            }
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public CustomUserModel saveCustomUser(CustomUserModel model) {
        model.setUserId(StringUtil.getUuid());
        CustomUser CustomUser = new CustomUser();
        BeanUtils.copyProperties(model, CustomUser);
        int insert = customUserMapper.insert(CustomUser);
        model.setId(CustomUser.getId());
        return model;
    }

    public CustomUserModel updateCustomUser(CustomUserModel model) {
        CustomUser CustomUser = customUserMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, CustomUser);
        int i = customUserMapper.updateByPrimaryKey(CustomUser);
        return model;
    }

    public int deleteCustomUser(int id) {
        int i = customUserMapper.deleteByPrimaryKey(id);
        return i;
    }

    public CustomUserModel findCustomUserModelByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) return null;
        CustomUserExample example = new CustomUserExample();
        CustomUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<CustomUser> customUsers = customUserMapper.selectByExample(example);
        if (customUsers.size() > 0) {
            CustomUserModel resModel = new CustomUserModel();
            BeanUtils.copyProperties(customUsers.get(0), resModel);
            TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(resModel.getUnitCode());
            if (unitModel != null) {
                resModel.setAffiliatedunitModel(unitModel);
                resModel.setUnitName(unitModel.getUnitName());
            }
            return resModel;
        } else {
            return null;
        }
    }

    public CustomUserModel logincustomUser(String loginId) {
        CustomUserExample example = new CustomUserExample();
        CustomUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginIdEqualTo(loginId);
        //criteria.andLoginPwdEqualTo(loginPwd);
        List<CustomUser> users = customUserMapper.selectByExample(example);
        if (users.size() > 0) {
            CustomUserModel model = new CustomUserModel();
            BeanUtils.copyProperties(users.get(0), model);
            operationLogService.saveOperationLog(1, OperationType.LOGIN, model, "");

            TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(model.getUnitCode());
            if (unitModel != null) {
                model.setUnitType(unitModel.getUnitType());
                model.setUnitName(unitModel.getUnitName());
                model.setAffiliatedunitModel(unitModel);
            }
            return model;
        } else {
            return null;
        }
    }

    //注册用户，生成登录账号
    public CustomUserModel registCustomUser(TRgeAuthModel authModel, String customerName, String loginId, String loginPwd) {
        CustomUser user = new CustomUser();
        user.setUserId(StringUtil.getUuid());
        user.setUserName(customerName);
        user.setUnitCode(authModel.getUnitCode());
        user.setLoginId(loginId);
        user.setLoginPwd(loginPwd);
        user.setUseFlag("1");
        user.setCreateMan("授权码");
        user.setRgeAuthCode(authModel.getAuthCode());
        user.setUnitType(authModel.getUnitType());
        user.setGroupCode(authModel.getGroupCode());
        user.setCreateTime(new Date());
        user.setAdminFlag(authModel.getAdminFlag());
        if (customUserMapper.insert(user) > 0) {
            authModel.setAuthUseNum(authModel.getAuthUseNum() + 1);
            CustomUserModel resModel = new CustomUserModel();
            BeanUtils.copyProperties(user, resModel);
            operationLogService.saveOperationLog(1, OperationType.REGISTRATION, resModel, "");
            return resModel;
        }
        return null;
    }

    /**
     * 根据登陆ID获取用户对象(注册时判重使用)
     *
     * @param loginId
     * @return
     */
    public CustomUser findCustomUserByLoginId(String loginId) {
        if (StringUtils.isEmpty(loginId)) return null;
        CustomUserExample example = new CustomUserExample();
        CustomUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginIdEqualTo(loginId);
        List<CustomUser> customUsers = customUserMapper.selectByExample(example);

        return customUsers.size() > 0 ? customUsers.get(0) : null;
    }

    /**
     * 校验数据合法性
     * @param userName
     * @param loginId
     * @param loginPwd
     * @return
     */
    public String checkDataLegitimacy(String userName,String loginId,String loginPwd){
        if(userName.length()<2){
            return "用户名称长度至少2位";
        }
        if(loginId.length()<3){
            return "登陆账户长度至少3位";
        }
        if(loginPwd.length()<6){
            return "登陆密码长度至少6位";
        }
        if(!Character.isLetter(loginId.charAt(0))){
            return "登陆账户必须以字母开头";
        }
        if(!StringUtil.isLetterDigit(loginId)){
            return "登陆账户只能包含字母和数字";
        }
        return null;
    }
}
