package com.winsun.controller;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.HhrActivity;
import com.winsun.bean.HhrUser;
import com.winsun.bean.Partner;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.PartnerMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MapUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author: chancy
 * @Date: 2020/2/12 17:26
 */
@Slf4j
@RestController
@RequestMapping("/school/partner")
public class PartnerController extends BaseController {

	private static PartnerMapper partnerMapper;
	private static SysUserMapper sysUserMapper;
	private static HhrUserMapper hhrUserMapper;
	private static SchoolMapper schoolMapper;

	@Autowired
	public PartnerController(PartnerMapper partnerMapper,SysUserMapper sysUserMapper,HhrUserMapper hhrUserMapper,SchoolMapper schoolMapper) {
		PartnerController.partnerMapper = partnerMapper;
		PartnerController.sysUserMapper = sysUserMapper;
		PartnerController.hhrUserMapper = hhrUserMapper;
		PartnerController.schoolMapper = schoolMapper;
	}

	@Permission(menuname = "修改合伙人信息", value = "update", method = RequestMethod.POST)
	public ResponseData<String> updatePartner(@RequestParam("id") String id, @RequestParam("phone") String phone,
			@RequestParam("account") String account, @RequestParam("name") String name,
			@RequestParam("idCard") String idCard,@RequestParam("sex") String sex,
			@RequestParam("grade") String grade, @RequestParam("schoolId") String schoolId,
			@RequestParam("roleId") String roleId,@RequestParam("ysm") String ysm,
			@RequestParam(name = "position",required = false) String position,
			@RequestParam(name = "parentId", required = false) String parentId,
			@RequestParam(name = "parentIds", required = false) String parentIds
			) {
		int updateSysUse = partnerMapper.updateSysUser(phone, name, account, sex, id);
		int updateHhUser = partnerMapper.updateHhUser(ysm, grade, idCard,position,parentId,parentIds,id);
		int updateSchoolRef = partnerMapper.updateSchoolRef(schoolId, id);
		if (updateSysUse == 1 && updateHhUser == 1 && updateSchoolRef == 1) {
			return ResponseData.success("修改完毕！");
		}
		return ResponseData.error("修改失败");
	}

	@SuppressWarnings("unchecked")
	@Permission(menuname = "查询合伙人信息", value = "list", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> listPartner(@RequestParam("school") String school,
			@RequestParam("name") String name, @RequestParam("area") String area,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);

		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
//		wrapperHhr.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		List<HhrUser> hhrUserList = hhrUserMapper.selectList(wrapperHhr);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		List<SysUser> sysUserList = sysUserMapper.selectList(wrapperSys);
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
//		wrapperSchool.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);
		
		Map<String, Object> refMap = MapUtil.listToMap(partnerMapper.getSchoolRef(), "user_id", "school_id");
		List<Map<String, Object>> newList = new ArrayList<>();
		
//		List<Map<String, Object>> sysList = new ArrayList<>();
//		for(SysUser sysUser : sysUserList) {
//			sysList.add(BeanMap.create(sysUser));
//		}
		
		for(int i=0; i<sysUserList.size(); i++) {
			SysUser sysUser = sysUserList.get(i);
			String sysUserId = sysUser.getId();
			String schoolRefId = (String)refMap.get(sysUserId);
			
			Map<String, Object> dataMap = new HashMap<String, Object>();
			
			for(HhrUser hhrUser : hhrUserList) {
				String hhrUserId = hhrUser.getId();
				if(sysUserId.equals(hhrUserId)) {
					dataMap.put("grade",hhrUser.getGrade());
					dataMap.put("parentId",hhrUser.getParentId());
					dataMap.put("position",hhrUser.getPosition());
					dataMap.put("idCard",hhrUser.getIdCard());
					dataMap.put("ysm",hhrUser.getYsm());
					break;
				}
			}
			
			for(School schoolEntity : schoolList) {
				String schoolId = Integer.toString(schoolEntity.getId());
				if(null != schoolRefId && schoolRefId.equals(schoolId)) {
					dataMap.put("area",schoolEntity.getSubName());
					dataMap.put("school",schoolEntity.getSchoolName());
					dataMap.put("schoolId",schoolEntity.getId());
					dataMap.put("id", sysUserId);
					break;
				}
			}
			
			// 需要两个数据表都匹配到，才添加
			if(null != dataMap.get("id")) {
				dataMap.put("name", sysUser.getName());
				dataMap.put("account", sysUser.getAccount());
				dataMap.put("phone", sysUser.getPhone());
				dataMap.put("sex", sysUser.getSex());
				dataMap.put("status", sysUser.getStatus());
				dataMap.put("roleid", sysUser.getRoleid());
				
				newList.add(dataMap);
			}
		}
		
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageSize) {
			dataList = newList;
		}else {
			dataList = newList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(dataList);
		page.setTotal(newList.size());
		return ResponseData.success(page, "查询完毕！");
	}

