package com.ssj.service.weixin.library.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.weixin.libmy.domain.LibBookApply;
import com.ssj.bean.weixin.libmy.domain.LibBookLocking;
import com.ssj.bean.weixin.libmy.domain.TbLibBookInfo;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.dao.weixin.library.dao.IOneBookQueryDao;
import com.ssj.dao.weixin.library.dao.IlibBookApplyDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.reading.request.*;
import com.ssj.service.weixin.library.service.*;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional
@Service(version="1.0")
public class LibBookApplyServiceImpl extends BaseServiceImpl<LibBookApply,String> implements LibBookApplyService {

    @Autowired
    private IlibBookApplyDao dao;
    @Autowired
    private PushTemplateService pushTemplateService;
    @Autowired
    private ILibJoinService joinService;
    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private UserService userService;

    @Autowired
    private IOneBookQueryDao queryDao;

    @Autowired
    private LibBookLockingService lockingService;

    @Autowired
    private IBookManagerService managerService;
    @Autowired
    private ILibBookService bookService;

    @Override
    public PagingAndSortingRepository<LibBookApply,String> getDao() {
        return dao;
    }

    @Override
    public void saveApplyInfo(ApplyBookReq param) {
        List<BookListVO> bookList = param.getBookList();
        if(bookList!=null && bookList.size()>0){
            Date now = new Date();
            String batchId =  (int)((Math.random()*9+1)*10000000)+"";//随机8位数
            for (BookListVO vo:bookList){
                LibBookApply apply = new LibBookApply();
                apply.setLibId(param.getLibId());
                apply.setBookImg(vo.getBookImg());
                apply.setBookSrc(vo.getBookSrc());
                apply.setCreateTime(now);
                apply.setPaiDate(vo.getPaiDate());
                apply.setTitle(vo.getTitle());
                apply.setPublish(vo.getPublish());
                apply.setType(1);
                apply.setBatchId(batchId);
                this.save(apply);
            }
            //推送通知
            String template_id_short="OPENTM207273120";
            String openId = SystemResourceLocator.getValue("book_openid").toString();
            Map<String, String> data = new HashMap<String,String>();
            TbLibJoin libjoin= joinService.getById(param.getLibId());
            data.put("first", libjoin.getLeagueName());
            data.put("keyword1", "申请新书单"+bookList.size()+"本需求");
            data.put("keyword2", "请您登录pc端后台操作");
            data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
            //data.put("remark","请登录后台查阅导出明细并可跟进办理。");
            pushTemplateDis(data,"OPENTM207273120");
            tokenManager.set("apply"+param.getLibId(), 1,30 * 24 * 3600);
        }
    }

    @Override
    public int randomBook(RandomBookReq param) {
        TbLibJoin libJoin= joinService.getById(param.getLibId());
        if(!libJoin.getLeagueName().contains("测试") && !libJoin.getLeagueName().contains("总部")) {
            String key = "read" + param.getLibId();
            Integer monthValue = tokenManager.get(key, Integer.class);
            if (monthValue != null) {
                if (monthValue > 0) {
                    return monthValue;
                }
            }
            tokenManager.set(key, 1, 60 * 24 * 3600);
        }
        LibBookApply apply = new LibBookApply();
        apply.setLibId(param.getLibId());
        apply.setType(2);
        apply.setBatchId((int)((Math.random()*9+1)*10000000)+"");
        apply.setRadomJson(JSON.toJSONString(param));
        apply.setCreateTime(new Date());
        this.save(apply);


        //推送通知
        Map<String, String> data = new HashMap<String,String>();

        data.put("first", libJoin.getLeagueName());
        data.put("keyword1", "申请随机调书"+param.getBookSize()+"本需求");
        data.put("keyword2", "请您登录pc端后台操作");
        data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
        //data.put("remark","请登录后台查阅导出明细并可跟进办理。");
        pushTemplateDis(data,"OPENTM207273120");
        return 0;
    }

    @Override
    public void saveApplyAudit(String libId,String batchId, int state, String msg) {
        dao.updateAudit(libId,batchId,state,msg);

        //发送通知
        Map<String, String> data = new HashMap<String,String>();
        List<Map<String, Object>> list =managerService.findByLibIdAndType(libId,4);
        data.put("first", "亲爱的馆长，您好！您的新书单申请有新动态");
        data.put("keyword1", "新书单申请");
        data.put("keyword2", state==1?"通过":"拒绝");
        data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
        data.put("remark",msg);
        for (Map<String, Object> map : list) {
                SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account")==null?"":map.get("wx_account").toString(), "OPENTM408894858", null,data);
                pushTemplateService.saveAndSendPushWxTemplate(templateShort);
        }
    }

