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


import cn.com.countrygarden.bi.main.constant.wcx.WcxConstant;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.wcx.WcxQuerySuggestDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxReplyDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxSuggestDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxSuggestReplyDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.handler.wcx.WcxSuggestExportHandle;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.wcx.WcxSuggestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author feng
 */
@RestController
@RequestMapping("/api/wcx/suggest")
public class WcxSuggestController {
    @Autowired
    WcxSuggestService wcxSuggestService;
    @Autowired
    WcxSuggestExportHandle wcxSuggestExportHandle;
    @Autowired
    private AccessTokenService accessTokenService;

    @GetMapping("/findSuggestList")
    public Result findSuggestList(WcxSuggestDto wcxSuggestDto
    ) {

             if ("总部".equals(wcxSuggestDto.getQueryState()
             )) {
                 wcxSuggestDto.setState(1);
             }
             if (("普通").equals(wcxSuggestDto.getQueryState())) {
                 wcxSuggestDto.setState(2);
             }
        PageData pageData = null ;
        //最新   时间排序
       if ("最新".equals(wcxSuggestDto.getNewOrHot())){
            pageData= wcxSuggestService.findSuggestByTime(wcxSuggestDto);
        }
        //热门  回复数排序
        if ("热门".equals(wcxSuggestDto.getNewOrHot())){
            pageData = wcxSuggestService.findSuggestByReply(wcxSuggestDto);
        }
        return Response.response(pageData);
    }

    /**
     * 查看提议对应的回复列表
     * @param dto
     * @return
     */
    @PostMapping("/findSuggestReply")
    public Result findSuggestReply(WcxReplyDto dto) {
        PageData pageData= wcxSuggestService.findSuggestReply(dto.getSuggestId(), dto.getReplyContent(),
                dto.getPageIndex(),dto.getPageSize());
        return Response.response(pageData);
    }

    /**
     * 删除我的提议
     * @param suggestId
     * @return
     */

    @PostMapping("/deleteMySuggest")
    public Result deleteMySuggest(@RequestParam(name = "suggestId") String suggestId, HttpServletRequest request) {
        try {
            AccessToken accessToken = getAccessToken(request);
            String sysUserCode = accessToken.getUserCode();
            wcxSuggestService.deleteMySuggest(suggestId ,sysUserCode);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail(WcxConstant.DEFAULT_ERROR_INFO);
        }
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

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

    /**
     * 提议列表查询  高级查询 加 导出
     * @param wcxSuggestDto
     * @param response
     * @return
     */
    @GetMapping("/suggestListExport")
    public Result suggestListExport(WcxSuggestDto wcxSuggestDto, HttpServletResponse response, HttpServletRequest request) {
        try {
            if ("总部".equals(wcxSuggestDto.getQueryState()
            )) {
                wcxSuggestDto.setState(1);
            }
            if (("普通").equals(wcxSuggestDto.getQueryState())) {
                wcxSuggestDto.setState(2);
            }
            List<WcxQuerySuggestDto> data= new ArrayList<>();
            //最新   时间排序
            if ("最新".equals(wcxSuggestDto.getNewOrHot())){
               data = wcxSuggestService.findSuggestByTimeExport(wcxSuggestDto);
            }
            //热门  回复数排序
            if ("热门".equals(wcxSuggestDto.getNewOrHot())){
                data = wcxSuggestService.findSuggestByReplyExport(wcxSuggestDto);
            }
            //查询提议评论
            List<WcxSuggestReplyDto> suggestReplys = wcxSuggestService.getSuggestReply(data);
            
            ServletOutputStream outputStream;
            try {
                outputStream = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                throw new ServiceException("获取io流失败");
            }
            // 响应处理
            response.setContentType("multipart/form-data");
            String codedFileName = "微创新提议.xls";
            String agent = request.getHeader("USER-AGENT");
            if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
            {
                codedFileName = "=?UTF-8?B?" + (new String(Base64Utils.encodeToString(codedFileName.getBytes("UTF-8")))) + "?=";
            } else {
                codedFileName =  URLEncoder.encode(codedFileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName);
            //火狐文件名乱码
          /*  response.setContentType("multipart/form-data");
            String fileName = "suggestList.xlsx";
            try {
                fileName = URLEncoder.encode("微创新提议" + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);*/
            wcxSuggestExportHandle.exportItem(data, suggestReplys,"微创新提议", outputStream);
        }catch (Exception e){
            e.printStackTrace();
            return Response.responseFail(WcxConstant.DEFAULT_ERROR_INFO);
        }
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }
}
