package cn.wise.sc.energy.power.plant.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.energy.power.plant.business.domain.UserInfo;
import cn.wise.sc.energy.power.plant.business.domain.UserInfoQuery;
import cn.wise.sc.energy.power.plant.business.repository.UserInfoRepository;
import cn.wise.sc.energy.power.plant.business.service.IUserInfoService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import cn.wise.sc.energy.power.plant.common.core.exception.ResponseEnum;
import org.springframework.beans.BeanUtils;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * @description:
 * @author: qh
 * @create: 2020-08-10 22:27
 **/
@Service
public class UserInfoServiceImpl implements IUserInfoService {

    final
    UserInfoRepository userInfoRepository;


    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public UserInfoServiceImpl(UserInfoRepository userInfoRepository) {
        this.userInfoRepository = userInfoRepository;
    }

    @Override
    public List<UserInfo> getSysUserByUsername(String username) {

        ResponseEnum.LICENCE_NOT_FOUND.assertNotEmpty(username);

        return userInfoRepository.findAll((root, query, criteriaBuilder) -> {
            Path<String> username1 = root.get("username");
            return criteriaBuilder.equal(username1, username);
        });
    }

    @Override
    public BaseResponse<Page<UserInfo>> page(Integer pageNo, Integer pageSize,
                                             String username, String plantId) {

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable page = PageRequest.of(pageNo, pageSize, sort);
        Page<UserInfo> userInfoPage;

        Specification<UserInfo> specification = (root, query, criteriaBuilder) -> {
            Path<String> plantPath = root.get("plantid");
            Predicate equalPlant = criteriaBuilder.equal(plantPath, plantId);
            if (StrUtil.isNotBlank(username)) {
                Path<Object> path = root.get("username");
                Predicate equalUsername = criteriaBuilder.equal(path, username);
                return criteriaBuilder.and(equalPlant, equalUsername);
            } else {
                return equalPlant;
            }
        };
        userInfoPage = userInfoRepository.findAll(specification, page);
        return BaseResponse.okData(userInfoPage);
    }

    @Override
    public BaseResponse<Boolean> addUserInfo(UserInfoQuery userInfo) {

        UserInfo userInfoNew = new UserInfo();
        BeanUtils.copyProperties(userInfo, userInfoNew);
        userInfoNew.setPassword(passwordEncoder.encode(userInfoNew.getPassword()));

        int size = getSysUserByUsername(userInfo.getUsername()).size();
        if (size > 0) {
            return BaseResponse.errorMsg("用户名已存在!");
        }
        if (StrUtil.isNotBlank(userInfo.getPlantId())){
            userInfoNew.setPlantid(userInfo.getPlantId());
        }
        userInfoNew.setId(null);
        userInfoNew.setRole(0);
        UserInfo save = userInfoRepository.save(userInfoNew);
        if (save.getId() != null) {
            return BaseResponse.okData(true);
        } else {
            return BaseResponse.okData(false);
        }
    }

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String a = passwordEncoder.encode("123123");
        System.out.println(a);
    }

    @Override
    public BaseResponse<Boolean> edit(UserInfoQuery userInfo) {

        UserInfo one = userInfoRepository.getOne(userInfo.getId());
        userInfo.setPlantId("");
        if (StrUtil.isNotBlank(userInfo.getPassword())) {
            one.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        }
        BeanUtil.copyProperties(userInfo, one, CopyOptions.create().ignoreNullValue());

        userInfoRepository.saveAndFlush(one);
        return BaseResponse.okData(true);
    }

    @Override
    public BaseResponse<Boolean> del(String id) {
        try {
            userInfoRepository.deleteById(id);
            return BaseResponse.okData(Boolean.TRUE);
        }catch (Exception ex){
            return BaseResponse.errorMsg("删除失败!");
        }
    }
}
