package cn.com.countrygarden.bi.main.controller.wcx;

import cn.com.countrygarden.bi.main.constant.wcx.WcxConstant;
import cn.com.countrygarden.bi.main.constant.wcx.enumeration.WcxAuditRoleEnum;
import cn.com.countrygarden.bi.main.constant.wcx.enumeration.WcxSysRoleEnum;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.wcx.WcxWeeklyStatisticsMapper;
import cn.com.countrygarden.bi.main.dao.wcx.WcxWeeklyStatisticsRegionMapper;
import cn.com.countrygarden.bi.main.dao.wcx.WcxWeeklyStatisticsRegionProjectMapper;
import cn.com.countrygarden.bi.main.dto.wcx.WcxInnovationDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxWeeklyStatisticsDTO;
import cn.com.countrygarden.bi.main.dto.wcx.WcxWeeklyStatisticsVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.handler.wcx.WcxInnoExportHandle;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.erp.impl.ExcelArrearageServiceImpl;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.service.wcx.WcxInnovationService;
import cn.com.countrygarden.bi.main.service.wcx.WcxRegionProjectService;
import cn.com.countrygarden.bi.main.service.wcx.WcxRoleService;
import cn.com.countrygarden.bi.main.service.wcx.WcxUserService;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import cn.com.countrygarden.bi.main.util.wcx.DateUtil;
import freemarker.core.ParseException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 创意信息处理
 */
@RestController
@RequestMapping("/api/wcx/wcxInnovation")
public class WcxInnovationController {
    @Autowired
    private WcxInnovationService wcxInnovationService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private WcxRoleService wcxRoleService;
    //    @Autowired
//    private TbSysUserService tbSysUserService;
    @Autowired
    private WcxRegionProjectService wcxRegionProjectService;
    @Autowired
    private WcxInnoExportHandle wcxInnoExportHandle;
    @Autowired
    private WcxUserService wcxUserService;
    @Autowired
    private TbSysUserService tbSysUserService;

    @Autowired
    private WcxWeeklyStatisticsMapper wcxWeeklyStatisticsMapper;

    @Autowired
    private WcxWeeklyStatisticsRegionMapper weeklyStatisticsRegionMapper;

    @Autowired
    private WcxWeeklyStatisticsRegionProjectMapper weeklyStatisticsRegionProjectMapper;

    /**
     * 获取创新数据列表
     *
     * @param condition
     * @return
     */
    @GetMapping("/pageList")
    public Result selectInnovationPageList(WcxInnovationDto condition, HttpServletRequest request) throws UnsupportedEncodingException {
        condition = addAuthorityCondition(condition, request);
        //condition =check(condition,request);
        PageData pageData = wcxInnovationService.selectPageList(condition);
        return Response.response(pageData);
    }

    /**
     * 分页查询审核页面的数据
     * @param condition
     * @param request
     * @return
     */
    @GetMapping("/pageListForAudit")
    public Result selectInnovationPageListForAudit(WcxInnovationDto condition, HttpServletRequest request) {
//        condition = addAuthorityCondition(condition, request);
        condition = check(condition, request);
        //修复区域筛选
        if(StringUtil.isBlank(condition.getRegionName())){
            condition.setRegionName(specialErpAndNcName(condition.getRegionName()));
        }
        PageData pageData = wcxInnovationService.selectPageListForAudit(condition);
        return Response.response(pageData);
    }

    /**
     * 返回自己的区域审核权限
     * @param userRoles
     * @return
     */
    private List<String> getBaselineList(List<UserRoles> userRoles) {
        List<String> baselineCodes = new ArrayList<>();
        for (UserRoles userRole : userRoles) {
            String roleCode = userRole.getRoleCode();
            String baselineCode = WcxAuditRoleEnum.getBaselineCode(roleCode);
            if (baselineCode != null) {
                baselineCodes.add(baselineCode);
            }
        }

        if (baselineCodes.isEmpty()) {
            throw new ServiceException("该用户没有权限查询信息");
        }
        if (baselineCodes.contains("Z")) {
            baselineCodes = null;
        }
        return baselineCodes;
    }

