package com.github.wxiaoqi.security.admin.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.dto.AppUserManageDTO;
import com.github.wxiaoqi.security.admin.entity.AppUserDetail;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.mapper.AppUserDetailMapper;
import com.github.wxiaoqi.security.admin.mapper.AppUserLoginMapper;
import com.github.wxiaoqi.security.admin.mapper.BaseUserMemberMapper;
import com.github.wxiaoqi.security.admin.vo.AppUserManageVo;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.vehicle.entity.SysRegion;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * app用户管理业务逻辑层
 *
 * @author Administrator
 */
@Service
@Slf4j
public class AppUserManageBiz extends BaseBiz<AppUserDetailMapper, AppUserDetail> {

    @Autowired
    private AppUserLoginMapper appUserLoginMapper;

    @Autowired
    private BaseUserMemberMapper baseUserMemberMapper;

    @Autowired
    private VehicleFeign vehicleFeign;

    /**
     * 根据条件查询
     *
     * @param appUserManageDTO 查询条件
     * @return
     */
    public PageInfo<AppUserManageVo> findAllByQuery(AppUserManageDTO appUserManageDTO) {
         PageHelper.startPage(appUserManageDTO.getPage(), appUserManageDTO.getLimit());
        List<AppUserManageVo> appUserManageVos = mapper.selectAppUserManage(appUserManageDTO);
        PageInfo<AppUserManageVo> pageInfo = PageInfo.of(appUserManageVos);
        if (pageInfo.getList()==null||pageInfo.getList().size()==0) {
            return  pageInfo;
        }
        return getAppUserManageVoPageInfo(pageInfo);
    }

    /**
     * 获取城市名并保存
     * @param pageInfo
     * @return
     */
    private PageInfo<AppUserManageVo> getAppUserManageVoPageInfo(PageInfo<AppUserManageVo> pageInfo) {
        List<Integer> citysCode = pageInfo.getList().parallelStream().map(AppUserManageVo::getCityCode).collect(Collectors.toList());
        HashSet<Integer> set = new HashSet<>();
        set.addAll(citysCode);
        ObjectRestResponse<List<SysRegion>> orr = vehicleFeign.getSysRegion(set);
        List<SysRegion> sysRegions = orr.getData();
        if (CollectionUtils.isNotEmpty(sysRegions)) {
            HashMap<Long, String> map = new HashMap<>();
            for (SysRegion sysRegion : sysRegions) {
                 map.put(sysRegion.getId(),sysRegion.getName());
            }
            for (AppUserManageVo appUserManageVo : pageInfo.getList()) {
                if(appUserManageVo.getCityCode() != null) {
                    Long cityCode = Long.valueOf(appUserManageVo.getCityCode());
                    String crtyName = map.get(cityCode);
                    appUserManageVo.setCityName(crtyName);
                }

            }
        }
        return pageInfo;
    }

    /**
     * 根据用公司账号权限和公司所在城市查询用户情况
     * @param appUserManageDTO
     * @return
     */
    public PageInfo<AppUserManageVo> findAllByQueryAndCity(AppUserManageDTO appUserManageDTO) {
        PageHelper.startPage(appUserManageDTO.getPage(), appUserManageDTO.getLimit());
        List<AppUserManageVo> appUserManageVos = mapper.selectAppUserManage(appUserManageDTO);
        if (CollectionUtils.isEmpty(appUserManageVos)) {
            return  new PageInfo<AppUserManageVo>();
        }
        Set<Integer> usSet = appUserManageDTO.getCitySet();
        List<AppUserManageVo> results = appUserManageVos.parallelStream().filter(us -> usSet.contains(us.getCityCode())).collect(Collectors.toList());
        PageInfo<AppUserManageVo> pageInfo = PageInfo.of(results);
        return getAppUserManageVoPageInfo(pageInfo);
    }

    /**
     * 禁用账户
     * @param id
     */

    @Transactional(rollbackFor =Exception.class)
    public void deleteAppUser(Integer id,Integer isDel) {
        AppUserLogin appUserLogin = new AppUserLogin();
        //修改为禁用并设置修改时间
        appUserLogin.setIsdel(isDel);
        appUserLogin.setUpdatetime(System.currentTimeMillis());
        Example example = new Example(AppUserLogin.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        appUserLoginMapper.updateByExampleSelective(appUserLogin, example);

        //设置
        AppUserDetail appUserDetail = new AppUserDetail();
        appUserDetail.setIsdel(isDel);
        appUserDetail.setUpdatetime(System.currentTimeMillis());
        Example detailExample = new Example(AppUserLogin.class);
        Example.Criteria detailCriteria = detailExample.createCriteria();
        criteria.andEqualTo("id", id);
        mapper.updateByExampleSelective(appUserDetail, detailCriteria);
    }

    /**
     * 查询一条
     * @param id
     * @return
     */
    public AppUserVo findOneById(Integer id) {
        return mapper.getUserInfo(id);
    }

    /**
     *保存
     * @param appUserVo
     */
    @Transactional(rollbackFor =Exception.class)
    public void save(AppUserVo appUserVo) {
        AppUserLogin appUserLogin = new AppUserLogin();
        AppUserDetail appUserDetail = new AppUserDetail();

        try {
            BeanUtilsBean.getInstance().copyProperties(appUserLogin, appUserVo);
            BeanUtilsBean.getInstance().copyProperties(appUserDetail, appUserVo);

            if (appUserVo.getUserid() == null || appUserVo.getUserid() == 0) {
                //设置登录用户信息
                appUserLogin.setIsdel(0);
                appUserLogin.setCreatetime(System.currentTimeMillis());
                appUserLogin.setCertificationStatus(0);
                appUserLogin.setStatus(0);
                //设置用户详情
                appUserDetail.setIsdel(0);
                if (appUserDetail.getIsMember() == null) {
                    appUserDetail.setIsMember(0);
                }

                appUserLoginMapper.insertSelective(appUserLogin);
                mapper.insertSelective(appUserDetail);

            } else {
                appUserLogin.setUpdatetime(System.currentTimeMillis());
                appUserDetail.setUpdatetime(System.currentTimeMillis());
                appUserLoginMapper.updateByPrimaryKeySelective(appUserLogin);
                mapper.updateByPrimaryKeySelective(appUserDetail);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

}
