package com.uas.platform.b2b.mobile.service.impl;

import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.mobile.model.ReleaseDetail;
import com.uas.platform.b2b.mobile.model.ReleaseTotal;
import com.uas.platform.b2b.mobile.service.MobileReleaseService;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.PagingRelease;
import com.uas.platform.b2b.model.PagingReleaseDetail;
import com.uas.platform.b2b.model.User;
import com.uas.platform.core.model.Constant;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.common.util.HttpUtil.ResponseWrap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by dongbw
 * 17/03/28 9:27.
 */
@Service
public class MobileReleaseServiceImpl implements MobileReleaseService {

    @Autowired
    private PagingReleaseDao pagingReleaseDao;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private EnterpriseDao enterpriseDao;

    @Autowired
    private PagingReleaseDetailDao pagingReleaseDetailDao;

    private final static String PROD_URL = "http://113.105.74.140:8092/tigase/baiduPush";

    @Override
    public ModelMap getReleaseCounts(Long vendUseruu, Long venduu) {
        ModelMap map = new ModelMap();
        String countSql = "select count(*) from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0 and prd.prd_readstatus = 0";
        Integer allCount = commonDao.queryForObject(countSql, Integer.class);
        String idSql = "select pr.pr_id from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0 and prd.prd_readstatus = 0";
        List<Integer> ids = commonDao.queryForList(idSql, Integer.class);
        String idString = "";
        for (Integer id : ids) {
            if (!"".equals(idString)) {
                idString = idString.concat(",");
            }
            idString = idString.concat(String.valueOf(id));
        }
        String title = "select a.pr_title " +
                " from purc$pagingrelease a left join purc$pagingreleasedetail prd on a.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and  prd.prd_totalstatus = 0 and prd.prd_readstatus = 0 order by a.pr_date desc";
        String date = "select a.pr_date " +
                " from purc$pagingrelease a left join purc$pagingreleasedetail prd on a.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0 and prd.prd_readstatus = 0 order by a.pr_date desc";
        String context = "select a.pr_context " +
                " from purc$pagingrelease a left join purc$pagingreleasedetail prd on a.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0 and prd.prd_readstatus = 0 order by a.pr_date desc";
        String type = "select a.pr_type " +
                " from purc$pagingrelease a left join purc$pagingreleasedetail prd on a.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0 and prd.prd_readstatus = 0 order by a.pr_date desc";
        List<ReleaseTotal> list = new ArrayList<>();
        ReleaseTotal listdata = new ReleaseTotal();
        List<String> dataTitles = commonDao.queryForList(title, String.class);  // 可能为0 或 1，所以用list装
        if (!CollectionUtils.isEmpty(dataTitles)) {
            String dataTitle = dataTitles.get(0);
            listdata.setTitle(dataTitle);
        }
        List<Date> lastTimes = commonDao.queryForList(date, Date.class);
        if (!CollectionUtils.isEmpty(lastTimes)) {
            Date lastTime = lastTimes.get(0);
            listdata.setLastTime(lastTime);
        }
        List<String> lastMessages = commonDao.queryForList(context, String.class);
        if (!CollectionUtils.isEmpty(lastMessages)) {
            String lastMessage = lastMessages.get(0);
            listdata.setLastMessage(lastMessage);
        }
        List<String> dataTypes = commonDao.queryForList(type, String.class);
        if (!CollectionUtils.isEmpty(dataTypes)) {
//            String dataType = dataTypes.get(0);
            listdata.setType("B2B商务提醒"); // 暂时设置为b2b
            listdata.setCount(allCount);
        }
        list.add(listdata);
        map.put("allCount", allCount);
        map.put("success", true);
        map.put("ids", idString);
        map.put("listdata", list);
        return map;
    }

//    @Override
//    public ModelMap getReleaseCounts(Long vendUseruu, Long venduu) {
//        ModelMap map = new ModelMap();
//        String typeSql = "select distinct(pr.pr_type) type from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_totalstatus = 0";
//        List<ReleaseTotal> typeList = commonDao.query(typeSql, ReleaseTotal.class);
//        String allCountSql = "select count(*) from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0";
//        Integer allCount = commonDao.queryForObject(allCountSql, Integer.class);
//        String idSql = "select pr.pr_id from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_totalstatus = 0";
//        List<Integer> ids = commonDao.queryForList(idSql, Integer.class);
//        String idString = "";
//        for (Integer id : ids) {
//            if (!"".equals(idString)) {
//                idString = idString.concat(",");
//            }
//            idString = idString.concat(String.valueOf(id));
//        }
//
//        List<ReleaseTotal> listdata = new ArrayList<>();
//        for (ReleaseTotal onlyType : typeList) {
//            String type = onlyType.getType();
//            String countSql = "select count(*) from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and pr.pr_type = '" + type + "' and prd.prd_totalstatus = 0";
//            Integer count = commonDao.queryForObject(countSql, Integer.class);
//            if (count != 0) {
//                String totalSql = "select a.pr_title title,a.pr_date lastTime, a.pr_context lastMessage, a.pr_type type " +
//                        " from purc$pagingrelease a left join purc$pagingreleasedetail prd on a.pr_id = prd.prd_prid " +
//                        "where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and a.pr_type = '" + type + "' and prd.prd_totalstatus = 0 order by a.pr_date desc";
//                List<ReleaseTotal> totals = commonDao.query(totalSql, ReleaseTotal.class);
//                ReleaseTotal total = totals.get(0);
//                if (total != null) { // 存在即添加到list中
//                    total.setCount(count);
//                    listdata.add(total);
//                }
//            }
//        }
//        map.put("allCount", allCount);
//        map.put("success", true);
//        map.put("ids", idString);
//        map.put("listdata", listdata);
//        return map;
//    }

