package com.jpsoft.shinestar.modules.mobile.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.MessageNoticeDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/mobile/messageNoticeApi")
@Api(description = "messageNotice")
public class MessageNoticeApiController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageNoticeService messageNoticeService;

    @Autowired
    private MessageNoticeCompanyService messageNoticeCompanyService;

    @Autowired
    private MessageNoticePersonService messageNoticePersonService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyInfoService companyService;

    @Autowired
    private PersonCompanyService personCompanyService;

    @Autowired
    private DataDictionaryService dataDictionaryService;


    @ApiOperation(value="获取信息")
    @RequestMapping(value = "detail",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "编号",paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = false, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "令牌", required = false, paramType = "query")
    })
    public MessageResult<Map> detail(
                                        @RequestParam(value="id",defaultValue="") String id,
                                        String token,
                                        @RequestAttribute String subject){
        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            MessageNotice messageNotice = messageNoticeService.get(id);

            if (messageNotice != null) {
                MessageNoticeDTO mnDTO = new MessageNoticeDTO();
                PojoUtils.map(messageNotice,mnDTO);

                boolean checkPoint = false;
                MessageNoticePerson mnp = messageNoticePersonService.findByNIdAndPId(id, Long.valueOf(subject));
                if(mnp != null){
                    //checkPoint = mnp.getIsReceive();
                    mnp.setIsReceive(true);
                    mnp.setUpdateBy(subject);
                    mnp.setUpdateTime(new Date());
                    messageNoticePersonService.update(mnp);
                }else{
                    mnp = new MessageNoticePerson();
                    mnp.setId(UUID.randomUUID().toString());
                    mnp.setDelFlag(false);
                    mnp.setCreateBy(subject);
                    mnp.setCreateTime(new Date());

                    mnp.setIsReceive(true);
                    mnp.setNoticeId(id);
                    mnp.setPersonId(Long.valueOf(subject));
                    messageNoticePersonService.insert(mnp);
                }

                List<MessageNotice> classifyNoticeList = messageNoticeService.findByClassify(messageNotice.getClassify(),id);

                Map<String,Object> returnMap = new HashMap<>();
                returnMap.put("messageNotice",mnDTO);
                returnMap.put("messageNoticePerson",mnp);
                returnMap.put("classifyList",classifyNoticeList);

                msgResult.setResult(true);
                msgResult.setData(returnMap);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String title,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("update_time","desc"));

        if (StringUtils.isNotEmpty(title)) {
            searchParams.put("title","%" + title + "%");
        }

        Page<MessageNotice> page = messageNoticeService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="当天数量")
    @RequestMapping(value = "countListShort",method = RequestMethod.POST)
    public MessageResult<Integer> countListShort(String token, @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

        MessageResult<Integer> msgResult = new MessageResult<>();
        Map<String,Object> searchParams = new HashMap<>();
        DateTime startTime = DateTime.now().withTimeAtStartOfDay();
        searchParams.put("startTime", startTime.toDate());
        searchParams.put("endTime", startTime.plusDays(1).toDate());

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("update_time","desc"));

        //获取公司CODE
        CompanyInfo company = companyService.get(personInfo.getCompanyId());
        //包含下级公司
        searchParams.put("companyIds", company.getCode().split(","));

        //角色权限
//        String[] popedoms = personInfo.getPopedom().split(",");
//        List<String> noticeTypeList = new ArrayList<>();
//        for(String popedom : popedoms) {
//            if (popedom.equals("3")) {
//                int count = personCompanyService.findByPersonIdAndIsClassTeacher(personInfo.getId()).size();
//                if(count > 0){
//                    noticeTypeList.add("3");
//                }else{
//                    noticeTypeList.add("4");
//                }
//            }else {
//                noticeTypeList.add(popedom);
//            }
//        }

//        if(noticeTypeList.size() > 0) {
//            searchParams.put("noticeTypeList", noticeTypeList);
//        }

        searchParams.put("status", true);
        Page<MessageNotice> page = messageNoticeService.pageSearchShort(searchParams,1,100,false,sortList);

        msgResult.setResult(true);
        msgResult.setData(page.size());

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageListShort",method = RequestMethod.POST)
    public MessageResult<Map> pageListShort(
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

        MessageResult<Map> msgResult = new MessageResult<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("update_time","desc"));

        Map<String,Object> searchParams = new HashMap<>();
        //获取公司CODE
        CompanyInfo company = companyService.get(personInfo.getCompanyId());
        //包含下级公司
        searchParams.put("companyIds", company.getCode().split(","));

        //角色权限
        String[] popedoms = personInfo.getPopedom().split(",");
        List<String> noticeTypeList = new ArrayList<>();
