package com.cftech.qy.message.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.api.QyArticle;
import com.cftech.base.org.api.QyMsgUtil;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.QyuserService;
import com.cftech.cms.cfarticle.model.Cfarticle;
import com.cftech.cms.cfarticle.service.CfarticleService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.Constants;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.mp.mass.model.MassSendrecord;
import com.cftech.mp.mass.service.MassSendrecordService;
import com.cftech.sys.security.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lisw on 2017/5/16 0016.
 */
@RestController
@RequestMapping("/a/qyMessage")
public class QyMessageController {

    @Autowired
    private MassSendrecordService massSendrecordService;

    @Autowired
    private QyMsgUtil qyMsgUtil;

    @Autowired
    private QyuserService qyuserService;

    @Autowired
    private CfarticleService cfArticleService;

    /**
     * @param request
     * @param massSendRecord 消息记录实体
     * @param orgId          部门ID列表
     * @param taglist        标签ID列表
     * @param userid         人员ID列表
     * @param articlesId     文章ID列表
     * @return
     */
    @RequestMapping(value = "sendMessage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresPermissions(value = "qy:article:sendMass")
    public JSONObject rtnJson(HttpServletRequest request,
                              MassSendrecord massSendRecord,
                              String orgId,
                              String taglist,
                              String userid,
                              String articlesId,
                              Long agentId,
                              String domain) {
        Long accountsid = UserUtils.getmpaccounts(request);
        boolean isAll = false;
        if (StringUtils.equals(massSendRecord.getSendType(), "0")) {
            isAll = true;
        }
        JSONObject whereJson = new JSONObject();
        List<Qyuser> qyusers = null;
        if (StringUtils.isNotBlank(userid)) {
            Conds qyUserConds = new Conds();
            qyUserConds.equal("t.accounts_id", accountsid);
            qyUserConds.equal("t.del_flag", 0);
            qyUserConds.in("t.id", userid.split(","));
            qyusers = qyuserService.fetchSearchByPage(qyUserConds, null, 0, 0);
            whereJson.put("userid", userid);
        }
        String orgUnits[] = new String[0];
        String tags[] = new String[0];
        if (StringUtils.isNotBlank(orgId)) {
            orgUnits = orgId.split(",");
            whereJson.put("orgId", orgId);
        }
        if (StringUtils.isNotBlank(taglist)) {
            tags = taglist.split(",");
            whereJson.put("tagList", taglist);
        }
        Conds cfArticleConds = new Conds();
        cfArticleConds.equal("del_flag", 0);
        List<Cfarticle> cfarticleList = cfArticleService.fetchSearchByPageInOrder(cfArticleConds, articlesId);
        int i = 0;
        List<QyArticle> qyArticles = new ArrayList<>();
        for (Cfarticle cfArticle : cfarticleList) {
            QyArticle qyArticle = new QyArticle();
            qyArticle.setTitle(cfArticle.getTitle());
            qyArticle.setDescription(cfArticle.getDesc());
            String picUrl = "";
            if (!cfArticle.getBigimg().startsWith("http://")) {
                cfArticle.setBigimg(domain + cfArticle.getBigimg());
            }
            if (!cfArticle.getSmallimg().startsWith("http://")) {
                cfArticle.setSmallimg(domain + cfArticle.getSmallimg());
            }
            if (i == 0) {
                picUrl = cfArticle.getBigimg();
            } else {
                picUrl = cfArticle.getSmallimg();
            }
            qyArticle.setPicurl(picUrl);
            if (cfArticle.getIsUrl() == '0') {
                qyArticle.setUrl(cfArticle.getContentSourceUrl());
            } else {
                String articleDetailUrl = "";
                if (cfArticle.getType().equals("0")) {//普通文章详情
                    articleDetailUrl = SystemConfig.p.get("ARTICLEDETAILURL").toString();
                } else {//图集文章详情
                    articleDetailUrl = SystemConfig.p.get("ARTICLEDETAILPICURL").toString();
                }
                String url = articleDetailUrl.replace("{ACCOUNTSID}", cfArticle.getAccountsId().toString()).replace("{ID}", cfArticle.getId().toString());
                qyArticle.setUrl(url);
            }
            qyArticles.add(qyArticle);
        }
        JSONObject msgJson = qyMsgUtil.sendNews(accountsid, isAll, qyusers, orgUnits, tags, agentId, qyArticles);
        JSONObject rtnJson = new JSONObject();
        massSendRecord.setAccountsid(accountsid);
        massSendRecord.setArea(whereJson.toJSONString());
        massSendRecord.setNewMedias(articlesId);
        massSendRecord.setCreateby(UserUtils.getUser().getId());
        massSendRecord.setUpdateby(UserUtils.getUser().getId());
        massSendRecord.setDelflag(Constants.DEL_FLAG_0);
        massSendrecordService.save(massSendRecord);
        return rtnJson;
    }
}
