package com.winsun.controller;

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.auth.core.util.IOUtils;
import com.winsun.bean.HhrSupervisorSchool;
import com.winsun.bean.HhrUser;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.mapper.*;
import com.winsun.utils.DataAuthUtil;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.MD5Utils;
import com.winsun.utils.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @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;
	private static HhrSupervisorSchoolMapper hhrSupervisorSchoolMapper;

	@Autowired
	private DataAuthUtil dataAuthUtil;

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

	@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("password") String password, @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("schools") Integer[] schools,
											  	@RequestParam("subNames") String[] subNames, @RequestParam("subName") String subName,
												@RequestParam(name = "position",required = false) String position,
												@RequestParam(name = "parentId", required = false) String parentId,
												@RequestParam(name = "parentIds", required = false) String parentIds) {
		try{
			SysUser user = sysUserMapper.selectById(id);
			password = StringUtils.isNotBlank(password) ? MD5Utils.md5(password, user.getSalt()) : user.getPassword();
			parentId = null == parentId ? "" : parentId.replaceAll("null", "");
			parentIds = null == parentIds ? "" : parentIds.replaceAll("null", "");
			if (StringUtils.isBlank(ysm)||"null".equals(ysm)) {
				ysm = "1";
			}
			School school = schoolMapper.selectById(schoolId);
			if (StringUtils.isEmpty(subName) || !subName.equals(school.getSubName())){
				return ResponseData.error("修改失败");
			}
			int updateSysUse = partnerMapper.updateSysUser(phone, name, account, sex, password,roleId, id, subName);
			int updateHhUser = partnerMapper.updateHhUser(ysm, grade, idCard,position,parentId,parentIds,id);
			int updateSchoolRef = partnerMapper.updateSchoolRef(schoolId, id);

			// 获取县分下的学校
			if (subNames != null && subNames.length > 0) {
				Integer[] subNamesSchool = null;
				Wrapper<School> schoolWrapper = new EntityWrapper<>();
				schoolWrapper.in(subNames != null && subNames.length > 0,"sub_name",subNames);
				schoolWrapper.groupBy("school_name");
				List<School> list = schoolMapper.selectList(schoolWrapper);
				if (list != null && list.size() != 0) {
					subNamesSchool = new Integer[list.size()];
				}else{
					subNamesSchool = new Integer[0];
				}
				for(int i = 0; i < list.size(); ++i) {
					subNamesSchool[i] = list.get(i).getId();
				}
				Integer[] temp = schools;
				schools = new Integer[subNamesSchool.length + temp.length];
				System.arraycopy(temp, 0, schools, 0, temp.length);
				System.arraycopy(subNamesSchool, 0, schools, temp.length, subNamesSchool.length);
			}

			// 删除当前用户院校配置的  hhr_supervisor_school
			schoolMapper.deleteSupervisorSchoolByUserId(id);

			HhrSupervisorSchool hhrSupervisorSchool = null;
			// 更新当前院校配置
			for(Integer sId : schools) {
				hhrSupervisorSchool = new HhrSupervisorSchool();
				hhrSupervisorSchool.setUserId(Integer.parseInt(id));
				hhrSupervisorSchool.setSchool(sId + "");
				hhrSupervisorSchoolMapper.insert(hhrSupervisorSchool);
			}
			if (updateSysUse == 1 && updateHhUser == 1 && updateSchoolRef == 1) {
				return ResponseData.success("修改完毕！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return ResponseData.error("修改失败");
		}
		return ResponseData.error("修改失败");
	}

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

		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		wrapperHhr.eq(StringUtils.isNotBlank(id),"id",id);
		wrapperHhr.eq(StringUtils.isNotBlank(isActive), "is_active", isActive);
		if(StringUtils.isNotBlank(isUpload) && "1".equals(isUpload)) {
			wrapperHhr.isNotNull("idcard_img_url");
		}else if(StringUtils.isNotBlank(isUpload) && "0".equals(isUpload)) {
			wrapperHhr.isNull("idcard_img_url");
		}

		List<HhrUser> hhrUserList = hhrUserMapper.selectList(wrapperHhr);

		// 查询用户学校关联表赋值进去  只要id列表
		Wrapper<HhrSupervisorSchool> wrapper = new EntityWrapper<>();
		wrapper.setSqlSelect("user_id as userId, group_concat(school) as school");
		wrapper.groupBy("user_id");
		List<HhrSupervisorSchool> hhrSupervisorSchools = hhrSupervisorSchoolMapper.selectList(wrapper);

		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.eq(StringUtils.isNotBlank(id),"id",id);
		wrapperSys.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		wrapperSys.eq(StringUtils.isNotBlank(roleid), "roleid", roleid);
		wrapperSys.eq(StringUtils.isNotBlank(account), "account", account);
		wrapperSys.eq(StringUtils.isNotBlank(status), "status", status);
		wrapperSys.notIn("status", "3,4");
		List<SysUser> sysUserList = sysUserMapper.selectList(wrapperSys);

		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.eq(StringUtils.isNotBlank(substName), "sub_name", substName);
		wrapperSchool.eq(StringUtils.isNotBlank(school), "id", school);
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);

		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		List<Map<String, Object>> newList = new ArrayList<>();
		Map<String, Object> roleMap = MapUtil.listToMap(partnerMapper.roleList(), "id", "name");

//		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>();
			Integer fxsCount = 0;
			// 添加合伙人基础数据
			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());
					dataMap.put("isActive",hhrUser.getIsActive());
					dataMap.put("idCardImgUrl",hhrUser.getIdcardImgUrl());
					dataMap.put("studentImgUrl",hhrUser.getStudentImgUrl());
					if(StringUtils.isNotBlank(hhrUser.getFxs())){
						dataMap.put("fxs",hhrUser.getFxs());
						fxsCount = hhrUser.getFxs().length() == 0?0:hhrUser.getFxs().split(",").length;
						dataMap.put("fxsCount",fxsCount);
					}else {
						dataMap.put("fxs","");
						dataMap.put("fxsCount",fxsCount);
					}
					dataMap.put("hasHhr","0");
					break;
				}
			}

			// 添加院校配置数据
			for(HhrSupervisorSchool hhrSupervisorSchool : hhrSupervisorSchools) {
				if (sysUserId.equals(hhrSupervisorSchool.getUserId() + "")) {
					dataMap.put("schools", hhrSupervisorSchool.getSchool());
					break;
				}
			}

			// 添加用户所属学校数据
			for(School schoolEntity : schoolList) {
				String schoolId = Integer.toString(schoolEntity.getId());
				if(null != schoolRefId && schoolRefId.equals(schoolId)) {
					dataMap.put("substName",schoolEntity.getSubName());
					dataMap.put("school",schoolEntity.getSchoolName());
					dataMap.put("schoolId",schoolEntity.getId());
					dataMap.put("id", sysUserId);
					break;
				}
			}


			// 需要两个数据表都匹配到，才添加  添加系统用户数据
			if(null != dataMap.get("id") && null != dataMap.get("hasHhr")) {
				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());
				dataMap.put("roleName", roleMap.get(sysUser.getRoleid()));
				newList.add(dataMap);
			}
		}
		// 数据权限控制
		newList = dataAuthUtil.authDeal(newList, user);
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageIndex*pageSize) {
			dataList = newList.subList((pageIndex-1)*pageSize, newList.size());
		}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){

		Wrapper<SysUser> userWrapper = new EntityWrapper<SysUser>();
		userWrapper.eq("account", account);
		userWrapper.ne("status", "3");
		List<SysUser> accountList = sysUserMapper.selectList(userWrapper);
		if(accountList.size() > 0) {
			return ResponseData.error("账号已存在");
		}

		Wrapper<HhrUser> hhrWrapper = new EntityWrapper<HhrUser>();
		hhrWrapper.eq("id_card", idCard);
		List<HhrUser> hhrList = hhrUserMapper.selectList(hhrWrapper);
		if(hhrList.size() > 0) {
			for(HhrUser hhrUser : hhrList) {
				SysUser sysUser = sysUserMapper.selectById(hhrUser.getId());
				if(!sysUser.getStatus().equals("3")) {
					// 判断剔除已删除的用户
					return ResponseData.error("身份证已存在");
				}
			}
		}



		// 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 = "pushFxyList", method = RequestMethod.POST)
	public ResponseData pushFxyList(@RequestParam("id") String id,@RequestParam("fxy") String fxy) {
		Wrapper<HhrUser> wrapper = new EntityWrapper<>();
		wrapper.eq("id",id);
		if("".equals(id)){
			return ResponseData.error("参数出错");
		}
		HhrUser hhrUser = new HhrUser();
		hhrUser.setId(id);
		hhrUser.setFxs(fxy);
		try {
			hhrUserMapper.updateById(hhrUser);
		}catch (Exception e){
			e.printStackTrace();
			return ResponseData.error("参数出错");
		}
		return ResponseData.success("更新完毕！");
	}
	@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, "查询完毕！");
	}

	@Permission(menuname = "获取角色清单", value = "roleList", method = RequestMethod.POST)
	public ResponseData<List<Map<String, Object>>> roleList() {
		List<Map<String, Object>> list = partnerMapper.roleList();
		ShiroUser user = getShiroUser();
		List<Map<String, Object>> resultList = dataAuthUtil.roleAuth(list, user);

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

	@Permission(menuname = "导出合伙人信息", value = "exportUserList", method = RequestMethod.POST)
	public void exportUserList(@RequestParam("id") String id,
		   	@RequestParam("school") String school,
			@RequestParam("name") String name, @RequestParam("substName") String substName,
			@RequestParam("account") String account, @RequestParam("roleid") String roleid,
			@RequestParam("isActive") String isActive,@RequestParam("isUpload") String isUpload,
			@RequestParam("status") String status) {
		ShiroUser user = getShiroUser();

		Wrapper<HhrUser> wrapperHhr = new EntityWrapper<HhrUser>();
		wrapperHhr.setSqlSelect(" id,grade,parent_id parentId,position,id_card idCard,"
				+ " (case when is_active = 1 then '活跃' when is_active = 0 then '不活跃' else '' end) isActive  ");
		wrapperHhr.eq(StringUtils.isNotBlank(id), "id", id);
		wrapperHhr.eq(StringUtils.isNotBlank(isActive), "is_active", isActive);
		if(StringUtils.isNotBlank(isUpload) && "1".equals(isUpload)) {
			wrapperHhr.isNotNull("idcard_img_url");
		}else if(StringUtils.isNotBlank(isUpload) && "0".equals(isUpload)) {
			wrapperHhr.isNull("idcard_img_url");
		}

		List<Map<String, Object>> hhrUserList = hhrUserMapper.selectMaps(wrapperHhr);

		Wrapper<SysUser> wrapperSys = new EntityWrapper<SysUser>();
		wrapperSys.setSqlSelect(" id,name,account,roleid,phone,(case status when 1 then '启用' when 2 then '冻结' else status end) status,"
				+ " (case sex when '1' then '男' when '2' then '女' else sex end) sex  ");
		wrapperSys.eq(StringUtils.isNotBlank(id), "id", id);
		wrapperSys.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		wrapperSys.eq(StringUtils.isNotBlank(roleid), "roleid", roleid);
		wrapperSys.eq(StringUtils.isNotBlank(account), "account", account);
		wrapperSys.eq(StringUtils.isNotBlank(status), "status", status);
		wrapperSys.notIn("status");
		List<SysUser> sysUserList = sysUserMapper.selectList(wrapperSys);

		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.eq(StringUtils.isNotBlank(substName), "sub_name", substName);
		wrapperSchool.eq(StringUtils.isNotBlank(school), "id", school);
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);

		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		List<Map<String, Object>> newList = new ArrayList<>();
		Map<String, Object> roleMap = MapUtil.listToMap(partnerMapper.roleList(), "id", "name");

//		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(Map<String, Object> hhrMap : hhrUserList) {
				String hhrUserId = hhrMap.get("id").toString();
				if(sysUserId.equals(hhrUserId)) {
					dataMap.put("grade", hhrMap.get("grade"));
					dataMap.put("parentId", hhrMap.get("parentId"));
					dataMap.put("position", hhrMap.get("position"));
					dataMap.put("idCard", hhrMap.get("idCard"));
					dataMap.put("ysm", hhrMap.get("ysm"));
					dataMap.put("isActive",hhrMap.get("isActive"));
					dataMap.put("idCardImgUrl", hhrMap.get("idCardImgUrl"));
					dataMap.put("studentImgUrl", hhrMap.get("studentImgUrl"));
					dataMap.put("hasHhr","0");
					break;
				}
			}

			for(School schoolEntity : schoolList) {
				String schoolId = Integer.toString(schoolEntity.getId());
				if(null != schoolRefId && schoolRefId.equals(schoolId)) {
					dataMap.put("substName",schoolEntity.getSubName());
					dataMap.put("school",schoolEntity.getSchoolName());
					dataMap.put("schoolId",schoolEntity.getId());
					dataMap.put("id", sysUserId);
					break;
				}
			}

			// 需要两个数据表都匹配到，才添加
			if(null != dataMap.get("id") && null != dataMap.get("hasHhr")) {
				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());
				dataMap.put("roleName", roleMap.get(sysUser.getRoleid()));

				newList.add(dataMap);
			}
		}

		// 数据权限控制
		newList = dataAuthUtil.authDeal(newList, user);

        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.hhrUserExcel("用户清单"), newList);
        try {

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }

	@Permission(menuname = "删除用户", value = "deleteUser", method = RequestMethod.POST)
	public ResponseData<Object> deleteUser(@Param("id") String id) {
		SysUser sysUser = new SysUser();
		sysUser.setId(id);
		sysUser.setStatus("3");

		int num = sysUserMapper.updateById(sysUser);
		if(num > 0) {
			return ResponseData.success("删除成功");
		}

		return ResponseData.success("删除失败");
	}
}