    @Override
    public void changeReleaseCounts(String ids) {
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            PagingRelease release = pagingReleaseDao.findOne(Long.valueOf(id));
            Set<PagingReleaseDetail> releaseDetails = release.getPagingReleaseDetails();
            for (PagingReleaseDetail detail : releaseDetails) {
                detail.setTotalStatus(Constant.YES);
                pagingReleaseDetailDao.save(detail);
            }
        }
    }

    @Override
    public ModelMap getReleaseDetails(Long vendUseruu, Long venduu, String type) {
//        ModelMap map = new ModelMap();
//        String countSql = "select count(*) from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and pr.pr_type = '" + type + "' and prd.prd_status = 0";
//        Integer allCount = commonDao.queryForObject(countSql, Integer.class);
//        String idSql = "select pr.pr_id from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and pr.pr_type = '" + type + "' and prd.prd_status = 0";
//        List<Integer> ids = commonDao.queryForList(idSql, Integer.class);
//        String idString = "";
//        for (Integer id : ids) {
//            if (!"".equals(idString)) {
//                idString = idString.concat(",");
//            }
//            idString = idString.concat(String.valueOf(id));
//        }
//        String releaseSql = "select pr.pr_id id,pr.pr_emname releaser,pr.pr_date createTime,pr.pr_context subTitle,pr.pr_title title from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and pr.pr_type= '" + type + "' and prd.prd_status = 0 order by pr.pr_date desc";
//        List<ReleaseDetail> releaseDetailList = commonDao.query(releaseSql, ReleaseDetail.class);
//        map.put("allCount", allCount);
//        map.put("success", true);
//        map.put("ids", idString);
//        map.put("listdata", releaseDetailList);
//        return map;
        ModelMap map = new ModelMap();
        String countSql = "select count(*) from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_status = 0 and prd.prd_readstatus = 0";
        Integer allCount = commonDao.queryForObject(countSql, Integer.class);
        // 因为单挑消息针对多个人，这里一个用户已读之后，只设置该用户的消息详情为已读
        String idSql = "select prd.prd_id from purc$pagingreleasedetail prd left join purc$pagingrelease pr on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_status = 0 and prd.prd_readstatus = 0";
        List<Integer> ids = commonDao.queryForList(idSql, Integer.class);
        String idString = "";
        for (Integer id : ids) {
            if (!"".equals(idString)) {
                idString = idString.concat(",");
            }
            idString = idString.concat(String.valueOf(id));
        }
        String releaseSql = "select pr.pr_id id,pr.pr_emname releaser,pr.pr_date createTime,pr.pr_context subTitle,pr.pr_type title from purc$pagingrelease pr left join purc$pagingreleasedetail prd on pr.pr_id = prd.prd_prid where prd.prd_emuu = " + vendUseruu + " and prd.prd_venduu = " + venduu + " and prd.prd_status = 0 and prd.prd_readstatus = 0 order by pr.pr_date";
        List<ReleaseDetail> releaseDetailList = commonDao.query(releaseSql, ReleaseDetail.class);
        map.put("allCount", allCount);
        map.put("success", true);
        map.put("ids", idString);
        map.put("listdata", releaseDetailList);
        return map;
    }

    @Override
    public ModelMap changeReleaseDetails(String ids) {
        ModelMap map = new ModelMap();
        boolean success = false;
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            PagingReleaseDetail detail = pagingReleaseDetailDao.findOne(Long.valueOf(id));
            if (detail != null) {
                detail.setTotalStatus(Constant.YES);
                detail.setStatus(Constant.YES);
                detail.setReadStatus(Constant.YES);
                detail.setReadDate(new Date());
                success = true;
                // 每条消息更新之后都需要调用存储过程去更新消息数量表的对应记录，所以这里单条保存
                detail = pagingReleaseDetailDao.save(detail);
            }
        }
        map.put("success", success);
        return map;
    }


    @Override
    public void pushReleases(List<PagingReleaseDetail> pagingReleaseDetails) {
        List<Long> detailIds = new ArrayList<>();
        Set<Long> userUUs = new HashSet<>();
        for (PagingReleaseDetail releaseDetail : pagingReleaseDetails) {
            // 推送消息同一个人只推一次
            if (releaseDetail.getVendUserUU() != null && !userUUs.contains(releaseDetail.getVendUserUU())) {
                Map<String, Object> params = new HashMap<>();
                User vendUser = userDao.findOne(releaseDetail.getVendUserUU());
                Enterprise vendor = enterpriseDao.findOne(releaseDetail.getVendUU());
                if (null != vendUser && vendUser.getUserIMId() != null) {
                    params.put("master", vendor.getEnName());//账套 公司名称
                    params.put("userid", String.valueOf(vendUser.getUserIMId()));//推送目标用户
                    String title = releaseDetail.getPagingRelease().getTitle() + '-' + releaseDetail.getPagingRelease().getType();
                    params.put("title", title);//推送标题
                    params.put("content", releaseDetail.getPagingRelease().getContext());//正文
                    params.put("enUU", String.valueOf(releaseDetail.getVendUU()));//UU号
//                params.put("masterId", masterId);//账套ID
                    params.put("url", "");//跳转链接地址
                    params.put("pageTitle", releaseDetail.getPagingRelease().getTitle());//页面标题
                    params.put("platform", "B2B");//系统名称，ERP或
                    try {
                        ResponseWrap res = HttpUtil.doPost(PROD_URL, params);
                        if (!res.isSuccess()) {
                            throw new Exception(res.getContent());
                        } else {
                            userUUs.add(releaseDetail.getVendUserUU());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            if (null != releaseDetail.getId()) {
                releaseDetail.setPushStatus(Constant.YES);
                detailIds.add(releaseDetail.getId());
            }
        }
        if (!CollectionUtils.isEmpty(detailIds)) {
            pagingReleaseDetailDao.setPushedByIds(detailIds.toArray());
        }
    }

}
