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

import cn.com.countrygarden.bi.main.configurer.OSSUtil;
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.WcxNoticeMapper;
import cn.com.countrygarden.bi.main.dto.wcx.WcxNoticeDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxNoticeDtoVO;
import cn.com.countrygarden.bi.main.dto.wcx.WcxNoticeVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
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.wcx.WcxNoticeService;
import cn.com.countrygarden.bi.main.service.wcx.WcxRegionProjectService;
import cn.com.countrygarden.bi.main.service.wcx.WcxRoleService;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import cn.com.countrygarden.bi.main.util.wcx.DateUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;


//公告
@RestController
@RequestMapping("/api/wcx/wcxNotice")
public class WcxNoticeController {

    @Autowired
    private WcxNoticeService wcxNoticeService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private WcxRegionProjectService wcxRegionProjectService;

    @Autowired
    private WcxRoleService wcxRoleService;
    /**
     * 获取公告
     *
     * @param condition
     * @return
     */
    @GetMapping("/pageList")
    public Result selectNoticePageList(WcxNoticeDto condition, HttpServletRequest request) {
        condition = addAuthorityCondition(condition, request);
        //condition =check(condition,request);
        if(condition.getRoleCodeAdmin().equals("wcx_admin")){
            PageData pageData = wcxNoticeService.selectPageList(condition);
            return Response.response(pageData);
        }
        return Response.response();
    }

    @PostMapping(value = "/add")
    public Result add(WcxNoticeDto wcxNoticeDto,
                      HttpServletRequest request){
        return  wcxNoticeService.add(wcxNoticeDto,getAccessToken(request));
    }

    @PostMapping(value = "/release")
    public Result release(@RequestParam(name = "noticeId") String noticeId,
                          @RequestParam(name = "releaseStatus") String releaseStatus,
                          @RequestParam(name = "userName",required = false) String userName,
                      HttpServletRequest request){
        return  wcxNoticeService.release(noticeId,releaseStatus,userName,getAccessToken(request));
    }

    @PostMapping(value = "/del")
    public Result del(@RequestParam(name = "noticeId") String noticeId,
                          HttpServletRequest request){
        return  wcxNoticeService.del(noticeId,getAccessToken(request));
    }

    @GetMapping(value = "/check")
    public Result check(@RequestParam(name = "noticeId") String noticeId,
                      HttpServletRequest request){
        return  wcxNoticeService.check(noticeId,getAccessToken(request));
    }

    @PostMapping(value = "/edit")
    public Result edit(@RequestParam(name = "noticeId") String noticeId,
                       @RequestParam(name = "noticeTitle") String noticeTitle,
                       @RequestParam(name = "noticeContent") String noticeContent,
                       @RequestParam(name = "dialogImageUrl",required = false) String dialogImageUrl,
                      HttpServletRequest request){
        WcxNoticeDto wcxNoticeDto=new WcxNoticeDto();
        wcxNoticeDto.setNoticeId(noticeId);
        wcxNoticeDto.setNoticeTitle(noticeTitle);
        wcxNoticeDto.setNoticeContent(noticeContent);
        wcxNoticeDto.setDialogImageUrl(dialogImageUrl);
        return  wcxNoticeService.edit(wcxNoticeDto,getAccessToken(request));
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @RequestMapping(value = "/image", method = RequestMethod.POST, produces = "application/json")
    public Result uploadImage(@RequestParam(required=true,value="file") MultipartFile file){
        if(null == file){
            throw new SecurityException("上传的文件为空");
        }
        String fileName = file.getOriginalFilename();// 文件名
        String fileExtension = ""; // 文件扩展名
        fileExtension = fileName.substring(fileName.lastIndexOf("."));

		/*if (!checkIsPic(file)) {
			return rtnFail("目前只支持图片上传");
		}*/
        String random = RandomStringUtils.random(16,"abcdefghijklmnopqrstuvwxyz123456789");
        String fileOnlyOneName = random + fileExtension;
        try {
            // String uploadDirName = imgLocalPath.substring(imgLocalPath.lastIndexOf("/"), imgLocalPath.length());
            String url = OSSUtil.uploadImageToOSS(fileOnlyOneName, new ByteArrayInputStream(file.getBytes()));
            Map<String,String> map=new HashMap<>();
            map.put("url",url);
            map.put("name",fileOnlyOneName);
            //return Response.response(ImmutableMap.of("url", url));
            return Response.response(map);
        } catch (IOException e) {
            e.printStackTrace();
            return Response.response(e.getMessage());
        }
    }

    /**
     * 添加权限条件
     *
     * @param condition
     * @param request
     * @return
     */
    private WcxNoticeDto addAuthorityCondition(WcxNoticeDto 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;
    }

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

    /**
     * 通过用户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;
    }
    @Autowired
    private WcxNoticeMapper wcxNoticeMapper;
    //导出数据
    @RequestMapping(value = "/evaluationrd", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrd(WcxNoticeVO condition, HttpServletRequest request, HttpServletResponse response) throws 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(index==1){
            ExportExcelUtil<WcxNoticeDtoVO> util = new ExportExcelUtil<WcxNoticeDtoVO>();
            String[] columnNames = { "标题" ,"发布人" ,"发布时间" ,"发布状态","创建时间","创建人"};
            Collection<WcxNoticeDtoVO> list=wcxNoticeMapper.selectPageListWcxNoticeExel(condition);
            for (int i = 0; i <list.size() ; i++) {
                if(((List<WcxNoticeDtoVO>) list).get(i).getReleaseStatus().equals("1")){
                    ((List<WcxNoticeDtoVO>) list).get(i).setReleaseStatus("已发布");
                }else {
                    ((List<WcxNoticeDtoVO>) list).get(i).setReleaseStatus("未发布");
                }
            }
            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);
        }


    }
}
