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.bean.*;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.mapper.UserSchoolMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
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 java.util.*;

/**
 * 〈新用户审核〉
 *
 * @author PXL
 * @create 2020/5/20 10:19
 */
@Slf4j
@RestController
@RequestMapping("/newUser")
public class NewUserController extends BaseController {

    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private UserSchoolMapper userSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private HhrUserMapper hhrUserMapper;
    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 新用户审核删除
     * @param id 需要删除的id
     * @return
     */
    @Permission(menuname = "删除正则信息", value = "delete", method = RequestMethod.POST)
    public ResponseData<String> deleteProduct(@RequestParam(name="id", required = false) String id,@RequestParam(name="isdel", required = false) String isdel) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            return ResponseData.error("无数据权限");
        }
        //Wrapper wrapper = new EntityWrapper<>();
        //wrapper.eq(StringUtils.isNotBlank(id),"id", id);
        //Map<String, Object> dataMapping = new HashMap<>();
        //dataMapping.put("is_del", isdel);
        //lzKpiMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if(StringUtils.isNotBlank(id)){
            /*lzWageMpapper.deleteById(id);*/
            return ResponseData.success("操作成功！");
        }
        return ResponseData.error("删除id不能为空!");
    }

    /**
     * 修改新用户审核状态
     * @param ids
     * @param status
     * @return
     */
    @Permission(menuname = "修改新用户审核信息", value = "update", method = RequestMethod.POST)
    public ResponseData<String> updateProduct(@RequestParam("ids") String ids,@RequestParam("status") String status) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "县分管理员（订单）"))) {
            return ResponseData.error("无数据权限");
        }
        List<String> list1 = Arrays.asList(ids.split(",")); //[a, b, c]
        List<Integer> list = new ArrayList<>();
        for (String s : list1) {
            list.add(Integer.valueOf(s));
        }
        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        SysUser sysUser = new SysUser();
        sysUser.setStatus(status);
        wrapper.in("id", list);
        sysUserMapper.update(sysUser,wrapper);
        return ResponseData.success("修改成功！");
    }

    /**
     *
     * @param account
     * @param name
     * @param status
     * @param substName
     * @param salesSchool
     * @param createtime
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Permission(menuname = "查询新用户审核信息", value = "list", method = RequestMethod.POST)
    public ResponseData<Page<Map<String,Object>>> listProduct(
            @RequestParam(name = "account", required = false) String account,
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "substName", required = false) String substName,
            @RequestParam(name = "salesSchool", required = false) String salesSchool,
            @RequestParam(name = "createtime", required = false) String createtime,
            @RequestParam(name = "pageNo") int pageNo,
            @RequestParam(name = "pageSize") int pageSize) {
        ShiroUser user = getShiroUser();
        if (!user.getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员", "县分管理员（订单）"))) {
            return ResponseData.error("无数据权限");
        }
        Page<Map<String,Object>> page = new Page<>(pageNo, pageSize);
        List<Map<String,Object>> list = new ArrayList<>();


        Wrapper<SysUser> sysUserWrapper = new EntityWrapper<>();
        sysUserWrapper.like(StringUtils.isNotBlank(account),"account",account, SqlLike.DEFAULT);
        sysUserWrapper.like(StringUtils.isNotBlank(name),"name",name, SqlLike.DEFAULT);
        sysUserWrapper.eq("status",'4');
        if(StringUtils.isNotBlank(createtime)){
            String[] dates = createtime.split("\\,");
            if(!createtime.equals(",")){
                sysUserWrapper.between("createtime",dates[0],dates[1]);
            }
        }
        List<SysUser> sysUserList = sysUserMapper.selectList(sysUserWrapper);
        if(sysUserList.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        List<String> userIds0 = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            userIds0.add(sysUser.getId());
        }
        Wrapper<UserSchool> userSchoolWrapper = new EntityWrapper<>();
        userSchoolWrapper.in("user_id",userIds0);
        userSchoolWrapper.groupBy("user_id");
        List<UserSchool> userSchools = userSchoolMapper.selectList(userSchoolWrapper);
        if(userSchools.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        List<String> schoolIds = new ArrayList<>();
        for (UserSchool userSchool : userSchools) {
            schoolIds.add(userSchool.getSchoolId());
        }
        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.in("id",schoolIds);
        schoolWrapper.eq(StringUtils.isNotBlank(substName),"sub_name",substName);
        schoolWrapper.eq(StringUtils.isNotBlank(salesSchool),"school_name",salesSchool);
        List<School> schoolList = schoolMapper.selectList(schoolWrapper);
        if(schoolList.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        List<Integer> schoolIds0 = new ArrayList<>();
        List<String> userIds = new ArrayList<>();
        for (School school : schoolList) {
            schoolIds0.add(school.getId());
        }
        for (UserSchool us : userSchools) {
            for (Integer s : schoolIds0) {
                if(us.getSchoolId().equals(s.toString())){
                    userIds.add(us.getUserId());
                }
            }
        }

        Wrapper<HhrUser> hhrUserWrapper = new EntityWrapper<>();
        hhrUserWrapper.in("id",userIds);
        List<HhrUser> hhrUserList = hhrUserMapper.selectList(hhrUserWrapper);
        if(hhrUserList.size()==0){
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return ResponseData.success(page);
        }
        /*List<String> userIds = new ArrayList<>();
        for (HhrUser hhrUser : hhrUserList) {
            userIds.add(hhrUser.getId());
        }*/

        for (String id : userIds) {
            Map<String,Object> objectMap = new HashMap<>();
            objectMap.put("id",id);
            for (UserSchool userSchool : userSchools) {
                if(userSchool.getUserId().equals(id)){
                    Wrapper<School> wrapper = new EntityWrapper<>();
                    wrapper.eq("id",userSchool.getSchoolId());
                    School school = schoolMapper.selectList(wrapper).get(0);
                    objectMap.put("subName",school.getSubName());
                    objectMap.put("schoolName",school.getSchoolName());
                    break;
                }
            }
            for (SysUser sysUser : sysUserList) {
                if(sysUser.getId().equals(id)){
                    objectMap.put("name",sysUser.getPhone());
                    objectMap.put("phone",sysUser.getPhone());
                    objectMap.put("sex",sysUser.getSex());
                    objectMap.put("status",sysUser.getStatus());
                    objectMap.put("createtime",sysUser.getCreatetime());
                    objectMap.put("updateTime",sysUser.getUpdateTime());

                    break;
                }
            }
            for (HhrUser hhrUser : hhrUserList) {
                if(hhrUser.getId().equals(id)){
                    objectMap.put("idCard",hhrUser.getIdCard());
                    objectMap.put("grade",hhrUser.getGrade());
                    objectMap.put("idcardImgUrl",hhrUser.getIdcardImgUrl());
                    objectMap.put("studentImgUrl",hhrUser.getStudentImgUrl());
                    objectMap.put("position",hhrUser.getPosition());
                    break;
                }
            }
            list.add(objectMap);
        }

        List<Map<String,Object>> dataList = new ArrayList<>();
        if(list.size() < pageSize) {
            dataList = list;
        }else {
            dataList = list.subList((pageNo-1)*pageSize, pageNo*pageSize);
        }
        page.setRecords(dataList);
        return ResponseData.success(page, "查询成功！");
    }

    /**
     *
     * @return
     */
    @Permission(menuname = "初始用户信息", value = "initUsers", method = RequestMethod.POST)
    public ResponseData<List<SysUser>> initUsers(){
        List<String> list = new ArrayList<>();
        list.add("241");
        list.add("242");
        Wrapper<SysUser> hhrUserWrapper = new EntityWrapper<>();
        hhrUserWrapper.in("roleid",list);
        List<SysUser> hhrUserList = sysUserMapper.selectList(hhrUserWrapper);
        return ResponseData.success(hhrUserList);
    }

    /**
     * 多个地方公用初始县分
     * @param substName
     * @return
     */
    @Permission(menuname = "初始县分", value = "initSubstName", method = RequestMethod.POST)
    public ResponseData<List<School>> initSubstName(@RequestParam(name = "substName", required = false) String substName){
        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.setSqlSelect("sub_name subName,school_name schoolName");
        schoolWrapper.groupBy("sub_name");
        schoolWrapper.orderBy("sub_name",false);
        List<School> list = schoolMapper.selectList(schoolWrapper);

        return ResponseData.success(list);
    }
    /**
     * 多个地方公用初始学校
     * @param substName
     * @return
     */
    @Permission(menuname = "初始学校", value = "getSchoolNames", method = RequestMethod.POST)
    public ResponseData<List<School>> getSchoolNames(@RequestParam(name = "substName", required = false) String substName){
        Wrapper<School> schoolWrapper = new EntityWrapper<>();
        schoolWrapper.eq(StringUtils.isNotBlank(substName),"sub_name",substName);
        schoolWrapper.groupBy("school_name");
        List<School> list = schoolMapper.selectList(schoolWrapper);
        return ResponseData.success(list);
    }
}
