package com.ruoyi.system.service.grid;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.zqt.ZQTHttpHelper;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridUserInfo;
import com.ruoyi.system.mapper.system.SysUserRoleMapper;
import com.ruoyi.system.service.system.ISysRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: hxc
 * @Date: 2019/3/7 0007 14:30
 * @Description:网格用户关联信息
 */
@Component
public class GridRegionUserFacadeService {

    @Autowired
    private GridRegionUserService gridRegionUserService;
    @Autowired
    private GridRegionService gridRegionService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private GridItemDailyService gridItemDailyService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${app.mgrdata.url}")
    private String appMgrdataUrl;

    public String commit(GridRegionUser body, String method) {
        try {
            AjaxResult result = new AjaxResult();

            Method methodCheck = null;
            try {
                methodCheck = this.getClass().getMethod(method + "Pre", body.getClass(), result.getClass());
            } catch (Exception e) {
                methodCheck = null;
            }
            if (null != methodCheck) {
                Object ret = methodCheck.invoke(this, body, result);
                if ((ret instanceof Boolean) && !(boolean) ret) {
                    return JSON.toJSONString(result);
                }
            }

            Method methodCommit = null;
            try {
                methodCommit = this.getClass().getMethod(method, body.getClass(), result.getClass());
            } catch (Exception e) {
                methodCommit = null;
            }
            if (null == methodCommit) {
                return JSON.toJSONString(AjaxResult.error(600, "方法未找到:" + method));
            }

            methodCommit.invoke(this, body, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    public boolean insertPre(GridRegionUser body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }
        if (!StringUtils.isNotEmpty(body.getWgId())) {
            result.buildError(400, "没有选择对应的网格");
            return false;
        }
        //判断记录是否存在
        GridRegionUserExample example = new GridRegionUserExample();
        example.createCriteria().andUserIdEqualTo(body.getUserId()).andWgIdEqualTo(body.getWgId());
        int count = gridRegionUserService.countByExample(example);
        if (count > 0) {
            result.buildError(600, "该用户已存在网格中,请重新添加");
            return false;
        }
        return true;
    }

    public void insert(GridRegionUser body, AjaxResult result) {
        String id = UUID.randomUUID().toString();

        GridRegionUser gridRegion = new GridRegionUser();
        gridRegion.setId(id);
        gridRegion.setUserId(body.getUserId());
        gridRegion.setWgId(body.getWgId());
        gridRegion.setIsValid("1");
        gridRegion.setYlzd1(body.getYlzd1());//姓名
        gridRegion.setYlzd2(body.getYlzd2());//网格类型
        gridRegion.setCreateBy(body.getCreateBy());
        gridRegion.setCreateTime(body.getCreateTime());
        gridRegion.setUpdateBy(body.getUpdateBy());
        gridRegion.setUpdateTime(body.getUpdateTime());
        int ret = gridRegionUserService.insertSelective(gridRegion);
        if (ret > 0) {
            result.buildSuccess("success", "id");
        } else {
            result.buildError(600, "新增失败");
        }
    }

    public boolean deletePre(GridRegionUser body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }

        if (!itemIsUUID(body.getId())) {
            result.buildError(400, "body里的id为空或非法");
            return false;
        }
        return true;
    }

    public void delete(GridRegionUser body, AjaxResult result) {
        GridRegionUser bean = get(body.getId(), null);
        if (null == bean) {
            result.buildError(400, "找不到该角色");
            return;
        }
        // 防止数据残留
        int ret = gridRegionUserService.deleteByStringPrimaryKey(body.getId());
        if (ret > 0) {
            result.buildSuccess("success", "1");
        } else {
            result.buildError(600, "删除失败");
        }
    }


    public GridRegionUser get(String id, GridRegionUser regionUser) {
        if (null == regionUser) {
            if (StringUtils.isNotEmpty(id)) {
                regionUser = gridRegionUserService.selectByPrimaryKey(id);
            }
            if (null == regionUser) {
                return null;
            }
        }

        return regionUser;
    }

    public List<GridRegionUser> get(GridRegionUserExample example, GridRegionUser regionUser) {
        if (null == regionUser) {
            List<GridRegionUser> regionUsers = gridRegionUserService.selectByExample(example);
            return regionUsers;
        }
        return null;
    }

    public void getRoles(String ylzd1, String ylzd2, String wgId, Integer pageNum, Integer pageSize, AjaxResult result) {
        if (null == pageNum || pageNum <= 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        ZQTPageModel<GridUserInfo> appPageModel = new ZQTPageModel<>();
        appPageModel.setRecordCount(0);
        appPageModel.setPageCount(0);
        appPageModel.setCurPage(pageNum);
        appPageModel.setItemList(new ArrayList<>());

        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(ylzd2)) {
            criteria.andYlzd2EqualTo(ylzd2);
        }
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgId)) {
            criteria.andWgIdEqualTo(wgId);
        }
        if (StringUtils.isNotEmpty(ylzd1)) {
            criteria.andYlzd1Like("%" + ylzd1 + "%");
        }
        int count = gridRegionUserService.countByExample(example);
        if (count <= 0) {
            result.buildSuccess("success", appPageModel);
            return;
        }
        example.setOrderByClause("update_time desc ");
        List<GridRegionUser> regionUsers = gridRegionUserService.selectByExampleForStartPage(example, pageNum, pageSize);
        if (null == regionUsers || regionUsers.isEmpty()) {
            result.buildSuccess("success", appPageModel);
            return;
        }
        List<GridUserInfo> userList = new ArrayList<GridUserInfo>();
        try {
            for (GridRegionUser regionUser : regionUsers) {
                GridUserInfo userInfo = new GridUserInfo();

                GridRegionExample regionExample = new GridRegionExample();
                regionExample.createCriteria().andWgCodeEqualTo(regionUser.getWgId());
                List<GridRegion> regionList = gridRegionService.selectByExample(regionExample);
                userInfo.setId(regionUser.getId());
                userInfo.setWgId(regionUser.getWgId());
                userInfo.setPic(regionUser.getYlzd3());
                userInfo.setIsDy(regionUser.getYlzd4());
                userInfo.setSbh(regionUser.getYlzd5());
                userInfo.setWgName(regionList == null ? "" : regionList.get(0).getWgName());

                SysUser sysUser = sysUserService.selectUserById(regionUser.getUserId());
                if (sysUser != null) {
                    userInfo.setEmail(sysUser.getEmail());
                    userInfo.setPhone(sysUser.getPhonenumber());
                    userInfo.setRealName(sysUser.getNickName());
                    userInfo.setUserId(sysUser.getUserId());
                    userInfo.setUserName(sysUser.getUserName());
                }
                userList.add(userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        appPageModel.setCurPage(pageNum);
        appPageModel.setRecordCount(count);
        appPageModel.setPageCount((long) Math.ceil(1.0 * count / pageSize));
        appPageModel.setItemList(userList);
        result.buildSuccess("success", appPageModel);
        return;
    }

    public boolean updatePre(GridRegionUser body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }

        return true;
    }

    public void update(GridRegionUser body, AjaxResult result) {
        String id = body.getId();
        GridRegionUser bean = get(id, null);
        if (null == bean) {
            result.buildError(400, "找不到待更新项");
            return;
        }
        GridRegionUserExample example = new GridRegionUserExample();
        example.createCriteria().andIdEqualTo(id);
        List<GridRegionUser> userList = gridRegionUserService.selectByExample(example);
        try {
            if (userList.size() > 1) {
                for (GridRegionUser user : userList) {
                    BeanUtils.copyProperties(user, body);
                    gridRegionUserService.updateByPrimaryKeySelective(body);
                }
            } else {
                gridRegionUserService.updateByPrimaryKeySelective(body);
            }
            result.buildSuccess("success", "1");
        } catch (Exception e) {
            result.buildError(600, "更新失败");
            e.printStackTrace();
        }
        return;
    }

    private boolean itemIsUUID(String item) {
        if (StringUtils.isEmpty(item)) {
            return false;
        }
        return item.matches("(\\w{8}(-\\w{4}){3}-\\w{12}?)");
    }

    public void getRegionUserByExample(GridRegionUserExample example, AjaxResult result) {
        int count = gridRegionUserService.countByExample(example);
        List<GridRegionUser> regionList = gridRegionUserService.selectByExample(example);
        if (count <= 0) {
            result.buildSuccess("success", regionList);
            return;
        }
        List<String> codeList = regionList.stream().map(GridRegionUser::getWgId).collect(Collectors.toList());
        GridRegionExample regionExample = new GridRegionExample();
        regionExample.createCriteria().andWgCodeIn(codeList);
        List<GridRegion> gridRegionList = gridRegionService.selectByExample(regionExample);
        for (GridRegionUser regionUser : regionList) {
            for (GridRegion gridRegion : gridRegionList) {
                if (regionUser.getWgId().equals(gridRegion.getWgCode())) {
                    regionUser.setYlzd3(gridRegion.getWgName());
                }
            }
        }
        result.buildSuccess("success", regionList);
        return;
    }


    public List<GridRegionUser> getRolesForExample(GridRegionUserExample example) {
        List<GridRegionUser> regionUsers = gridRegionUserService.selectByExample(example);
        return regionUsers;
    }

    public void getRegionUserNumByBaseId(AjaxResult result) {
        Map<String, Object> map = new HashMap<>();
        GridRegionExample example1 = new GridRegionExample();
        GridRegionExample example2 = new GridRegionExample();
        GridRegionUserExample userExample = new GridRegionUserExample();
        //1、基础网格  2、专属网格
        example1.createCriteria().andWgTypeEqualTo("1").andIsValidEqualTo("1");
        int jcCount = gridRegionService.countByExample(example1);
        map.put("jcCount", jcCount);
        example2.createCriteria().andWgTypeEqualTo("2").andIsValidEqualTo("1");
        int zsCount = gridRegionService.countByExample(example2);
        map.put("zsCount", zsCount);
        //1、基础网格的网格员数量
        userExample.createCriteria().andIsValidEqualTo("1").andYlzd2EqualTo("1");
        int userCount = gridRegionUserService.countByExample(userExample);
        map.put("jcUserCount", userCount);
        result.buildSuccess("success", map);
    }


    public void getRegionUserNumByBaseIdBysjwg(AjaxResult result) {
        Map<String, Object> map = new HashMap<>();
        GridRegionExample example1 = new GridRegionExample();
        example1.createCriteria().andWgTypeEqualTo("1").andIsValidEqualTo("1").andLevelEqualTo("3");
        int sjwgsl = 0;
        sjwgsl = gridRegionService.countByExample(example1);
        if (sjwgsl == 0) {
            GridRegionExample example = new GridRegionExample();
            example.createCriteria().andWgTypeEqualTo("1").andIsValidEqualTo("1").andLevelEqualTo("2");
            sjwgsl = gridRegionService.countByExample(example);
        }
        map.put("sjwgsl", sjwgsl);
        GridRegionExample zsexample = new GridRegionExample();
        zsexample.createCriteria().andWgTypeEqualTo("2").andIsValidEqualTo("1");
        int zswgsl = gridRegionService.countByExample(zsexample);
        map.put("zswgsl", zswgsl);

        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("threegird");
        sysRole.setStatus("0");
        List<SysRole> roleList = sysRoleService.selectRoleList(sysRole);
        if(CollectionUtils.isEmpty(roleList)){
            map.put("sysConfigRoleUser", 0);
        }
        map.put("sysConfigRoleUser", sysUserRoleMapper.countUserRoleByRoleIds(roleList.stream().map(SysRole::getRoleId).collect(Collectors.toList())));
        GridItemDailyExample example2 = new GridItemDailyExample();
        GridItemDailyExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIsValidEqualTo("1");
        List<GridItemDaily> bsRcsxb = gridItemDailyService.selectByExample(example2);
        int sxs = 0;
        for (int i = 0; i < bsRcsxb.size(); i++) {
            String inputs = bsRcsxb.get(i).getSjfl();
            int count = 0;
            int count1 = 0;
            if (StringUtils.isNotEmpty(inputs)) {
                for (int J = 0; J <= inputs.length() - 2; J++) {
                    String g = inputs.substring(J, J + 2);
                    if (g.equals("00")) {
                        count++;
                    }
                }
                for (int J = 0; J <= inputs.length() - 1; J++) {
                    String g = inputs.substring(J, J + 1);
                    if (g.equals("0")) {
                        count1++;
                    }
                }
                if (count == 1 || count1 == 1) {
                    sxs++;
                }
            }
        }
        map.put("sxs", sxs);
        result.buildSuccess("success", map);
    }

    public void getHqsyerwg(String parentId, AjaxResult result) {
        GridRegionExample example1 = new GridRegionExample();
        example1.createCriteria().andWgParentIdEqualTo(parentId).andIsValidEqualTo("1");
        List<GridRegion> gridRegion = gridRegionService.selectByExample(example1);
        result.buildSuccess("success", gridRegion);
        return;
    }

    /**
     * 大屏网格管理-基本信息接口（镇下是所有乡镇的数据）
     *
     * @param result
     */
    public void getAllRegionUserNum(AjaxResult result) {
        Map<String, Object> map = new HashMap<>();
        //获取区下所有乡镇
        String url = appMgrdataUrl + "/manageData/getXZData";
        Map<String, String> headParams = new HashMap<String, String>();
        headParams.put("Content-Type", "application/json");
        //获取区下所有乡镇
        String post = null;
        try {
            post = ZQTHttpHelper.doPostJson(url, JSON.toJSONString(map), headParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject manageData = JSONObject.parseObject(post);
        if (manageData != null && StringUtils.isNotBlank(manageData.getString("data")) && "200".equals(manageData.getString("status"))) {
            GridRegionExample regionExample = new GridRegionExample();
            regionExample.createCriteria().andIsValidEqualTo("1");
            List<GridRegion> regionList = gridRegionService.selectByExample(regionExample);
            List<GridRegion> jcRegionUser = regionList.stream().filter(wgxx -> ("1".equals(wgxx.getWgType()) && "3".equals(wgxx.getLevel()))).collect(Collectors.toList());//基础网格信息
            List<GridRegion> zsRegionUser = regionList.stream().filter(wgxx -> "2".equals(wgxx.getWgType())).collect(Collectors.toList());//专属网格信息
            map.put("jcwgsl", jcRegionUser.size());
            map.put("zswgsl", zsRegionUser.size());
            map.put("wgzs", jcRegionUser.size() + zsRegionUser.size());
            SysRole roleParam = new SysRole();
            roleParam.setStatus("0");
            List<SysRole> configRoleList = sysRoleService.selectRoleList(roleParam);
            List<Long> threegirdIdList = configRoleList.stream().filter(role -> "threegird".equals(role.getRoleKey())).map(SysRole::getRoleId).collect(Collectors.toList());
            List<Long> twogridIdList = configRoleList.stream().filter(role -> "twogrid".equals(role.getRoleKey())).map(SysRole::getRoleId).collect(Collectors.toList());
            int twogridUsers = sysUserRoleMapper.countUserRoleByRoleIds(twogridIdList);
            int threegirdUsers = sysUserRoleMapper.countUserRoleByRoleIds(threegirdIdList);
            map.put("wgz", twogridUsers);
            map.put("wgy", threegirdUsers);
            map.put("wgll", twogridUsers + threegirdUsers);
            result.buildSuccess("success", map);
        }

    }
}
