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

import cn.com.countrygarden.bi.main.constant.wcx.ApplicationContextRegister;
import cn.com.countrygarden.bi.main.constant.wcx.WcxConstant;
import cn.com.countrygarden.bi.main.constant.wcx.enumeration.WcxPrizeTypeEnum;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.wcx.WcxInnovationDto;
import cn.com.countrygarden.bi.main.dto.wcx.WcxPrizeDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.handler.wcx.WcxPrizeExportHandle;
import cn.com.countrygarden.bi.main.handler.wcx.WcxPrizeHandle;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.service.wcx.WcxInnovationService;
import cn.com.countrygarden.bi.main.service.wcx.WcxPrizeService;
import cn.com.countrygarden.bi.main.service.wcx.WcxThumbService;
import cn.com.countrygarden.bi.main.util.wcx.DateUtil;
import cn.com.countrygarden.bi.main.util.wcx.PageUtil;
import freemarker.core.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
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.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 各基础业务线点赞前三
 */
@RestController
@RequestMapping("/api/wcx/prize")
public class WcxPrizeController {
    @Autowired
    private WcxPrizeService wcxPrizeService;
    @Autowired
    private WcxPrizeExportHandle wcxPrizeExportHandle;
    @Autowired
    private WcxInnovationService wcxInnovationService;
    @Autowired
    private WcxThumbService wcxThumbService;

    /**
     * 查询奖单
     * 查询历史奖单 状态为
     * 查询
     *
     * @param condition
     * @return
     */
    @GetMapping
    public Result searchPrizeItem(WcxPrizeDto condition) {
        condition.setStartDate(DateUtil.formatStrToDate(condition.getStartDateStr(), DateUtil.COMMON_DATE_FORMAT));
        condition.setEndDate(DateUtil.formatStrToDate(condition.getEndDateStr(), DateUtil.COMMON_DATE_FORMAT));
        PageData pageData = wcxPrizeService.selectPageListItem(condition);
        return Response.response(pageData);
    }

    /**
     * 抽取奖单
     * 查询历史奖单 状态为
     * 查询
     *
     * @param condition
     * @return
     */
    @GetMapping("/extract")
    public Result extractPrizeItem(WcxPrizeDto condition) {
        String prizeType = condition.getPrizeType();
        if (!StringUtils.hasText(prizeType )) {
            throw new ServiceException("抽取奖单时,奖单抽取规则不能为空");
        }
        if (condition.getStartDateStr() == null || condition.getEndDateStr() == null) {
            throw new ServiceException("抽取奖单时,时间不能为空");
        }
        condition.setStartDate(DateUtil.formatStrToDate(condition.getStartDateStr(), DateUtil.COMMON_DATE_FORMAT));
        condition.setEndDate(DateUtil.formatStrToDate(condition.getEndDateStr(), DateUtil.COMMON_DATE_FORMAT));
        // 条件
        int pageIndex = condition.getPageIndex();
        int pageSize = condition.getPageSize();
        Date startDate = condition.getStartDate();
        Date endDate = condition.getEndDate();
        if (endDate != null) {
            endDate = DateUtil.getEndOfDay(endDate);
        }

        // 业务
        PageData pageData;

        // 判断是否有
        String prizeId = wcxPrizeService.haveGet(startDate, endDate, prizeType);
        if (prizeId != null) {
            pageData = wcxPrizeService.selectPageListItem(prizeId, pageIndex, pageSize);
        } else {
            // 从容器中获取对应类别的bean
            String prizeTypeName = WcxPrizeTypeEnum.getEntityByPrizeType(prizeType);
            WcxPrizeHandle bean = (WcxPrizeHandle)ApplicationContextRegister.getApplicationContext().getBean(prizeTypeName);
            // 移除原所有数据
            wcxPrizeService.remove();
            List<WcxPrizeDto> wcxPrizeDtos = bean.selectItem(startDate, endDate);

            bean.save(wcxPrizeDtos);
            // 分页展示
            pageData = PageUtil.spiltPage(wcxPrizeDtos, pageIndex, pageSize);
        }

        return Response.response(pageData);
    }

