package com.ruoyi.web.controller.grid;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.zqt.ZQTImportExcelUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridDxbVO;
import com.ruoyi.system.domain.system.SysUserRole;
import com.ruoyi.system.domain.task.TkCommonTaskExample;
import com.ruoyi.system.mapper.grid.GridRegionUserMapper;
import com.ruoyi.system.mapper.system.SysUserRoleMapper;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.grid.GridRegionUserFacadeService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import com.ruoyi.system.service.system.ISysRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.task.TkCommonTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Auther: hxc
 * @Date: 2019/3/7 0007 19:00
 * @Description:
 */
@Api(tags = "网格管理 - 网关关联人管理")
@RestController
@RequestMapping("/api/grid/region/user")
public class RegionUserController {

    @Autowired
    private GridRegionUserFacadeService gridRegionUserFacadeService;
    @Autowired
    private GridRegionUserService gridRegionUserService;

    @Autowired
    private GridRegionUserMapper gridRegionUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private TkCommonTaskService tkCommonTaskService;

    @Autowired
    private GridRegionService gridRegionService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * @param wgId
     * @param ylzd1    用户姓名
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@RequestParam("wgId") String wgId,
                       @RequestParam("ylzd1") String ylzd1,
                       @RequestParam("ylzd2") String ylzd2,
                       @RequestParam("pageNum") Integer pageNum,
                       @RequestParam("pageSize") Integer pageSize) {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionUserFacadeService.getRoles(ylzd1, ylzd2, wgId,  pageNum, pageSize, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public String insert(@RequestBody GridRegionUser body) {
        try {
            return gridRegionUserFacadeService.commit(body, "insert");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@RequestBody GridRegionUser body) {
        try {
            return gridRegionUserFacadeService.commit(body, "delete");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.PATCH)
    @ResponseBody
    public String update(@RequestBody GridRegionUser body) {
        try {
            return gridRegionUserFacadeService.commit(body, "update");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "hqsyerwg", method = RequestMethod.GET)
    @ResponseBody
    public String hqsyerwg(@RequestParam("parentId") String parentId) {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionUserFacadeService.getHqsyerwg(parentId, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    /**
     * @param file
     * @param wgLx
     * @param userName
     * @param memberClass
     * @return
     */
    @ApiOperation(value = "导入网格对象Excel", notes = "将网格对象Excel导入数据库")
    @RequestMapping(value = "importExcel", method = RequestMethod.POST)
    public AjaxResult readExcel(MultipartFile file, @RequestParam String wgLx, @RequestParam String wgId,@RequestParam String userName, @RequestParam String memberClass) {
        String msg = "";
        List<GridRegionUser> list = new ArrayList<>(); //返回的集合
        List<SysUserRole> roleUserList = new ArrayList<>(); //返回的集合

        InputStream is = null;
        Workbook workbook = null;
//        String filePath="D:/网格信息20190517150433.xls";
        String fileName = file.getOriginalFilename();
        if (file == null) {
            return AjaxResult.error(400, "文件不存在");
        } else {
            try {
                is = file.getInputStream();//创建文件流
//                is = new FileInputStream(filePath); //创建文件流
                if ("xls".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                    workbook = new HSSFWorkbook(is);  //xls对应的HSSFWorkbook工作簿对象
                } else if ("xlsx".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                    workbook = new XSSFWorkbook(is);  //xlsx对应的XSSFWorkbook工作簿对象
                } else {
                    return AjaxResult.error(400, "文件格式不正确");
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error(400, "系统错误");
            }

            //循环遍历工作簿里面的sheet表
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i); //读取工作表
                if (sheet == null) //空判断
                    continue;
                for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                    Row row = sheet.getRow(j); //读取每行
                    if (row != null && memberClass != null) {

                        if ("3".equals(wgLx)) {//用户角色
                            SysUserRole roleUser = new SysUserRole();
                            //设置网格信息实体各属性的值
                            if (ZQTImportExcelUtil.getValue(row.getCell(0)) == null) {
                                msg += "第" + j + "行用户名不能为空" + "";
                            } else {
                                String username = ZQTImportExcelUtil.getValue(row.getCell(0)).trim();

                                SysUser sysUser = sysUserService.selectUserByUserName(username);

                                if (sysUser == null) {
                                    msg += "第" + j + "行不存在该用户" + "\n";
                                    continue;
                                } else {
                                    roleUser.setUserId(sysUser.getUserId());
                                }
                            }
//                            if (ZQTImportExcelUtil.getValue(row.getCell(1)) == null) {
//                                msg += "第" + j + "行姓名不能为空" + "\n";
//                            } else {
//                                roleUser.setUserName(ZQTImportExcelUtil.getValue(row.getCell(1)).trim());
//                            }
                            roleUserList.add(roleUser);
                        } else {//网格用户信息

                            GridRegionUser wgxxUser = new GridRegionUser();
                            //设置网格信息实体各属性的值
                            if (ZQTImportExcelUtil.getValue(row.getCell(0)) == null) {
                                msg += "第" + j + "行用户名不能为空" + "\n";
                            } else {
                                String username = ZQTImportExcelUtil.getValue(row.getCell(0)).trim();
                                SysUser sysUser = sysUserService.selectUserByUserName(username);

                                if (sysUser == null) {
                                    msg += "第" + j + "行不存在该用户" + "\n";
                                    continue;
                                } else {
                                    wgxxUser.setUserId(sysUser.getUserId());
                                }
                            }
                            if (ZQTImportExcelUtil.getValue(row.getCell(1)) == null) {
                                msg += "第" + j + "行姓名不能为空" + "\n";
                            } else {
                                wgxxUser.setYlzd1(ZQTImportExcelUtil.getValue(row.getCell(1)).trim());
                            }
                            if (ZQTImportExcelUtil.getValue(row.getCell(2)) == null) {
                                msg += "第" + j + "行网格编码不能为空" + "\n";
                            } else {
                                wgxxUser.setWgId(ZQTImportExcelUtil.getValue(row.getCell(2)).trim());
                            }
                            list.add(wgxxUser);
                        }

                    }
                }
            }
        }

        if (msg.length() == 0) {
//            msg.length()==0则说明没有不符合规范的数据
            int records = 0;
            int countActivity = 0;
            int temp = 0;
            try {
                if ("3".equals(wgLx)) {
                    for (SysUserRole member : roleUserList) {
                        //逐条导入数据库
                        //判断是否存在 存在update
                        SysUserRole sysUserRole = sysUserRoleMapper.getByRoleIdAndUserId(member.getUserId(), wgId);
                        if (sysUserRole != null) {
                            SysUserRole deleteRole = new SysUserRole();
                            deleteRole.setRoleId(Long.parseLong(wgId));
                            deleteRole.setUserId(member.getUserId());
                            sysUserRoleMapper.deleteUserRoleInfo(deleteRole);
                        }
                        member.setRoleId(Long.parseLong(wgId));
                        temp = sysUserRoleMapper.insertSysRole(member);
                        if (temp == 1) {
                            records++;
                        } else {
                            msg += "第" + records + 1 + "条数据导入出错：";
                        }
                    }
                } else {
                    for (GridRegionUser member : list) {
                        //逐条导入数据库
                        GridRegionUserExample example = new GridRegionUserExample();
                        GridRegionUserExample.Criteria criteria = example.createCriteria();
                        criteria.andIsValidEqualTo("1").andWgIdEqualTo(member.getWgId()).andUserIdEqualTo(member.getUserId());
                        //判断是否存在 存在update
                        List<GridRegionUser> bsWgxxUsers = gridRegionUserFacadeService.getRolesForExample(example);
                        if (bsWgxxUsers.isEmpty()) {
                            String id = UUID.randomUUID().toString();
                            member.setId(id);
                            member.setYlzd2(wgLx);
                            member.setCreateTime(DateUtils.getTime());
                            member.setCreateBy(userName);
                            member.setUpdateTime(DateUtils.getTime());
                            member.setUpdateBy(userName);
                            member.setIsValid("1");
                            temp = gridRegionUserService.insertSelective(member);
                        } else {
                            member.setId(bsWgxxUsers.get(0).getId());
                            member.setUpdateTime(DateUtils.getTime());
                            member.setUpdateBy(userName);
                            temp = gridRegionUserService.updateByPrimaryKeySelective(member);
                        }
                        if (temp == 1) {
                            records++;
                        } else {
                            msg += "第" + records + 1 + "条数据导入出错：";
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(400, msg);
            }
            msg = "导入" + records + "条数据";
            return AjaxResult.success("success", msg);
        }
        return AjaxResult.error(400, msg);//返回不规范数据信息
    }


    /*********************************对外提供的接口*************************************/

    @RequestMapping(value = "/wgIdToUser", method = RequestMethod.GET)
    @ResponseBody
    public String wgIdToUser(@RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionUserExample example = new GridRegionUserExample();
            example.createCriteria().andWgIdEqualTo(wgCode).andIsValidEqualTo("1");
            List<GridRegionUser> regionUsers = gridRegionUserFacadeService.get(example, null);
            List<String> list = new ArrayList<>();
            if (!regionUsers.isEmpty()) {
                for (GridRegionUser bsWgxxUser : regionUsers) {
                    list.add(bsWgxxUser.getUserId());
                }

                SysUser userParam = new SysUser();
                userParam.setDelFlag("0");
                userParam.setStatus("0");
                userParam.setUserIds(list);
                List<SysUser> sysUsers = sysUserService.selectUserList(userParam);
                result.buildSuccess("success", sysUsers);
                return JSON.toJSONString(result);
            } else {
                result.buildSuccess("success", list);
                return JSON.toJSONString(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getWgxxByName", method = RequestMethod.GET)
    @ResponseBody
    public String getWgxxByName(@RequestParam("wgCode") String wgCode, @RequestParam("name") String name) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionUserExample example = new GridRegionUserExample();
            GridRegionUserExample.Criteria criteria = example.createCriteria();

            if (!StringUtils.isNotEmpty(wgCode)) {
                result.buildError(400, "wgCode不能为空");
                return JSON.toJSONString(result);
            }
            if (StringUtils.isNotEmpty(name)) {
                criteria.andYlzd1Like("%" + name + "%");
            }
            if ("zswg".equals(wgCode)) {
                criteria.andIsValidEqualTo("1").andYlzd2EqualTo("2");
            } else {

                criteria.andIsValidEqualTo("1").andWgIdLike(wgCode + "%");//有效的
            }

            gridRegionUserFacadeService.getRegionUserByExample(example, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "/getRegionUserByWgIdList", method = RequestMethod.POST)
    @ResponseBody
    public String getRegionUserByWgIdList(@RequestBody GridDxbVO wgdxbVO) {
        try {
            AjaxResult result = new AjaxResult();
            if (wgdxbVO.getWgCodeList() == null || wgdxbVO.getWgCodeList().length == 0) {
                result.buildError(400, "网格code不能为空");
                return JSON.toJSONString(result);
            }
            GridRegionUserExample example = new GridRegionUserExample();
            GridRegionUserExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");//有效的
            if (StringUtils.isNotEmpty(wgdxbVO.getName())) {
                criteria.andYlzd1Like("%" + wgdxbVO.getName() + "%");
            }
            if(StringUtils.isNotBlank(wgdxbVO.getUserId())){
                criteria.andUserIdEqualTo(wgdxbVO.getUserId());
            }
            List<String> list = Arrays.asList(wgdxbVO.getWgCodeList());
            criteria.andWgIdIn(list);
            criteria.andIsValidEqualTo("1");
            gridRegionUserFacadeService.getRegionUserByExample(example, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(400, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getRegionUserNumByBaseId", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionUserNumByBaseId() {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionUserFacadeService.getRegionUserNumByBaseId(result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "/getRegionUserNumByBaseIdBysjwg", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionUserNumByBaseIdBysjwg() {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionUserFacadeService.getRegionUserNumByBaseIdBysjwg(result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping(value = "/getAllRegionUserNum", method = RequestMethod.GET)
    @ResponseBody
    public String getAllRegionUserNum() {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionUserFacadeService.getAllRegionUserNum(result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "/getWgxxBaseInfoByBaseId", method = RequestMethod.GET)
    @ResponseBody
    public String getWgxxBaseInfoByBaseId(@RequestParam String wgCode) {
        try {
            AjaxResult result = new AjaxResult();

            Map<String, Object> wgs = listWgNamesAndIds(null, wgCode);
            List<String> wgIds = (ArrayList) wgs.get("wgIds");
            List<String> wgNames = (ArrayList) wgs.get("wgNames");

            if (CollectionUtils.isEmpty(wgNames)) {
                wgNames.add("");
            }
            if (CollectionUtils.isEmpty(wgIds)) {
                wgIds.add("");
            }

            gridRegionUserFacadeService.getRegionUserNumByBaseId(result);

            Map<String, Object> map = (Map<String, Object>) result.get("data");

            map.put("ZongZhi", 0);

            TkCommonTaskExample tkCommonTaskExample = new TkCommonTaskExample();
            TkCommonTaskExample.Criteria tkCommonTaskCr = tkCommonTaskExample.createCriteria();
            tkCommonTaskCr.andWgCodeIn(wgIds);
            tkCommonTaskCr.andStandby1EqualTo("0");
            int wgCount = tkCommonTaskService.countByExample(tkCommonTaskExample);

            map.put("wangGe", wgCount);

            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Map<String, Object> listWgNamesAndIds(String wgName, String WgCode) {
        Map<String, Object> resultMap = new HashMap<>();
        List<String> wgNames = new ArrayList<>();
        List<String> wgIds = new ArrayList<>();

        wgNames.add("");
        wgIds.add("");

        resultMap.put("wgNames", wgNames);
        resultMap.put("wgIds", wgIds);

        GridRegionExample fGridRegionExample = new GridRegionExample();
        GridRegionExample.Criteria fBsWgCr = fGridRegionExample.createCriteria();
        fBsWgCr.andWgCodeEqualTo(WgCode);
        GridRegion fWg = gridRegionService.selectFirstByExample(fGridRegionExample);

        if (null == fWg) {
            return resultMap;
        }

        wgNames.add(fWg.getWgName());
        wgIds.add(fWg.getWgCode());

        GridRegionExample gridRegionExample = new GridRegionExample();
        GridRegionExample.Criteria bsWgCr = gridRegionExample.createCriteria();
        bsWgCr.andWgParentIdEqualTo(fWg.getWgCode());
        List<GridRegion> secBsWgs = gridRegionService.selectByExample(gridRegionExample);

        for (GridRegion gridRegion : secBsWgs) {
            wgNames.add(gridRegion.getWgName());
            wgIds.add(gridRegion.getWgCode());
        }

        GridRegionExample thirdGridRegionExample = new GridRegionExample();
        GridRegionExample.Criteria thirdBsWgCr = thirdGridRegionExample.createCriteria();
        thirdBsWgCr.andWgParentIdIn(wgIds);
        List<GridRegion> thirdBsWgs = gridRegionService.selectByExample(thirdGridRegionExample);

        for (GridRegion gridRegion : thirdBsWgs) {
            wgNames.add(gridRegion.getWgName());
            wgIds.add(gridRegion.getWgCode());
        }

        resultMap.put("wgNames", wgNames);
        resultMap.put("wgIds", wgIds);

        return resultMap;
    }

    /**
     * 保存网格权限
     * @return
     */
    @ApiOperation("保存网格权限")
    @PostMapping("/saveBatch")
    @Transactional
    public AjaxResult saveBatch(@RequestBody List<GridRegionUser> body){
        if(CollectionUtils.isEmpty(body) || StringUtils.isBlank(body.get(0).getUserId())){
            throw new ServiceException("参数错误！");
        }
        String userId = body.get(0).getUserId();
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        gridRegionUserMapper.deleteByExample(example);
        if(StringUtils.isNotBlank(body.get(0).getWgId())){
            GridRegion gridRegion = gridRegionService.getWgByCode(body.get(0).getWgId());
            String level = gridRegion.getLevel();
            body.forEach( e ->{
                GridRegion region = gridRegionService.getWgByCode(e.getWgId());
                if(!region.getLevel().equals(level)){
                    throw new ServiceException("必须绑定相同层级的网格！");
                }
                e.setId(IdUtils.simpleUUID());
                e.setIsValid("1");
                gridRegionUserMapper.insertSelective(e);
            });
        }
        return AjaxResult.success();
    }

    /**
     * 某用户的权限列表
     * @return
     */
    @ApiOperation("用户权限列表")
    @GetMapping("/userRegionList")
    public AjaxResult getUserRegionList(@RequestParam(value = "userId")String userId){
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        return AjaxResult.success(gridRegionUserService.selectByExample(example));
    }

}
