package com.testor.module.safe.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.auth.model.TokenResponse;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.resource.model.domain.SysResource;
import com.testor.biz.sys.resource.service.SysResourceService;
import com.testor.biz.sys.roleResource.model.domain.SysRoleResource;
import com.testor.biz.sys.roleResource.service.SysRoleResourceService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.biz.sys.userRole.model.domain.SysUserRole;
import com.testor.biz.sys.userRole.service.SysUserRoleService;
import com.testor.module.safe.model.domain.TSafeHazardOrg;
import com.testor.module.safe.model.dto.TSafeHazardOrgDTO;
import com.testor.module.safe.model.dto.TSafeHazardOrgDelParam;
import com.testor.module.safe.model.dto.TSafeHazardOrgParam;
import com.testor.module.safe.model.vo.*;
import com.testor.module.safe.service.TSafeHazardOrgService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.jwt.JwtHelper;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 隐患上报台账Controller
 *
 * @author testor-framework
 * @date 2022-08-04 14:01:01
 */
@RestController
@RequestMapping("/module/safe/hazard/org")
@Api(value = "TSafeHazardOrg", tags = "隐患上报台账")
@Slf4j
public class TSafeHazardOrgController extends SuperController {
    @Autowired
    private TSafeHazardOrgService tSafeHazardOrgService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private NewSysOrgService newSysOrgService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysResourceService sysResourceService;

    @Autowired
    private SysRoleResourceService sysRoleResourceService;


