package io.renren.modules.admin.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.admin.dao.MemberDao;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.service.MemberService;
import io.renren.modules.admin.entity.EmployeeEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.EmployeeService;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private AttendersService attendersService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");
        // System.out.println(key);
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
                .like(StringUtils.isNotBlank(key),"username", key)
                .or()
                .like(StringUtils.isNotBlank(key),"truename", key)
        );

        List<MemberEntity> theList = page.getRecords();

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (MemberEntity member : theList) {
            Map<String, Object> mMap = new HashMap<String, Object>();
            Long memberId = member.getId();
            mMap.put("id", memberId);
            mMap.put("truename", member.getTruename());
            mMap.put("username", member.getUsername());
            mMap.put("organization", member.getOrganization());
            mMap.put("position", member.getPosition());
            mMap.put("phone", member.getPhone());
            mMap.put("email", member.getEmail());
            mMap.put("createTime", member.getCreateTime());
            mMap.put("isCheck", member.getIsCheck());
            Long servicerId = member.getServicerId();
            if (servicerId != 0) {
                Map<String, Object> employeeMap = employeeService.getMap(
                    new QueryWrapper<EmployeeEntity>().eq("id", servicerId));
                    System.out.println(employeeMap);
                    if (employeeMap != null && employeeMap.containsKey("truename")) {
                        mMap.put("servicerName", employeeMap.get("truename"));
                    } else {
                        mMap.put("servicerName", "");
                    }
            } else {
                mMap.put("servicerName", "");
            }
            List<Map<String, Object>> meetingList = attendersService.getMeetingListByMemberId(memberId);
            int meetingCounts = meetingList.size();
            if (meetingCounts > 0) {
                Map<String, Object> meetingInfo = meetingList.get(meetingCounts - 1);
                mMap.put("meetingName", meetingInfo.get("name_cn"));
            } else {
                mMap.put("meetingName", "");
            }
            mMap.put("meetingCounts", meetingCounts);
            list.add(mMap);
        }

        return new PageUtils(list, (int)page.getTotal(), (int)page.getSize(), (int)page.getCurrent());
    }

    @Override
	@Transactional
    public void saveMember(MemberEntity member){
        member.setCreateTime(new Date());
        //sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		member.setPassword(new Sha256Hash(member.getPassword(), salt).toHex());
		member.setSalt(salt);
		this.save(member); 
    }

    @Override
	@Transactional
    public void update(MemberEntity member) {
        
        member.setUsername(null);
        if(StringUtils.isBlank(member.getPassword())){
			member.setPassword(null);
		}else{
			member.setPassword(new Sha256Hash(member.getPassword(), member.getSalt()).toHex());
		}

        this.updateById(member);
    }

    @Override
    public int updateStatus(Long id, Integer isCheck) {
        int itemp = baseMapper.updateStatus(id, isCheck);
        return itemp;
        // @Update("update member set is_check=#{is_check}  where id = #{id}")
    }
}