    /**
     * 审核页面做校验检查
     * @param condition
     * @param request
     * @return
     */
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(ExcelArrearageServiceImpl.class);

    private WcxInnovationDto check (WcxInnovationDto condition, HttpServletRequest request) {
        // 权限处理
        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        List<UserRoles> sysUserRole = getSysUserRole(sysUserCode);
        // 获取角色的基线权限
        List<String> baselineRole = getBaselineList(sysUserRole);

        condition.setStartDate(DateUtil.formatStrToDate(condition.getStartDateStr(), DateUtil.COMMON_DATE_FORMAT));
        condition.setEndDate(DateUtil.formatStrToDate(condition.getEndDateStr(), DateUtil.COMMON_DATE_FORMAT));
        if (baselineRole != null) {
            condition.setBaselineList(baselineRole);
            List<String>userRegionList=wcxRegionProjectService.selectErpRegionList(sysUserCode);
            List<String> userRegion=new ArrayList<>();
            for (String s : userRegionList) {
                String text = specialErpAndNcName(s);
                userRegion.add(text);
            }
            condition.setRegionList(userRegion);
            System.out.println("微创新···········"+condition.getRegionList().toString());
            logger.info("微创新···········"+condition.getRegionList().toString());
        }
        return condition;
    }

    /**
     * 更新创新表id对应的基础业务线
     *
     * @param innovationId
     * @param baseline
     * @return
     */
    @PutMapping()
    public Result update(
            @RequestParam(name = "innovationId") String innovationId
            , @RequestParam(name = "baseline") String baseline
    ) {
        wcxInnovationService.updateBaseLineById(innovationId, baseline);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    /**
     * 添加权限条件
     *
     * @param condition
     * @param request
     * @return
     */
    private WcxInnovationDto addAuthorityCondition(WcxInnovationDto condition, HttpServletRequest request) {
        // 权限处理
        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        List<UserRoles> sysUserRole = getSysUserRole(sysUserCode);
        // 获取角色的基线权限
        String baselineRole = getBaseline(sysUserRole);

        condition.setStartDate(DateUtil.formatStrToDate(condition.getStartDateStr(), DateUtil.COMMON_DATE_FORMAT));
        condition.setEndDate(DateUtil.formatStrToDate(condition.getEndDateStr(), DateUtil.COMMON_DATE_FORMAT));
        if ("0".equals(baselineRole)) {
            String erpRegionName = wcxRegionProjectService.selectErpRegionName(sysUserCode);
            if (!StringUtils.hasText(erpRegionName)) {
                throw new ServiceException("关联不上登录用户所在区域");
            }
            String regionName = erpRegionName; // 部门名称即区域名称
            condition.setRegionName(regionName);
        } else if (baselineRole != null) {
            condition.setBaseline(baselineRole);
        }
        for (int i = 0; i <sysUserRole.size() ; i++) {
            if(sysUserRole.get(i).getRoleCode().equals("wcx_admin")){
                condition.setRoleCodeAdmin(sysUserRole.get(i).getRoleCode());
            }
        }
        return condition;
    }
    /**
     * 通过用户code获取对应得用户角色
     *
     * @param sysUserCode
     * @return
     */
    private List<UserRoles> getSysUserRole(String sysUserCode) {
        List<UserRoles> userRoles = wcxRoleService.selectSysRoleBySysUserCode(sysUserCode);
        return userRoles;
    }

    /**
     * 获取用户可操作的对应基线
     *
     * @param userRoles
     * @return 管理员权限 返回null;
     * 区域权限 返回 0
     * 部分权限 返回对应基线码(1,2,3....)
     */
    private String getBaseline(List<UserRoles> userRoles) {
        List<String> baselineCodes = new ArrayList<>();
        for (UserRoles userRole : userRoles) {
            String roleCode = userRole.getRoleCode();
            String baselineCode = WcxSysRoleEnum.getBaselineCode(roleCode);
            if (baselineCode != null) {
                baselineCodes.add(baselineCode);
            }
        }

        if (baselineCodes.isEmpty()) {
            throw new ServiceException("该用户没有权限查询信息");
        }

        String baseline = null;
        if (baselineCodes.contains("Z")) {
            baseline = null;
        } else {
            // 日志 如果一个人含有多个角色
            baseline = baselineCodes.get(0);
        }
        return baseline;
    }

    /**
     * 获取创新数据
     *
     * @param innovationId
     * @return
     */
    @GetMapping
    public Result getInnovation(String innovationId) {
        if (!StringUtils.hasText(innovationId)) {
            return Response.responseFail("创意id不能传空");
        }
        WcxInnovationDto condition = new WcxInnovationDto();
        condition.setInnovationId(innovationId);
        WcxInnovationDto wcxInnovationDto = wcxInnovationService.selectWcxInnovationDto(condition);
        return Response.response(wcxInnovationDto);
    }


    /**
     * 获取待审核创新数据
     *
     * @param innovationId
     * @return
     */
    @GetMapping("/getInnovationShenhe")
    public Result getInnovationShenhe(String innovationId) {
        if (!StringUtils.hasText(innovationId)) {
            return Response.responseFail("创意id不能传空");
        }
        WcxInnovationDto condition = new WcxInnovationDto();
        condition.setInnovationId(innovationId);
        WcxInnovationDto wcxInnovationDto = wcxInnovationService.getInnovationShenhe(condition);
        return Response.response(wcxInnovationDto);
    }

    /**
     * @return cn.com.countrygarden.bi.main.core.Result
     * @Methods examine 审核
     * @Author chenhaowei
     * @Date 2020/7/16 19:16
     * @Param [wcxInnovationDto, request]
     **/
    @PostMapping("/examine")
    public Result examine(WcxInnovationDto wcxInnovationDto, HttpServletRequest request) {
        if (!StringUtils.hasText(wcxInnovationDto.getInnovationId())) {
            return Response.responseFail("创意id不能传空");
        }
        WcxInnovationDto result = wcxInnovationService.select(wcxInnovationDto.getInnovationId());
        if (result == null) {
            return Response.responseFail("不存在该条创意,请刷新页面后重试");
        }
        int examine=wcxInnovationService.examineStatus(wcxInnovationDto.getInnovationId());
        if(examine==1||examine==2){
            return Response.responseFail("该数据已被处理");
        }
        //查询时候已经做了数据过滤，审核这里就不做任何的限制
        wcxInnovationService.examine(wcxInnovationDto);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    @PostMapping("/addExamine")
    public void addExamine(String innovationId,String baseline){
        try {
            wcxInnovationService.addExamine(innovationId,baseline);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除创新数据
     *
     * @param innovationId
     * @return
     */
    @DeleteMapping("/{innovationId}")
    public Result delete(@PathVariable String innovationId, HttpServletRequest request) {
        if (!StringUtils.hasText(innovationId)) {
            return Response.responseFail("创意id不能传空");
        }
        WcxInnovationDto result = wcxInnovationService.select(innovationId);
        if (result == null) {
            return Response.responseFail("不存在该条创意,请刷新页面后重试");
        }

        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        List<UserRoles> sysUserRole = getSysUserRole(sysUserCode);
        // 权限处理
        // 判断是否有权限删除
        String baselineRole = getBaseline(sysUserRole);
        String baseline = result.getBaseline();
        // 如果是区域则对应得条件
        if ("0".equals(baselineRole)) {
            // 判断区域角色是否有权限
            String erpRegionName = wcxRegionProjectService.selectErpRegionName(sysUserCode);
            if (!StringUtils.hasText(erpRegionName)) {
                return Response.responseFail("关联不上登录用户所在区域");
            }
            String regionName = erpRegionName;
            String innRegionName = result.getRegionName();
            if (innRegionName == null || !innRegionName.contains(regionName)) {
                return Response.responseFail("该用户没有权限删除信息");
            }
        } else if (baselineRole != null && !baselineRole.equals(baseline)) {
            // 判断是否是线条角色,且删除的是对应线条
            return Response.responseFail("该用户没有权限删除信息");
        }

        try {
            wcxInnovationService.delete(innovationId);
        } catch (ServiceException e) {
            e.printStackTrace();
            return Response.responseFail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail(WcxConstant.DEFAULT_ERROR_INFO);
        }
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    /**
     * 获取模糊查询创新简易数据
     *
     * @param innovationTitle 创意标题模糊信息
     * @return
     */
    @GetMapping("/simpleList")
    public Result innovationSimpleList(String innovationTitle) {
        if (!StringUtils.hasText(innovationTitle)) {
            return Response.responseFail("创意标题innovationTitle不能传空");
        }
        List<WcxInnovationDto> innovDtos = wcxInnovationService.selectSimplePageData(innovationTitle);
        return Response.response(innovDtos);
    }

    /**
     * 获取操作者用户信息
     *
     * @param request
     * @return
     */
    public AccessToken getAccessToken(HttpServletRequest request) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return token;
    }

    /**
     * 创意导出
     *
     * @throws ParseException
     */
    @GetMapping("/export")
    public void baselineExport(WcxInnovationDto condition, HttpServletRequest request, HttpServletResponse response) throws ParseException {
        //checkExportParam(condition);
        //
        condition = addAuthorityCondition(condition, request);
        condition.setPageSize(-1);
        condition.setExamineStatus(condition.getExamineStatus());

        List<WcxInnovationDto> data = wcxInnovationService.selectInnoList(condition);

        ServletOutputStream outputStream;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("获取io流失败");
        }
        // 响应处理
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("微创新创意" + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        wcxInnoExportHandle.exportItem(data, "微创新创意", outputStream);
    }

    @GetMapping("/getErpOrgList")
    public Result getErpOrgList() {
        List<Map<String, String>> erpOrg=wcxInnovationService.getErpOrgList();
        return Response.response(erpOrg);
    }

    private String specialErpAndNcName(String erpRegionName) {
        // 特殊处理,NC组织体系与ERP组织体系, 目前通过名称关联, 但是NC的名称为广州东莞深区域,erp的名称为广州东/莞深区域,这里特殊处理区域信息
        if (StringUtils.hasText(erpRegionName)) {
            if (erpRegionName.contains("江中/佛山区域")) {
                erpRegionName = "江中佛山区域";
            }
            if (erpRegionName.contains("广州东/莞深区域")) {
                erpRegionName = "广州东莞深区域";
            }
            if (erpRegionName.contains("广清/佛山区域")) {
                erpRegionName = "广清佛山区域";
            }
            if (erpRegionName.contains("粤东/惠深区域")) {
                erpRegionName = "粤东惠深区域";
            }
            if (erpRegionName.contains("广清/佛山区域")) {
                erpRegionName = "广清佛山区域";
            }
            if (erpRegionName.contains("广西/云南区域")) {
                erpRegionName = "广西云南区域";
            }
            if (erpRegionName.contains("广清/莞深区域")) {
                erpRegionName = "广清莞深区域";
            }
            if(erpRegionName.contains("盛世")){
                erpRegionName = "盛世";
            }
        }
        return erpRegionName;
    }

    @PostMapping("/addTop")
    private Result addTop(@RequestParam(value = "innovationId")String innovationId,
                          @RequestParam(value = "isTop")Integer isTop,HttpServletRequest request){
        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        return Response.response(wcxInnovationService.addTop(innovationId,isTop,sysUserCode));
    }

    @PostMapping("/addRecomm")
    private Result addRecomm(@RequestParam(value = "innovationId")String innovationId,
                          @RequestParam(value = "isRecomm")Integer isRecomm,HttpServletRequest request){
        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        return Response.response(wcxInnovationService.addRecomm(innovationId,isRecomm,sysUserCode));
    }

    @PostMapping("/addExcellent")
    private Result addExcellent(@RequestParam(value = "innovationId")String innovationId,
                          @RequestParam(value = "isExcellent")Integer isExcellent,HttpServletRequest request){
        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        return Response.response(wcxInnovationService.addExcellent(innovationId,isExcellent,sysUserCode));
    }


    @GetMapping("/getWcxWeekly")
    public Result getWcxWeekly(WcxWeeklyStatisticsDTO weeklyStatisticsDTO,HttpServletRequest request) {
        return Response.response(wcxInnovationService.getWcxWeekly(weeklyStatisticsDTO,request));
    }


    //导出数据
    @RequestMapping(value = "/evaluationrdgetWcxWeekly", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdgetWcxWeekly(WcxWeeklyStatisticsDTO weeklyStatisticsDTO, HttpServletRequest request, HttpServletResponse response) throws java.text.ParseException, IOException {

/*        AccessToken accessToken = getAccessToken(request);
        String sysUserCode = accessToken.getUserCode();
        List<UserRoles> sysUserRole = getSysUserRole(sysUserCode);
        int index=0;
        for (int i = 0; i <sysUserRole.size() ; i++) {
            if(sysUserRole.get(i).getRoleCode().equals("wcx_admin")){
                index=1;
                break;
            }
        }*/
        if(StringUtil.isNotBlank(weeklyStatisticsDTO.getWeek())){
            String[] timeStr=weeklyStatisticsDTO.getWeek().split(",");
            weeklyStatisticsDTO.setWeekList( Arrays.asList(timeStr));
        }

            ExportExcelUtil<WcxWeeklyStatisticsVO> util = new ExportExcelUtil<>();
            String[] columnNames = { "周期" ,"新增创新内容" ,"新增创新内容环比（%）" ,"访问人数","用户使用环比（%）","新增用户数","新增用户环比（%）"};
        Collection<WcxWeeklyStatisticsVO> list=new ArrayList<>();
        if(StringUtil.isNotBlank(weeklyStatisticsDTO.getOrgName())){
            Collection<WcxWeeklyStatisticsVO>statisquyu=weeklyStatisticsRegionMapper.selectstatisquyuVO(weeklyStatisticsDTO);
            if(CollectionUtils.isNotEmpty(statisquyu)){
                list.addAll(statisquyu);
            }

        }else if(StringUtil.isNotBlank(weeklyStatisticsDTO.getOrgName()) && StringUtil.isNotBlank(weeklyStatisticsDTO.getCommName())){
            Collection<WcxWeeklyStatisticsVO> statisquyuxiangmu=weeklyStatisticsRegionProjectMapper.selectstatisquyuxiangmuVO(weeklyStatisticsDTO);
            if(CollectionUtils.isNotEmpty(statisquyuxiangmu)){
                list.addAll(statisquyuxiangmu);
            }
        }else {
            Collection<WcxWeeklyStatisticsVO> statistime=wcxWeeklyStatisticsMapper.statistimeVO(weeklyStatisticsDTO);
            if(CollectionUtils.isNotEmpty(statistime)){
                list.addAll(statistime);
            }
        }

            response.setContentType("multipart/form-data");
            String fileName = URLEncoder.encode("用户使用情况报表.xls","UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            util.exportExcel("用户使用情况报表", columnNames, list, response.getOutputStream(), ExportExcelUtil.EXCEL_FILE_2003,null);



    }

    @GetMapping(value = "/tongjizhou",  produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void tongjizhou(HttpServletRequest request) throws java.text.ParseException, IOException {
        wcxInnovationService.tongjizhou();
        System.out.println("执行完毕");
    }

    @GetMapping(value = "/tongjiyue",  produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void tongjiyue(HttpServletRequest request) throws java.text.ParseException, IOException {
        wcxInnovationService.tongjiyue();
        System.out.println("执行完毕");
    }

    @GetMapping(value = "/tongjiri",  produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void tongjiri(HttpServletRequest request) throws java.text.ParseException, IOException {
        wcxInnovationService.tongjiri();
        System.out.println("执行完毕");
    }
}