	@Permission(menuname = "新增合伙人", value = "addPartner", method = RequestMethod.POST)
	public ResponseData<String> addPartner(@RequestParam("account") String account, @RequestParam("name") String name,
			@RequestParam("idCard") String idCard, @RequestParam("sex") String sex, @RequestParam("grade") String grade,
			@RequestParam("password") String password, @RequestParam("schoolId") String schoolId,
			@RequestParam("roleId") String roleId,@RequestParam("phone") String phone,
			@RequestParam(name = "position",required = false) String position,
			@RequestParam(name = "parentId", required = false) String parentId,
			@RequestParam(name = "parentIds", required = false) String parentIds){

		// String salt = Integer.toString((int)(Math.random()*100000));
		String salt = MD5Utils.getRandomString(5);
		password = MD5Utils.md5(password, salt);
		SysUser sysUser = new SysUser();
		sysUser.setAccount(account);
		sysUser.setName(name);
		sysUser.setPassword(password);
		sysUser.setSalt(salt);
		sysUser.setSex(sex);
		sysUser.setPhone(phone);
		sysUser.setRoleid(roleId);
		sysUser.setStatus("1");
		sysUser.setRoleid(roleId);
		sysUser.setCreatetime(new Date());
		sysUser.setUpdateTime(new Date());
		int num = sysUserMapper.insert(sysUser);
		
//		int num = partnerMapper.insertSysUser(account, name, password, salt, sex, phone, roleId, "1",
//				new Date(), new Date());

		if (num > 0) {
			List<Map<String,Object>> userList = partnerMapper.selectSysUser(account);
			Map<String, Object> userMap = userList.get(0);
			String userId = userMap.get("id").toString();
			HhrUser hhrUser = new HhrUser();
			
			hhrUser.setId(userId);
			hhrUser.setIdCard(idCard);
			hhrUser.setGrade(grade);
			hhrUser.setPosition(position);
			hhrUser.setParentId(parentId);
			hhrUser.setParentIds(parentIds);
			hhrUser.setYsm("1");
			int result =  hhrUserMapper.insert(hhrUser);

			//int result = partnerMapper.insertHhrUser(userId, idCard, grade, 1);

			if (result == 1) {
				partnerMapper.saveSchoolRef(userId, schoolId);
				return ResponseData.success("新增完毕！");
			}
		}

		return ResponseData.error("新增失败");
	}
	
	
	@Permission(menuname = "查询合伙人信息", value = "list1", method = RequestMethod.POST)
	public ResponseData<Page<Partner>> listPartner1(@RequestParam("school") String school,
			@RequestParam("name") String name, @RequestParam("area") String area,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<Partner> wrapper = new EntityWrapper<Partner>();
		wrapper.like(StringUtils.isNotBlank(school), "school", school, SqlLike.DEFAULT);
		wrapper.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		wrapper.eq(StringUtils.isNotBlank(area), "area", area);
		Page<Partner> page = new Page<>(pageIndex, pageSize);
		List<Partner> salespeople = partnerMapper.selectPage(page, wrapper);
		page.setRecords(salespeople);
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "获取学子公司职位下级成员", value = "getXzUserList", method = RequestMethod.POST)
	public ResponseData<List<HhrUser>> getXzUserList(@RequestParam("position") String position) {
		ShiroUser user = getShiroUser();
		if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
			return ResponseData.error("无数据权限");
		}

		// 查询县分列表
		Wrapper<HhrUser> wrapper = new EntityWrapper<HhrUser>();
		wrapper.setSqlSelect("id,parent_ids parentIds,position ")
					  .eq("position", position);
		List<HhrUser> list = hhrUserMapper.selectList(wrapper);
		
		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.setSqlSelect("id,name ");
		List<SysUser> sysList = sysUserMapper.selectList(wrapperSys);
		
		for(HhrUser hhrUser : list) {
			for(SysUser sysUser :sysList) {
				if(hhrUser.getId().equals(sysUser.getId())) {
					hhrUser.setName(sysUser.getName());
					break;
				}
			}
		}

		return ResponseData.success(list, "查询完毕！");
	}
	
	
}
