package com.gic.haoban.manage.web.controller.content;

import java.util.ArrayList;
import java.util.List;

import com.gic.haoban.manage.api.qdto.combined.CombinedQDTO;
import com.gic.haoban.manage.web.qo.combined.CombinedQO;
import com.gic.haoban.manage.web.qo.combined.CombinedsQO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.app.customer.dto.CustomerDTO;
import com.gic.haoban.app.customer.dto.MemberInfoListParamsDTO;
import com.gic.haoban.app.customer.service.api.service.DistributeApiService;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.ContentMaterialDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.service.MaterialApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.web.controller.WebBaseController;
import com.gic.haoban.manage.web.qo.CustomerQO;
import com.gic.haoban.manage.web.utils.ClerkUtils;

@RestController
public class QwMessageController extends WebBaseController {
    private final Logger logger = LogManager.getLogger(QwMessageController.class);
    @Autowired
    private DistributeApiService distributeApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService ;
    @Autowired
    private MaterialApiService materialApiService ;

    /**
     *  群发-分享 - 店员和店长
     */
    @RequestMapping("/message-send")
    public RestResponse<Object> messageSend(CustomerQO qo, String imgJson, String selectedStoreId , Long contentMaterialId) {
        CustomerDTO params = EntityUtil.changeEntityByJSON(CustomerDTO.class, qo);
        String clerkId = qo.getClerkId();
        String wxEnterpriseId = qo.getWxEnterpriseId();
        String enterpriseId = qo.getEnterpriseId();
        String searchParams = qo.getSearchParams();
        String staffId = qo.getStaffId();
        List<String> memberIdList = qo.getMemberIdList();
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId);
        String storeId = ClerkUtils.getClerkStore(clerk, clerkId, selectedStoreId);
        // 店长参数
        params.setStoreId(storeId);
        params.setEnterpriseId(enterpriseId);
        params.setClerkId(clerkId);
        MemberInfoListParamsDTO memberInfoListParamsDTO = com.gic.haoban.common.utils.StringUtil.getBean(searchParams,
                MemberInfoListParamsDTO.class);
        params.setQwFriendFlag(true);
        List<String> sendMemberIds = distributeApiService.getMemberIds(params, memberIdList, memberInfoListParamsDTO);
        if (CollectionUtils.isEmpty(sendMemberIds)) {
            return RestResponse.failure("-1","无会员数据");
        }
        List<String> staffIdList = new ArrayList<>();
        if (clerk.getClerkType() == 1) {
            staffIdList = staffApiService.listBindStaffId(storeId);
            logger.info("店长,成员数={}",staffIdList);
        } else if(clerk.getClerkType()==0) {
            StaffClerkRelationDTO dto = this.staffClerkRelationApiService.getOneByClerkId(clerkId) ;
            if(null != dto) {
                logger.info("店员关联的成员={}",dto.getStaffId());
                staffIdList.add(dto.getStaffId());
            }
        }
        if(CollectionUtils.isEmpty(staffIdList)) {
            return RestResponse.failure("-1","无成员数据");
        }
        JSONObject json = new JSONObject();
        json.put("userIdList", staffIdList);
        json.put("sendMemberIds", sendMemberIds);
        json.put("enterpriseId", enterpriseId);
        json.put("imgJson", imgJson);
        json.put("storeId", storeId);
        json.put("staffId", staffId);
        json.put("content", qo.getContent()) ;
        json.put("contentMaterialId", contentMaterialId) ;
        json.put("sendClerkId", clerkId);
        // 群发-分享
        json.put("sendType", 1);
        json.put("wxEnterpriseId", wxEnterpriseId);
        String ret = json.toJSONString();
        try {
            GICMQClientUtil.getClientInstance().sendCommonMessage("haobanCommonRouter", ret,
                    "com.gic.haoban.app.customer.service.api.service.MessageLogApiService", "callBackSendMessage");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return RestResponse.successResult();
    }
    
    // 朋友圈任务 - 店长和区经
    @RequestMapping("/add_moment_task")
    public RestResponse<Object> share(CustomerQO qo, String imgJson ,Long contentMaterialId , String searchParams) {
        String clerkId = qo.getClerkId();
        String wxEnterpriseId = qo.getWxEnterpriseId();
        String enterpriseId = qo.getEnterpriseId();
        String staffId = qo.getStaffId();
        List<String> clerkIdList = qo.getClerkIdList() ;
        List<String> storeIdList = qo.getStoreIdList() ;
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId);
        logger.info("clerkType={},ChooseAll={}",clerk.getClerkType(),qo.getChooseAll());
        int clerkType = clerk.getClerkType() ;
        if(clerkType==0) {
            return RestResponse.failure("-1","非店长、区经");
        }
        String chooseAll = qo.getChooseAll() ;
        if(StringUtils.isBlank(chooseAll) || !"1".equals(chooseAll)) {
            if(clerkType==1 && CollectionUtils.isEmpty(clerkIdList)) {
                return RestResponse.failure("-1","请选择导购");
            }
            if(clerkType==2 && CollectionUtils.isEmpty(storeIdList)) {
                return RestResponse.failure("-1","请选择门店");
            }
        }else {
            storeIdList = null ;
        }
        JSONObject json = new JSONObject();
        json.put("clerkIdList", clerkIdList);
        json.put("storeIdList", storeIdList) ;
        json.put("searchParams", searchParams) ;
        json.put("enterpriseId", enterpriseId);
        json.put("imgJson", imgJson);
        json.put("staffId", staffId);
        json.put("sendClerkId", clerkId);
        json.put("sendClerkType", clerkType) ;
        json.put("sendClerkStoreId", clerk.getStoreId());
        // 朋友圈-分享
        json.put("sendType", 2);
        json.put("wxEnterpriseId", wxEnterpriseId);
        json.put("content", qo.getContent()) ;
        json.put("contentMaterialId", contentMaterialId) ;
        String params = json.toJSONString();
        try {
            GICMQClientUtil.getClientInstance().sendCommonMessage("haobanCommonRouter", params,
                    "com.gic.haoban.app.customer.service.api.service.MessageLogApiService", "callBackSendMessage");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return RestResponse.successResult();
    }
    
    // 1群发 2朋友圈
    @RequestMapping("get-qw-materialid")
    public RestResponse<Object> getMaterialId(String wxEnterpriseId,String imgUrl , int materialType , @RequestParam(defaultValue="2")int mediaType) {
        ContentMaterialDTO dto = new ContentMaterialDTO();
        dto.setImgUrl(imgUrl);
        dto.setMediaType(mediaType);
        dto.setMaterialType(materialType);
        ServiceResponse<String> resp = this.materialApiService.getMaterialId(wxEnterpriseId, dto) ;
        if(resp.isSuccess()) {
            return RestResponse.successResult(resp.getResult()) ;
        }
        return RestResponse.failure("-1", resp.getMessage()) ;
    }

    @RequestMapping("combined-qw-materialid")
    public RestResponse<Object> combinedMaterialId(@RequestBody CombinedQO combinedQO) {
        String wxEnterpriseId = combinedQO.getWxEnterpriseId();
        CombinedQDTO combinedQDTO = com.gic.commons.util.EntityUtil.changeEntityNew(CombinedQDTO.class, combinedQO);
        ServiceResponse<String> resp = this.materialApiService.getMaterialIdByCombined(wxEnterpriseId, combinedQDTO) ;
        if(resp.isSuccess()) {
            return RestResponse.successResult(resp.getResult()) ;
        }
        return RestResponse.failure("-1", resp.getMessage()) ;
    }

}