    /* Generated Method*/
    @ApiOperation(value = "新增 隐患上报台账", notes = "Add TSafeHazardOrg")
    @PostMapping(value = "/add")
    public BaseResponse<TSafeHazardOrg> addEntity(@RequestBody TSafeHazardOrgParam addRequest) {
        BaseResponse<TSafeHazardOrg> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            boolean result = tSafeHazardOrgService.saveData(addRequest);
            if (result) {
                baseResponse.setData(addRequest);
            }
        }
        return baseResponse;
    }

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "获取 隐患上报台账 ", notes = "Get TSafeHazardOrg By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TSafeHazardOrg> getById(@ApiParam("隐患上报id") String id) {
        BaseResponse<TSafeHazardOrg> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TSafeHazardOrg data = tSafeHazardOrgService.getDetails(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 隐患上报台账 ", notes = "Update TSafeHazardOrg By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TSafeHazardOrg updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TSafeHazardOrg data = BeanHelper.beanToBean(updateRequest, TSafeHazardOrg.class);
            data.setCreateBy(null);
            boolean result = tSafeHazardOrgService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }


    @ApiOperation(value = "获取token", notes = "Update TSafeHazardOrg By Id")
    @GetMapping(value = "/getToken")
    public BaseResponse<TokenResponse> getToken(String orgId) {
        BaseResponse<TokenResponse> baseResponse = new BaseResponse<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysUser sysUser = null;
        SysResource resource = sysResourceService.getOne(new QueryWrapper<SysResource>().eq("resource_name", "隐患台账"));
        List<SysUser> users = sysUserService.list(new QueryWrapper<SysUser>().eq("org_id", orgId).eq("status", "0"));
        if (users.size() > 0) {
            for (SysUser user : users) {
                List<SysUserRole> roles = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", user.getUserId()));
                if (roles != null) {
                    for (SysUserRole role : roles) {
                        List<SysRoleResource> list = sysRoleResourceService.list(new QueryWrapper<SysRoleResource>().eq("role_id", role.getRoleId()).eq("resource_id", resource.getResourceId()));
                        if (list.size() > 0) {
                            sysUser = user;
                            break;
                        }
                    }
                }
            }
        }
        if (sysUser != null) {
            /*UserInfoResponse userInfoResponse = this.authService.getUserInfo(sysUser.getUserId());
            com.testor.biz.auth.model.UserInfo userInfo = userInfoResponse.getUserInfo();
            userInfo.setUserName(loginUser.getUserName());
            userInfo.setUserId(loginUser.getUserId());
            userInfo.setLoginName(loginUser.getLoginName());*/
            loginUser.setOrgId(sysUser.getOrgId());
            loginUser.setOrgName(sysUser.getOrgName());
            String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), loginUser.getUserId(), JSON.toJSONString(loginUser), "Token Issuer", "", 36000L);
            baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
        } else {
            UserInfo userInfo = ContextUtils.getLoginUser();
            String jwt = JwtHelper.issueJwtAuth0(IdHelper.getId32bit(), userInfo.getUserId(), JSON.toJSONString(userInfo), "Token Issuer", "", 36000L);
            baseResponse.setData(TokenResponse.builder().token(jwt).expired(36000L).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "删除 隐患上报台账 ", notes = "delete TSafeHazardOrg By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TSafeHazardOrgDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TSafeHazardOrg data = new TSafeHazardOrg();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tSafeHazardOrgService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    /*@ApiOperation(value = "批量删除隐患上报台账", notes = "delete TSafeHazardOrg by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TSafeHazardOrgDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            *//* 批量删除 *//*
            List<TSafeHazardOrg> tSafeHazardOrgList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TSafeHazardOrg data = new TSafeHazardOrg();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tSafeHazardOrgList.add(data);
            }
            boolean result = tSafeHazardOrgService.updateBatchById(tSafeHazardOrgList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }*/

    @ApiOperation(value = "获取 隐患上报台账 分页列表", notes = "List TSafeHazardOrg with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> listEntity(TSafeHazardOrgParam param) {
        return tSafeHazardOrgService.listEntity(param);
    }

    @ApiOperation(value = "获取 隐患上报台账 分页列表", notes = "List TSafeHazardOrg with page")
    @GetMapping(value = "/todoList")
    public BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> listEntityTodoList(TSafeHazardOrgParam param) {
        return tSafeHazardOrgService.listEntityTodoList(param);
    }



    @ApiOperation(value = "导出隐患上报台账列表 ", notes = "Get TSafeHazardOrg By Id")
    @GetMapping(value = "/export")
    public BaseResponse getById(TSafeHazardOrgParam param, HttpServletResponse response) {
        BaseResponse baseResponse = new BaseResponse<>();
        tSafeHazardOrgService.exportEntity(param, response);
        return baseResponse;
    }

    @ApiOperation(value = "数据构建 ", notes = "Get TSafeHazardOrg By Id")
    @GetMapping(value = "/build")
    public BaseResponse build() {
        BaseResponse baseResponse = new BaseResponse<>();
        tSafeHazardOrgService.buildData();
        return baseResponse;
    }

    @PostMapping(value = "/createOrgTask")
    public void createOrgTask(String id) {
        tSafeHazardOrgService.createOrgTask(id);
    }


    @ApiOperation(value = "隐患数量统计")
    @PostMapping(value = "/hiddenStatistics")
    public BaseResponse<List<TSafeHazardOrgStatisticsVO>> hiddenDangerStatistics(@RequestBody TSafeHazardOrgParam param) {
        BaseResponse<List<TSafeHazardOrgStatisticsVO>> baseResponse = new BaseResponse<>();
        List<TSafeHazardOrgStatisticsVO> tSafeHazardOrgStatisticsVOS = tSafeHazardOrgService.hiddenDangerStatistics(param);
        baseResponse.setData(tSafeHazardOrgStatisticsVOS);
        return baseResponse;
    }


    @ApiOperation(value = "隐患数量统计")
    @PostMapping(value = "/hiddenStatisticsByConditions")
    public BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> hiddenStatisticsByConditions(@RequestBody TSafeHazardOrgParam param) {
        BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> baseResponse = new BaseResponse<>();
        List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsVOS = tSafeHazardOrgService.hiddenStatisticsByConditions(param);
        baseResponse.setData(tSafeHazardOrgStatisticsVOS);
        return baseResponse;
    }



    @ApiOperation(value = "导入隐患台账 ", notes = "Update TSafeCheckOrg By Id")
    @PostMapping(value = "/import")
    public BaseResponse<BizGeneralResponse> importData(MultipartFile file,TSafeHazardOrgParam param){
        BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
        boolean result = tSafeHazardOrgService.importData(file,param);
        return baseResponse;
    }

    @ApiOperation(value = "导出隐患台账导入模板 ", notes = "Update TSafeCheckOrg By Id")
    @GetMapping(value = "/exportTemplate")
    public BaseResponse<BizGeneralResponse> exportTemplate(HttpServletResponse response,@RequestParam String planId){
        BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
        boolean result = tSafeHazardOrgService.exportTemplate(response,planId);
        return baseResponse;
    }

    @ApiOperation(value = "按功能配置 - 隐患数量统计")
    @PostMapping(value = "/hiddenStatisticsHistogram")
    public BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> hiddenDangerStatisticsHistogram(@RequestBody TSafeHazardOrgParam param) {
        BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> baseResponse = new BaseResponse<>();
        List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsVOS = tSafeHazardOrgService.hiddenStatisticsHistogram(param);
        baseResponse.setData(tSafeHazardOrgStatisticsVOS);
        return baseResponse;
    }

    @ApiOperation(value = "按功能配置 - 隐患数量统计")
    @PostMapping(value = "/hiddenStatisticsPieChart")
    public BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> hiddenStatisticsPieChart(@RequestBody TSafeHazardOrgParam param) {
        BaseResponse<List<TSafeHazardOrgStatisticsTypeVO>> baseResponse = new BaseResponse<>();
        List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsVOS = tSafeHazardOrgService.hiddenStatisticsPieChart(param);
        baseResponse.setData(tSafeHazardOrgStatisticsVOS);
        return baseResponse;
    }

    @ApiOperation(value = "隐患类型统计")
    @PostMapping(value = "/hiddenTypeStatistics")
    public BaseResponse<List<HiddenStatisticsVo>> hiddenTypeStatistics(@RequestBody TSafeHazardOrgParam param) {
        BaseResponse<List<HiddenStatisticsVo>> baseResponse = new BaseResponse<>();
        List<HiddenStatisticsVo> tSafeHazardOrgStatisticsVOS = tSafeHazardOrgService.hiddenTypeStatistics(param);
        baseResponse.setData(tSafeHazardOrgStatisticsVOS);
        return baseResponse;
    }

    @ApiOperation(value = "首页 - 隐患治理 -当前未整改完成隐患数量")
    @GetMapping(value = "/hiddenDangersNumber")
    public BaseResponse<Integer> hiddenDangersNumber(String orgId) {
        BaseResponse<Integer> baseResponse = new BaseResponse<>();

        UserInfo loginUser = ContextUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            return baseResponse;
        }
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }

        NewSysOrg sysOrg = newSysOrgService.getById(orgId);
        if (ObjectUtils.isEmpty(sysOrg)) {
            return baseResponse;
        }
        QueryWrapper<TSafeHazardOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("process_status", 5).ne("process_status", 4).ne("status", 1);
        String nature = sysOrg.getNature();
        if (StringUtils.isBlank(nature)){
            nature = sysOrg.getTreeLevel().toString();
        }
        int treeLevel = Integer.parseInt(nature);
        if (1 == treeLevel) {
            // 总部

        } else if (2 == treeLevel || 3 == treeLevel) {
            // 区域公司
            List<String> orgListByParentId = newSysOrgService.getSubInstitutionIds(orgId);
            queryWrapper.in("org_id", orgListByParentId);
        } else if (4 == treeLevel) {
            // 粮库
            queryWrapper.eq("org_id", orgId);
        }
        int count = tSafeHazardOrgService.count(queryWrapper);
        baseResponse.setData(count);
        return baseResponse;
    }

    @ApiOperation(value = "首页 - 隐患治理 - 当前未整改完成隐患数量列表")
    @GetMapping(value = "/hiddenDangersNumberList")
    public BaseResponse<List<HiddenDangerVO>> hiddenDangersNumberList(String orgId) {
        BaseResponse<List<HiddenDangerVO>> baseResponse = new BaseResponse<>();


        UserInfo loginUser = ContextUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            return baseResponse;
        }
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }

        NewSysOrg sysOrg = newSysOrgService.getById(orgId);
        if (ObjectUtils.isEmpty(sysOrg)) {
            return baseResponse;
        }

        List<HiddenDangerVO> hiddenDanger = new ArrayList<>();

        String nature = sysOrg.getNature();
        if (StringUtils.isBlank(nature)){
            nature = sysOrg.getTreeLevel().toString();
        }
        int treeLevel = Integer.parseInt(nature);

        // 粮库
        if (4 == treeLevel) {
            List<TSafeHazardOrg> list = tSafeHazardOrgService.list(new QueryWrapper<TSafeHazardOrg>().eq("org_id", orgId)
                    .ne("status", BizConstants.STATUS_DELETE).ne("process_status", 5).ne("process_status", 4)
            );
            if (!list.isEmpty()) {
                for (TSafeHazardOrg tSafeHazardOrg : list) {
                    HiddenDangerVO hiddenDangerVO = new HiddenDangerVO();
                    hiddenDangerVO.setOrgId(tSafeHazardOrg.getOrgId());
                    hiddenDangerVO.setOrgName(tSafeHazardOrg.getName());
                    String processStatus = tSafeHazardOrg.getProcessStatus();
                    if (StringHelper.isNotEmpty(processStatus)) {
                        hiddenDangerVO.setGenerally(Integer.parseInt(processStatus));
                    }
                    hiddenDanger.add(hiddenDangerVO);
                }
            }
        }else {
            //获取下级单位id
            List<NewSysOrg> orgListByParentId = newSysOrgService.getOrgListByParentId(orgId);
            for (NewSysOrg newSysOrg : orgListByParentId) {
                String orgId1 = newSysOrg.getOrgId();
                List<String> subInstitutionIds = newSysOrgService.getSubInstitutionIds(orgId1);

                HiddenDangerVO hiddenDangerVO = new HiddenDangerVO();
                hiddenDangerVO.setOrgId(orgId1);
                hiddenDangerVO.setOrgName(newSysOrg.getOrgName());
                if (!subInstitutionIds.isEmpty()) {
                    //一般危险隐患
                    QueryWrapper<TSafeHazardOrg> generallyQueryWrapper = new QueryWrapper<TSafeHazardOrg>().in("org_id", subInstitutionIds)
                            .ne("status", BizConstants.STATUS_DELETE).ne("process_status", 5).ne("process_status", 4)
                            .eq("\"level\"", 1);
                    int generallyCount = tSafeHazardOrgService.count(generallyQueryWrapper);
                    hiddenDangerVO.setGenerally(generallyCount);
                    //重大危险隐患
                    QueryWrapper<TSafeHazardOrg> majorQueryWrapper = new QueryWrapper<TSafeHazardOrg>().in("org_id", subInstitutionIds)
                            .ne("status", BizConstants.STATUS_DELETE).ne("process_status", 5).ne("process_status", 4)
                            .eq("\"level\"", 2);
                    int majorCount = tSafeHazardOrgService.count(majorQueryWrapper);
                    hiddenDangerVO.setMajor(majorCount);
                }
                hiddenDanger.add(hiddenDangerVO);
            }


        }

        baseResponse.setData(hiddenDanger);
        return baseResponse;
    }


    @ApiOperation(value = "首页 - 隐患治理 -当前完成隐患数量")
    @GetMapping(value = "/hiddenDangersDoneNumber")
    public BaseResponse<Integer> hiddenDangersDoneNumber(String orgId) {
        BaseResponse<Integer> baseResponse = new BaseResponse<>();

        UserInfo loginUser = ContextUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            return baseResponse;
        }
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }

        SysOrg sysOrg = sysOrgService.getById(orgId);
        if (ObjectUtils.isEmpty(sysOrg)) {
            return baseResponse;
        }
        QueryWrapper<TSafeHazardOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("process_status", 5).ne("process_status", 4).ne("status", 1);
        int treeLevel = sysOrg.getTreeLevel().intValue();
        if (1 == treeLevel) {
            // 总部

        } else if (2 == treeLevel) {
            // 区域公司
            List<SysOrg> orgListByParentId = sysOrgService.getOrgListByParentId(orgId);
            List<String> parentOrgIds = orgListByParentId.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            parentOrgIds.add(orgId);
            queryWrapper.in("org_id", parentOrgIds);


        } else if (3 == treeLevel) {
            // 粮库
            queryWrapper.eq("org_id", orgId);
        }
        int count = tSafeHazardOrgService.count(queryWrapper);
        baseResponse.setData(count);
        return baseResponse;
    }


}
