package io.hmit.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.hmit.common.service.impl.CrudServiceImpl;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.modules.area.dto.AreaDTO;
import io.hmit.modules.area.service.AreaService;
import io.hmit.modules.committee.dto.CommitteeDTO;
import io.hmit.modules.committee.service.CommitteeService;
import io.hmit.modules.meeting.service.WlMeetingStaffService;
import io.hmit.modules.user.dao.UserDao;
import io.hmit.modules.user.dto.AreaUserDTO;
import io.hmit.modules.user.dto.CommitteeUserDTO;
import io.hmit.modules.user.dto.UserDTO;
import io.hmit.modules.user.entity.UserEntity;
import io.hmit.modules.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息表（关注公众号的用户）
 *
 * @author syf syf0412@qq.com
 * @since 1.0.0 2020-12-25
 */
@Service
public class UserServiceImpl extends CrudServiceImpl<UserDao, UserEntity, UserDTO> implements UserService {

    @Autowired
    private CommitteeService committeeService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private WlMeetingStaffService wlMeetingStaffService;

    @Override
    public QueryWrapper<UserEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String mobile = (String)params.get("mobile");
        String area = "";
        if(params.get("area") != null){
            area = params.get("area").toString();
        }
        String committee = "";
        if(params.get("committee") != null){
            committee = params.get("committee").toString();
        }
        String company = (String)params.get("company");
        String name = (String)params.get("name");
        String check = (String)params.get("check");
        String groupByCommittee = (String)params.get("groupByCommittee");
        String groupByArea = (String)params.get("groupByArea");
        String member = (String)params.get("member");

        QueryWrapper<UserEntity> wrapper = new QueryWrapper<UserEntity>()
                .eq(StringUtils.isNotBlank(id), "id", id)
                .like(StringUtils.isNotBlank(mobile), "mobile", mobile)
                .eq(StringUtils.isNotBlank(area), "area_id", area)
                .like(StringUtils.isNotBlank(company), "company", company)
                .like(StringUtils.isNotBlank(name), "name", name)
                .eq(StringUtils.isNotBlank(committee), "committee_id", committee)
                .eq(StringUtils.isNotBlank(check),"if_check",check)
                .eq(StringUtils.isNotBlank(member),"member",member)
                .groupBy(StringUtils.isNotBlank(groupByCommittee),"committee_id")
                .groupBy(StringUtils.isNotBlank(groupByArea),"area_id");


        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        Map<String, Object> params = new HashMap<>();
        for (Long id : ids) {
            params.put("userId",id);
            wlMeetingStaffService.list(params).forEach(wlMeetingStaffDTO -> {
                wlMeetingStaffService.deleteById(wlMeetingStaffDTO.getId());
            });
        }
        super.delete(ids);
    }


    @Override
    public List<CommitteeUserDTO> getCommitteeUserList(Map<String, Object> params) {

        List<CommitteeUserDTO> committeeUserDTOList = new ArrayList<>();
        //根据查询条件查找出部分满足条件的会员信息，并按委员会分组（重点是得到满足条件的会员的委员会ID）
        params.put("groupByCommittee","committee_id");
        params.put("member","1");

        //遍历查询出的会员信息
        list(params).forEach(userDTO -> {
            String name = (String)params.get("name");

            //构造符合信息的某委员会下的UserInfoList
            List<UserDTO> userDTOList = ConvertUtils.sourceToTarget(baseDao.selectList(new QueryWrapper<UserEntity>()
                    .eq("committee_id", userDTO.getCommitteeId())
                    .eq("member",1)
                    .like(StringUtils.isNotBlank(name),"name", name)),UserDTO.class) ;

            //根据委员会ID查询出委员会Name 对DTO进行填充
            if(userDTO.getCommitteeId()!= null){
                userDTO.setCommitteeName(committeeService.get(userDTO.getCommitteeId()).getName());
                //调用封装的方法组成会员和委员会的层级关系并返回
                committeeUserDTOList.add(new CommitteeUserDTO().assembleCommitteeUser(userDTO.getCommitteeId(),userDTO.getCommitteeName(),userDTOList));
                return;
            }
        });

        return committeeUserDTOList;
    }

    @Override
    public List<AreaUserDTO> getAreaUserList(Map<String, Object> params) {
        List<AreaUserDTO> areaUserDTO = new ArrayList<>();
        //根据查询条件查找出部分满足条件的会员信息，并按地区分组（重点是得到满足条件的会员的地区ID）
        params.put("groupByArea","area_id");
        params.put("member","1");

        //遍历查询出的会员信息
        list(params).forEach(userDTO -> {
            String name = (String)params.get("name");

            //构造符合信息的某地区下的UserInfoList
            List<UserDTO> userDTOList = ConvertUtils.sourceToTarget(
                    baseDao.selectList(new QueryWrapper<UserEntity>()
                    .eq("area_id", userDTO.getAreaId()).eq("member",1)
                    .like(StringUtils.isNotBlank(name),"name",name)),UserDTO.class) ;

            //根据地区ID查询出地区Name 对DTO进行填充
            if(userDTO.getAreaId()!= null){
                userDTO.setAreaName(areaService.get(userDTO.getAreaId()).getName());
                //调用封装的方法组成会员和地区的层级关系并返回
                areaUserDTO.add(new AreaUserDTO().assembleAreaUser(userDTO.getAreaId(),userDTO.getAreaName(),userDTOList));
                return;
            }
        });

        return areaUserDTO;
    }
}