    /**
     * 导出
     *
     * @throws ParseException
     */
    @GetMapping("/exportPrize")
    public void exportByOne(WcxPrizeDto condition, HttpServletRequest request, HttpServletResponse response) throws ParseException {
        checkExportParam(condition);
        // 条件
        String prizeId = condition.getPrizeId();
        List<WcxPrizeDto> wcxPrizeDtos = wcxPrizeService.selectPageDataItem(prizeId);
        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(condition.getPrizeTitle() + ".xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        wcxPrizeExportHandle.exportItem(wcxPrizeDtos, condition.getPrizeTitle(), outputStream);
    }

    /**
     * 查询奖单
     * 查询历史奖单 状态为
     * 查询
     *
     * @param prizeItemId
     * @return
     */
    @PostMapping("/itemStatus")
    public Result updateItemStatus(@RequestParam("prizeItemId") String prizeItemId, @RequestParam("itemStatus") String itemStatus) {
        wcxPrizeService.updateItemStatus(prizeItemId, itemStatus);
        return Response.response("success");
    }

    /**
     * 查询奖单
     *
     * @param condition
     * @return
     */
    @GetMapping("/pageList")
    public Result selectPrize(WcxPrizeDto condition) {
        if (condition == null) {
            return Response.responseFail("请刷新页面后重试,或联系管理员");
        }
        condition.setStartDate(DateUtil.formatStrToDate(condition.getStartDateStr(), DateUtil.COMMON_DATE_FORMAT));
        condition.setEndDate(DateUtil.formatStrToDate(condition.getEndDateStr(), DateUtil.COMMON_DATE_FORMAT));
        PageData pageData = wcxPrizeService.selectPageList(condition);
        return Response.response(pageData);
    }

    /**
     * 删除抽取状态的明细
     *
     * @param prizeItemId
     * @return
     */
    @DeleteMapping("/itemStatusGet/{prizeItemId}")
    public Result deletePrize(@PathVariable String prizeItemId) {
        wcxPrizeService.removeGetItem(prizeItemId);
        return Response.response("success");
    }

    /**
     * 发布奖单
     *
     * @param prizeId
     * @return
     */
    @PostMapping("/openPrize")
    public Result openPrize(@RequestParam("prizeId") String prizeId) {
        if (!StringUtils.hasText(prizeId)) {
            return Response.responseFail("prizeId参数不能为空");
        }
        wcxPrizeService.openPrize(prizeId);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    private void checkExportParam(WcxPrizeDto condition) {
        if (!StringUtils.hasText(condition.getPrizeId())) {
            throw new ServiceException("奖单主键prizeId未传递");
        }
        if (!StringUtils.hasText(condition.getPrizeTitle())) {
            throw new ServiceException("奖单标题prizeTitle未传递");
        }
    }

    /**
     * 审核奖单不通过
     *
     * @param prizeItemIds
     * @return
     */
    @PostMapping("/itemStatusBatch")
    public Result disablePrizeItem(@RequestParam("prizeItemIds") String[] prizeItemIds, @RequestParam("itemStatus") String itemStatus){
        if (prizeItemIds == null)  {
            throw new ServiceException("奖单明细主键prizeIds未传递");
        }
        // todo 判断状态的合法性
        // todo 判断参数的合法性
        List<String> prizeItemIdsList = Arrays.asList(prizeItemIds);
        wcxPrizeService.updatePrizeItemStatusBatch(prizeItemIdsList, itemStatus);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    /**
     * 添加额外的创意
     * @param innovationId
     * @param prizeId
     * @return
     */
    @PostMapping("/extraInno")
    public Result saveExtraInno(@RequestParam("innovationId") String innovationId, @RequestParam("prizeId") String prizeId){
        // todo 判断prizeId是什么类型,禁止其非创意类禁止提交
        if (!StringUtils.hasText(innovationId)) {
            throw new ServiceException("innovationId未传递");
        }
        if (!StringUtils.hasText(prizeId)) {
            throw new ServiceException("prizeId未传递");
        }
        WcxPrizeDto wcxPrizeDto = wcxPrizeService.findFirst(prizeId);
        if (wcxPrizeDto == null) {
            throw new ServiceException("请刷新后重试");
        }
        WcxInnovationDto innoDto = wcxInnovationService.selectWcxInnovationDto(innovationId);
        if("7".equals(innoDto.getBaseline()) || "7"==innoDto.getBaseline()){
            throw new ServiceException("此规则不能添加服务亮点");
        }
        Integer thumbedNum = wcxThumbService.findThumbedNumByInnoId(innoDto.getInnovationId(), wcxPrizeDto.getStartDate(), wcxPrizeDto.getEndDate());
        if (thumbedNum == null) {
            innoDto.setThumbNumber(0);
        } else {
            innoDto.setThumbNumber(thumbedNum.longValue());
        }
        wcxPrizeService.saveExtraInno(innoDto, prizeId);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }

    /**
     * 审核奖单不通过
     *
     * @param prizeItemId
     * @return
     */
    @PutMapping("/orderNo")
    public Result updateOrderNo(@RequestParam("prizeItemId") String prizeItemId, @RequestParam("orderNo") Integer orderNo){
        if (!StringUtils.hasText(prizeItemId)) {
            throw new ServiceException("行标识prizeItemId未传递");
        }
        if (orderNo == null) {
            throw new ServiceException("排名orderNo未传递");
        }
        wcxPrizeService.updateOrderNo(prizeItemId, orderNo);
        return Response.response(WcxConstant.DEAL_SUCCESS);
    }
}
