package com.huimv.admin.service.primary.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.admin.domain.primary.SysAccountEntity;
import com.huimv.admin.domain.primary.SysUserEntity;
import com.huimv.admin.group.UserAndAccountGroup;
import com.huimv.admin.repo.primary.SysAccountEntityRepository;
import com.huimv.admin.repo.primary.SysUserEntityRepository;
import com.huimv.admin.service.primary.IUserService;
import com.huimv.admin.utils.Result;
import com.huimv.admin.utils.ResultCode;
import com.huimv.admin.utils.id.SnowflakeSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private SysUserEntityRepository sysUserEntityRepository;
    @Autowired
    private SysAccountEntityRepository sysAccountEntityRepository;

    @Override
    public Page<SysUserEntity> findUser(String searchStr, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        if (!StringUtils.isEmpty(searchStr)) {
            Page<SysUserEntity> userEntityList = sysUserEntityRepository.findByUserNameOOrMobile(searchStr, pageable);
            return userEntityList;
        }
        System.out.println("findAll");
        return sysUserEntityRepository.findAll(pageable);

    }

    public Page<SysUserEntity> findUser2(String searchStr, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        Page<SysUserEntity> userPage = sysUserEntityRepository.findAll(new Specification<SysUserEntity>(){
            @Override
            public Predicate toPredicate(Root<SysUserEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(null != searchStr && !"".equals(searchStr)){
                    list.add((Predicate) criteriaBuilder.equal(root.get("userName").as(String.class), searchStr));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        },pageable);
        return userPage;
    }

    @Override
    public JSONObject findUserAccount(String searchStr, int pageNum, int pageSize) {
//        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        int start = (pageNum-1)*pageSize;
        System.out.println("start>>"+start);

        if (!StringUtils.isEmpty(searchStr)) {
            List<Object[]> userAccountList = sysUserEntityRepository.findUserAndAccountByUserName(searchStr, start,pageSize);
            JSONArray userAccountJa = new JSONArray();
            for(int a=0;a<userAccountList.size();a++){
                Object[] userAccountObj = (Object[]) userAccountList.get(a);
                /* 封装用户和账户关联对象 */
                userAccountJa.add(packageUserAccountRelatedObj(userAccountObj));
            }
            int total = sysUserEntityRepository.countByUserName(searchStr);
            JSONObject resultJo = new JSONObject();
            resultJo.put("code",10001);
            resultJo.put("totalElements",total);
            resultJo.put("data",userAccountJa);
            return resultJo;
        }
        List<Object[]> allUserAccountList = sysUserEntityRepository.findUserAndAccount(start,pageSize);
        JSONArray allUserAccountJa = new JSONArray();
        for(int a=0;a<allUserAccountList.size();a++){
            Object[] userAccountObj = (Object[]) allUserAccountList.get(a);
            /* 封装用户和账户关联对象 */
            allUserAccountJa.add(packageUserAccountRelatedObj(userAccountObj));
        }
        Long total = sysUserEntityRepository.count();
        JSONObject resultJo = new JSONObject();
        resultJo.put("code",10001);
        resultJo.put("totalElements",total);
        resultJo.put("data",allUserAccountJa);
        return resultJo;
    }

    /**
     * 封装对象
     */
    private Object packageUserAccountRelatedObj(Object[] userAccountObj) {
        JSONObject dataJo = new JSONObject();
        dataJo.put("id",userAccountObj[0].toString());
        dataJo.put("userName",userAccountObj[1].toString());
        if(userAccountObj[2] == null){
            dataJo.put("male","");
        }else{
            dataJo.put("male",userAccountObj[2].toString());
        }
        if(userAccountObj[3] == null){
            dataJo.put("birthday","");
        }else{
            dataJo.put("birthday",userAccountObj[3].toString());
        }
        if(userAccountObj[4] == null){
            dataJo.put("mobile","");
        }else{
            dataJo.put("mobile",userAccountObj[4].toString());
        }
        if(userAccountObj[5] == null){
            dataJo.put("address","");
        }else{
            dataJo.put("address",userAccountObj[5].toString());
        }
        if(userAccountObj[6] == null){
            dataJo.put("job","");
        }else{
            dataJo.put("job",userAccountObj[6].toString());
        }
        if(userAccountObj[7] == null){
            dataJo.put("remark","");
        }else{
            dataJo.put("remark",userAccountObj[7].toString());
        }
        if(userAccountObj[8] == null)
        {
            dataJo.put("userId","");
        }else{
            dataJo.put("userId",userAccountObj[8].toString());
        }
        if(userAccountObj[9] == null){
            dataJo.put("accountName","");
        }else{
            dataJo.put("accountName",userAccountObj[9].toString());
        }
        if(userAccountObj[10] == null)
        {dataJo.put("accountStatus","");

        }else{
            dataJo.put("accountStatus", Integer.parseInt(userAccountObj[10].toString()));
        }
        return dataJo;
    }

    @Override
    public JSONObject findUserAccount2(String searchStr, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        System.out.println("searchStr>>"+searchStr);
        if (!StringUtils.isEmpty(searchStr)) {
//            List<Object[]> userAccountList = sysUserEntityRepository.findUserAndAccountByUserName(searchStr, pageable);
            Page<SysUserEntity> userPage = sysUserEntityRepository.findUserAndAccount2(searchStr,pageable);

            int total = sysUserEntityRepository.countByUserName(searchStr);
            JSONObject resultJo = new JSONObject();
            resultJo.put("code",10001);
            resultJo.put("totalElements",total);
            resultJo.put("data",userPage);
            return resultJo;
        }
        System.out.println("pageable.toSting()>>"+pageable.toString());
        Page<SysUserEntity> userPage = sysUserEntityRepository.findUserAndAccount2(searchStr,pageable);

        Long total = sysUserEntityRepository.count();
        JSONObject resultJo = new JSONObject();
        resultJo.put("code",10001);
        resultJo.put("totalElements",total);
        resultJo.put("data",userPage);
        return resultJo;
    }


    @Override
    public List<UserAndAccountGroup> yxxList(String searchStr, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        List<UserAndAccountGroup> list = new ArrayList<>();
        if (searchStr != null && !"".equals(searchStr)){
            Page<SysUserEntity> users = sysUserEntityRepository.findByUserNameOOrMobile(searchStr, pageable);
            for (SysUserEntity user : users) {
                SysAccountEntity account = sysAccountEntityRepository.findByUserId(user.getUserId()).get(0);
                UserAndAccountGroup userAndAccountGroup = saveUser(user);
                userAndAccountGroup.setAccountName(account.getAccountName());
                userAndAccountGroup.setAccountStatus(account.getAccountStatus());
                list.add(userAndAccountGroup);
            }
        }
        Page<SysUserEntity> users = sysUserEntityRepository.findAll(pageable);
        for (SysUserEntity user : users) {
            SysAccountEntity account = sysAccountEntityRepository.findByUserId(user.getUserId()).get(0);
            UserAndAccountGroup userAndAccountGroup = saveUser(user);
            userAndAccountGroup.setAccountName(account.getAccountName());
            userAndAccountGroup.setAccountStatus(account.getAccountStatus());
            list.add(userAndAccountGroup);
        }
        return list;

    }

    @Override
    public Result addUser(SysUserEntity user) {
        try {
            SnowflakeSequence idWorker = new SnowflakeSequence();
            long userId = idWorker.nextId();
            // 添加用户信息
            user.setUserId(userId);
            sysUserEntityRepository.save(user);

            // 添加账号信息
            String mobile = user.getMobile();
            String userName = user.getUserName();
            SysAccountEntity sysAccountEntity = new SysAccountEntity();
            if (mobile != null && !"".equals(mobile) ){
                sysAccountEntity.setAccountName(mobile);
            }else if (userName != null && !"".equals(userName)){
                sysAccountEntity.setAccountName(userName);
            }
            sysAccountEntity.setAccountStatus(0);
            sysAccountEntity.setRemark("");
//            sysAccountEntity.setPassword(GetMD5Str.getMD5Str("123456"));
            sysAccountEntity.setPassword("123456");
            sysAccountEntity.setUserId(userId);
            sysAccountEntityRepository.save(sysAccountEntity);
            return new Result(10000,"修改成功",true);
        }catch (Exception e){
             return new Result(10001,"添加失败",false);
        }
    }

    @Override
    public Result updateUser(SysUserEntity user) {
        try {
            if (user == null) {
                return  new Result(ResultCode.FAIL);
            }
            sysUserEntityRepository.save(user);
            return new Result(10000,"修改成功",true);
        }catch (Exception e){
            return new Result(10001,"修改失败",false);
        }
    }

    @Override
    public Result removeUser(List<Integer> userIds) {
        for (Integer userId : userIds) {
            try {
                SysUserEntity user = this.sysUserEntityRepository.findById(userId).orElse(null);
                if (user == null) {
                    return new Result(10002,"请选择数据",false);
                }
                this.sysUserEntityRepository.deleteById(userId);
                // 删除账号
                this.sysAccountEntityRepository.deleteByUserId(user.getUserId());
            }catch (Exception e){
                return new Result(10001,"删除失败",false);
            }
        }
        return new Result(10000,"删除成功",false);
    }

    private UserAndAccountGroup saveUser(SysUserEntity user) {
        UserAndAccountGroup userAndAccountGroup = new UserAndAccountGroup();
        userAndAccountGroup.setAddress(user.getAddress());
        userAndAccountGroup.setBirthday(user.getBirthday());
        userAndAccountGroup.setId(user.getId());
        userAndAccountGroup.setJob(user.getJob());
        userAndAccountGroup.setMale(user.getMale());
        userAndAccountGroup.setMobile(user.getMobile());
        userAndAccountGroup.setRemark(user.getRemark());
        userAndAccountGroup.setUserId(user.getUserId());
        userAndAccountGroup.setUserName(user.getUserName());
        return userAndAccountGroup;
    }


}