    @Override
    public void saveApplyRadom(LibBookApply apply) {
        //随机生成数据插入到locking 表批量插入
        RandomBookReq param = JSON.parseObject(apply.getRadomJson(),RandomBookReq.class);
        Map<String,Object> data1 = getGradeSearch(param.getGradeList());
        StringBuffer selSql = new StringBuffer();
        if(data1.get("grade")!=null){
            selSql.append(" and t.section in ('").append(data1.get("grade").toString().replace(",","','")).append("')");
        }
        data1.putAll(getThemeSearch(param.getThemeList()));
        if(!"".equals(data1.get("ptheme"))){
            selSql.append("  and (t.parent_theme in ('").append(data1.get("ptheme").toString().replace(",","','")).append("') ");
            if(!"".equals(data1.get("ctheme"))){
                selSql.append("  or t.child_theme in ('").append(data1.get("ctheme").toString().replace(",","','")).append("')) ");
            }else{
                selSql.append("  )");
            }
        }else{
            if(!"".equals(data1.get("ctheme"))) {
                selSql.append("  and t.child_theme in ('").append(data1.get("ctheme").toString().replace(",", "','")).append("') ");
            }
        }

        //插入数据
        List<Map<String,Object>> list = queryDao.findRadomList(selSql.toString(),param.getBookSize(),param.getLibId(),"");
        //dao.insertData(selSql.toString(),param.getBookSize(),param.getLibId());
        int againNum = 0;
        if(list!=null){
            againNum = param.getBookSize()-list.size();
        }else{
            list = new ArrayList<>();
            againNum = param.getBookSize();
        }
        if(againNum>0){
            StringBuffer idAppand = new StringBuffer();
            idAppand.append(" and t.id not in (");
            int i=0;
            for (Map<String,Object> map :list) {
                idAppand.append("'").append(map.get("id")).append("'");
                i++;
                if(i<list.size()){
                    idAppand.append(",");
                }
            }
            idAppand.append(") ");
            list.addAll(queryDao.findRadomList("",againNum,param.getLibId(),idAppand.toString()));
        }
        List<LibBookLocking> lockList = new ArrayList<>();
        List<TbLibBookInfo> infoList = new ArrayList<>();
        for (Map<String,Object> map :list){

            //减去库存
            TbLibBookInfo info =bookService.getById(map.get("info_id").toString());
            info.setBookStockRemain(info.getBookStockRemain()-1);

            //保存记录
            LibBookLocking locking = new LibBookLocking();
            locking.setBookSize(1);
            locking.setBookInfoId(map.get("info_id").toString());
            locking.setInLibId(param.getLibId());
            locking.setOutLibId("fa14e041-3823-4dac-b061-1e250e5a7d49");
            locking.setStat(2);
            locking.setType(2);
            locking.setCreateTime(new Date());
            locking.setUpdateTime(new Date());
            locking.setBookDetailId(map.get("id").toString());
            locking.setIsbn13(map.get("isbn13").toString());
            locking.setBatchId(apply.getBatchId());
            lockList.add(locking);
            infoList.add(info);
            //lockingService.save(locking);
        }
        lockingService.save(lockList);
        bookService.save(infoList);
        apply.setState(1);
        this.save(apply);
        //发送通知
        Map<String, String> data = new HashMap<String,String>();
        List<Map<String, Object>> list2 =managerService.findByLibIdAndType(apply.getLibId(),4);
        data.put("first", "亲爱的馆长，您好！您的随机调书申请已处理。");
        data.put("keyword1", "随机调书");
        data.put("keyword2", "已完成");
        data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
        data.put("remark","系统已经为您随机挑书"+param.getBookSize()+"本，正快马加鞭送给您，请耐心等待吧！");
        for (Map<String, Object> map : list2) {
            SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account")==null?"":map.get("wx_account").toString(), "OPENTM408894858", null,data);
            pushTemplateService.saveAndSendPushWxTemplate(templateShort);
        }
    }

    @Override
    public int appplyTimes(String libId) {
        String key = "apply"+libId;
        Integer monthValue=tokenManager.get(key,Integer.class);
        if(monthValue!=null){
            if(monthValue>0){
                return monthValue;
            }
        }
        return 0;
    }

    private Map<String,Object> getThemeSearch(List<ThemeReq> themeList){
        Map<String,Object> map = new HashMap<>();
        String ptheme = "";
        String ctheme = "";
        if(themeList!=null && themeList.size()>0){
            for (ThemeReq themeReq:themeList){
                List<ThemeReq> childList = themeReq.getChildList();
                if(childList==null || childList.size()==0){
                    if(ptheme.length()>0){
                        ptheme +=",";
                    }
                    ptheme +=themeReq.getCode();
                }else{
                    for(ThemeReq cthemeReq:childList){
                        if(ctheme.length()>0){
                            ctheme +=",";
                        }
                        ctheme+=cthemeReq.getCode();
                    }
                }
            }
        }

        map.put("ptheme","");
        map.put("ctheme",ptheme);
        return map;
    }

    private Map<String,Object> getGradeSearch(List<GradeReq> gradeList){
        Map<String,Object> map = new HashMap<>();
        String grade = "";
        if(gradeList!=null && gradeList.size()>0){
            for (GradeReq gradeReq:gradeList){
                if(grade.length()>0){
                    grade +=",";
                }
                grade +=gradeReq.getGrade();
            }
        }

        map.put("grade",grade);
        return map;
    }

    public void pushTemplateDis(Map<String, String> data,String templateId){

        String str =   tokenManager.getString("dispatcher2018");
        String[] userIds=str.split(",");
        for (String string : userIds) {
            if(string!=null&&string.length()>0){
                String wxopenId=userService.getAccount(string);
                SendTemplateShort templateShort = new SendTemplateShort(wxopenId, templateId, null,data);
                pushTemplateService.saveAndSendPushWxTemplate(templateShort);
            }
        }
    }
}
