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

import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.dto.experience.WcxExperContentDto;
import cn.com.countrygarden.bi.main.dto.experience.WcxPublishFileDto;
import cn.com.countrygarden.bi.main.service.experience.WcxExperContentService;
import cn.com.countrygarden.bi.main.util.*;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体验内容查询控制器
 */
@RestController("WcxExperContentController")
@RequestMapping("/api/experContent")
public class WcxExperContentController extends BaseController {


    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WcxExperContentService wcxExperContentService;


    /**
     * 体验内容查询
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/list",produces = "application/json;charset=utf-8")
    public Result list(@RequestBody(required = false) WcxExperContentDto dto,
                       HttpServletRequest request){

        Result result = new Result();

        try {

            Map<String,Object> params = new HashMap<String,Object>();

            if (EmptyUtils.isNotEmpty(dto.getIdentity())){
                List<String> identityList = Arrays.asList(dto.getIdentity().split(","));
                params.put("identity", identityList);
            }
            params.put("organCode",dto.getOrganCode());
            params.put("commId",dto.getCommId());
            params.put("name",dto.getName());
            params.put("publishType",dto.getPublishType());
            params.put("publishTime",dto.getPublishTime());
            params.put("page", StringUtils.isEmpty(String.valueOf(dto.getPage()))?1:dto.getPage());
            params.put("limit",StringUtils.isEmpty(String.valueOf(dto.getSize()))?10:dto.getSize());
            Query query = new Query(params);
            List list = wcxExperContentService.queryPageList(query);
            int total = wcxExperContentService.count(query);
            PageUtils pageUtils = new PageUtils(list,total);
            return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }

    }

    /**
     * 导出体验内容数据
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{

        Map<String,Object> formMap = Servlets.getParametersStartingWith(request,"");

        try {
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("publishTime", ObjectUtils.toString(formMap.get("startTime"),null));

            if (EmptyUtils.isNotEmpty(ObjectUtils.toString(formMap.get("identity"),null))){
                List<String> identityList = Arrays.asList(ObjectUtils.toString(formMap.get("identity")).split(","));
                params.put("identity", identityList);
            }

            params.put("publishType",ObjectUtils.toString(formMap.get("publishType"),null));
            HSSFWorkbook workbook = wcxExperContentService.exportList(params);
            String fileName = "体验内容数据.xls";
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;fileName="+ new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
            workbook.write(response.getOutputStream());
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            throw e;
        }
    }

    /**
     * 评分
     * @param dto
     * @param request
     * @return
     */
    @PostMapping(value = "/score")
    public Result score(@RequestBody WcxExperContentDto dto, HttpServletRequest request){
        Result result = new Result();

        try {
            wcxExperContentService.score(dto);
            return result.setResultCode(ResultCode.SUCCESS);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }

    /**
     * 删除体验数据
     * @param dto
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/delete")
    public Result delete(@RequestBody WcxExperContentDto dto) throws Exception {
        Result result = new Result();

        try {
            wcxExperContentService.delete(dto);
            return result.setResultCode(ResultCode.SUCCESS);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }

    /**
     * 查看附件内容
     * @param dto
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/getPublishFiles")
    public Result getPublishFiles(@RequestBody WcxExperContentDto dto) throws Exception{
        Result result = new Result();

        try {
            List<WcxPublishFileDto> fileDtoList = wcxExperContentService.getPublishFiles(dto);
            if(CollectionUtils.isNotEmpty(fileDtoList)){
                for (WcxPublishFileDto fileDto : fileDtoList){
                    String publishContent = fileDto.getPublishContent();
                    String chatName = fileDto.getChatName();
                    if (org.springframework.util.StringUtils.hasText(publishContent)) {
                        String content = EmojiParser.parseToUnicode(publishContent);
                        fileDto.setPublishContent(content);
                    } else {
                        // todo 日志 打印没有简易信息
                    }
                    if (org.springframework.util.StringUtils.hasText(chatName)) {
                        String chat = EmojiParser.parseToUnicode(chatName);
                        fileDto.setChatName(chat);
                    } else {
                        // todo 日志 打印没有简易信息
                    }
                }
            }
            return result.setResultCode(ResultCode.SUCCESS).setData(fileDtoList);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return result.setResultCode(ResultCode.FAIL).setResultMsg(e.getMessage()).setData(false);
        }
    }

}