//        for(String popedom : popedoms) {
//            if (popedom.equals("3")) {
//                int count = personCompanyService.findByPersonIdAndIsClassTeacher(personInfo.getId()).size();
//                if(count > 0){
//                    noticeTypeList.add("3");
//                }else{
//                    noticeTypeList.add("4");
//                }
//            }else {
//                noticeTypeList.add(popedom);
//            }
//        }

        if(noticeTypeList.size() > 0) {
            searchParams.put("noticeTypeList", noticeTypeList);
        }

        searchParams.put("status", true);
        Page<MessageNotice> page = messageNoticeService.pageSearchShort(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public MessageResult<MessageNotice> add(String title, String content,
                                            String token,
                                            @RequestAttribute String subject){
        MessageResult<MessageNotice> msgResult = new MessageResult<>();

        try {
            String noticeType = "";
            List<DataDictionary> dataDictionaryList = dataDictionaryService.findByCatalogName("用户身份");
            for(DataDictionary dataDictionary : dataDictionaryList){
                noticeType += dataDictionary.getValue() + ",";
            }
            if(StringUtils.isNotEmpty(noticeType)){
                noticeType = noticeType.substring(0,noticeType.length()-1);
            }

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            MessageNotice messageNotice = new MessageNotice();

            messageNotice.setId(UUID.randomUUID().toString());
            messageNotice.setTitle(title);
            messageNotice.setContent(content);
            messageNotice.setStatus(true);
            messageNotice.setNoticeType(noticeType);
            messageNotice.setDelFlag(false);
            messageNotice.setCreateBy(subject);
            messageNotice.setCreateTime(new Date());
            messageNotice.setUpdateBy(subject);
            messageNotice.setUpdateTime(new Date());

            int affectCount = messageNoticeService.insert(messageNotice);

            if (affectCount > 0) {
                MessageNoticeCompany messageNoticeCompany = new MessageNoticeCompany();
                messageNoticeCompany.setId(UUID.randomUUID().toString());
                messageNoticeCompany.setCompanyId(personInfo.getCompanyId());
                messageNoticeCompany.setNoticeId(messageNotice.getId());
                messageNoticeCompany.setDelFlag(false);
                messageNoticeCompany.setCreateBy(subject);
                messageNoticeCompany.setCreateTime(new Date());
                messageNoticeCompany.setUpdateBy(subject);
                messageNoticeCompany.setUpdateTime(new Date());
                int affectCount2 = messageNoticeCompanyService.insert(messageNoticeCompany);

                if(affectCount2 > 0) {
                    msgResult.setResult(true);
                    msgResult.setData(messageNotice);
                }else{
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库添加失败");
                }
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @PostMapping("checkPoints")
    @ApiOperation(value = "查询是否已领取积分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = false, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "令牌", required = false, paramType = "query")
    })
    public MessageResult<Boolean> checkPoints(String id, String token, @RequestAttribute String subject) {

        MessageResult<Boolean> messageResult = new MessageResult<>();

        try {
            boolean checkPoint = false;
            MessageNoticePerson mnp = messageNoticePersonService.findByNIdAndPId(id, Long.valueOf(subject));
            if(mnp != null){
                checkPoint = mnp.getIsReceive();
            }else{
                mnp = new MessageNoticePerson();
                mnp.setId(UUID.randomUUID().toString());
                mnp.setDelFlag(false);
                mnp.setCreateBy(subject);
                mnp.setCreateTime(new Date());

                mnp.setIsReceive(false);
                mnp.setNoticeId(id);
                mnp.setPersonId(Long.valueOf(subject));
                messageNoticePersonService.insert(mnp);
            }

            messageResult.setData(checkPoint);
            messageResult.setCode(200);
            messageResult.setMessage("成功");
            messageResult.setResult(true);


        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;
    }

    @PostMapping("collectPoints")
    @ApiOperation(value = "领取积分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", required = true, paramType = "form"),
            @ApiImplicitParam(name = "signUrl", value = "签字图片路径", required = false, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = false, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "令牌", required = false, paramType = "query")
    })
    public MessageResult<Boolean> collectPoints(String id,
                                                String signUrl,
                                                String token,
                                                @RequestAttribute String subject) {

        MessageResult<Boolean> messageResult = new MessageResult<>();
        try {
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            MessageNotice messageNotice = messageNoticeService.get(id);
            MessageNoticePerson mnp = messageNoticePersonService.findByNIdAndPId(id, Long.valueOf(subject));
            boolean isReceive = false;
            if(mnp == null){
                mnp = new MessageNoticePerson();
                mnp.setId(UUID.randomUUID().toString());
                mnp.setDelFlag(false);
                mnp.setCreateBy(subject);
                mnp.setCreateTime(new Date());

                mnp.setIsReceive(true);
                mnp.setNoticeId(id);
                mnp.setPersonId(Long.valueOf(subject));
                mnp.setSignUrl(signUrl);
                messageNoticePersonService.insert(mnp);
            }else{
                isReceive = mnp.getIsReceive();
                mnp.setIsReceive(true);
                mnp.setSignUrl(signUrl);
                messageNoticePersonService.update(mnp);
            }

//            if(!isReceive&&messageNotice.getIsReceive()) {
//                pointsUtil.addPoints("通知公告领取积分", "noticePoints", id, personInfo, "12", messageNotice.getPoint());
//            }

            messageResult.setData(true);
            messageResult.setCode(200);
            messageResult.setMessage("成功");
            messageResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;
    }
}
