package com.cftech.mp.mass.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.util.Constants;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.mp.fans.service.MpFanssService;
import com.cftech.mp.mass.model.MassSendrecord;
import com.cftech.mp.mass.service.MassSendrecordService;
import com.cftech.sys.security.UserUtils;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.mp.api.wxsendmsg.model.SendMessageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @author 作者 lisw:
 * @version 创建时间：2016年10月25日 下午6:32:13 图文
 */
@Controller
@RequestMapping("/a/newsmedia")
public class NewsMediaController {

    private static final Logger logger = LoggerFactory
            .getLogger(NewsMediaController.class);

    @Autowired
    private MpAccountsService accountsService;


    @Autowired
    private MpFanssService fanssService;

    @Autowired
    private MassSendrecordService massSendrecordService;

    @Autowired
    private MpTokenUtil tokenUtil;


    /**
     * 群发接口
     *
     * @param mediaId
     * @return
     */
    @RequestMapping(value = "/uploadMediaArticle", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadMediaArticle(String mediaId,
                                         HttpServletRequest request, MassSendrecord massSendRecord, String storeIds) {
        JSONObject rtnJson = new JSONObject();
        Long accountsid = UserUtils.getmpaccounts(request);
        MpAccountsEntity entity = accountsService.getDetail(accountsid);
        SendMessageResponse responseMedia = null;
        String sex = request.getParameter("sex");
        String tags = request.getParameter("tags");
        try {
            String newsid = "";
            List<String> openids = new ArrayList<String>();
            massSendRecord.setNewMedias(mediaId);
            massSendRecord.setAccountsid(accountsid);
            massSendRecord.setCreateby(UserUtils.getUser().getId());
            massSendRecord.setUpdateby(UserUtils.getUser().getId());
            massSendRecord.setDelflag(Constants.DEL_FLAG_0);
            if (StringUtils.equals("0", massSendRecord.getSendType())) {// 全部
                responseMedia = JwSendMessageAPI.sendMessageToGroupOrAllWithMediaId(tokenUtil.getToken(accountsid), true, null, mediaId);
            } else if (StringUtils
                    .equals("1", massSendRecord.getSendType())) {// 按条件
                if(StringUtils.isNotBlank(storeIds)){
                    storeIds= storeIds.substring(0,storeIds.length()-1);
                }
                openids = fanssService
                        .fannsByArea(massSendRecord.getArea()
                                .replace("省", "").replace("市", ""), accountsid.toString(), sex, tags,storeIds);
                if(openids==null || openids.size()==0){
                    rtnJson.put("errorNo", "2");//未找到群发对象
                    return  rtnJson;
                }
                responseMedia = JwSendMessageAPI.sendMessageToOpenidsWithMediaId(tokenUtil.getToken(accountsid), openids, mediaId);
            } else {

            }
            if (responseMedia.getErrcode().equals("0")) {
                JSONObject whereJson = new JSONObject();
                if (StringUtils.isNotBlank(massSendRecord.getArea())) {
                    whereJson.put("area", massSendRecord.getArea());
                }
                if (StringUtils.isNotBlank(sex)) {
                    whereJson.put("sex", sex);
                }
                if(StringUtils.isNotBlank(tags)){
                    whereJson.put("tags",tags);
                }
                if(StringUtils.isNotBlank(storeIds)){
                    whereJson.put("storeIds",storeIds);
                }
                if (openids != null && openids.size() > 0) {
                    massSendRecord.setTousers(String.join(",", openids));
                }

                massSendRecord.setArea(whereJson.toString());
                massSendRecord.setMsgId(responseMedia.getMsg_id() != null ? Long.valueOf(responseMedia.getMsg_id()) : null);
                massSendRecord.setMsgDataId(responseMedia.getMsg_data_id() != null ? Long.valueOf(responseMedia.getMsg_data_id()) : null);
                massSendrecordService.save(massSendRecord);
                rtnJson.put("errorNo", "0");
            } else if(responseMedia.getErrcode().equals("40130")){
                rtnJson.put("errorNo", "4");//发送失败
            }else if(responseMedia.getErrcode().equals("45065")){
                rtnJson.put("errorNo", "5");//发送失败
            }else{
                rtnJson.put("errorNo", "1");
            }
        } catch (Exception e) {
            e.printStackTrace();

            rtnJson.put("errorNo", "1");
        }
        return rtnJson;
    }


}
