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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.YwWxEnterpriseDTO;
import com.gic.haoban.manage.api.enums.QuartzEnum;
import com.gic.haoban.manage.api.enums.SyncTaskTypeEnum;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.api.service.fee.HaobanQywxFeeApiService;
import com.gic.haoban.manage.api.service.role.HaobanRoleApiService;
import com.gic.haoban.manage.web.controller.WebBaseController;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.member.tag.api.service.MemberTagImportDealService;
import com.gic.mq.sdk.GicMQClient;
import com.gic.redis.data.util.RedisUtil;
import com.gic.sharing.core.service.api.service.MqApiService;
import com.task.allocation.qo.AllocationTaskQo;
import com.task.allocation.qo.TaskAllocationComputed;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
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.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created 2018/12/17.
 *
 * @author hua
 */
@Controller
@RequestMapping("/test")
public class TestController extends WebBaseController {

    private static final Logger logger = getLogger(TestController.class);
    @Autowired
    private TestApiService testApiService;

    @Autowired
    private MqApiService mqApiService;

    @Autowired
    private StaffApiService staffApiService;

    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;

    @Autowired
    private MemberTagImportDealService memberTagImportDealService;
    @Autowired
    private HaobanQywxFeeApiService haobanQywxFeeApiService;
    @Autowired
    private ExternalClerkRelatedApiService externalClerkRelatedApiService;
    @Autowired
    private HaobanRoleApiService haobanRoleApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;

    /**
     * 创建定时器
     *
     * @return
     */
    @RequestMapping("/create-quarter_key")
    @ResponseBody
    public HaobanResponse createQuarterKey(String key) {
        QuartzEnum quartzEnum = QuartzEnum.getByKey(key);
        if (null == quartzEnum) {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
        testApiService.quartzTaskConvert(quartzEnum.getServiceName(), quartzEnum.getMethod(), quartzEnum.getCron(), quartzEnum.getParams(), null);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 创建定时器
     *
     * @return
     */
    @RequestMapping("/create-quarter")
    @ResponseBody
    public HaobanResponse createQuarter(String serviceName, String methodName, String cron, String params, String referId) {
        if (StringUtils.isAnyBlank(serviceName, methodName, cron)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        testApiService.quartzTaskConvert(serviceName, methodName, cron, params, referId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    /**
     * 删除定时器
     *
     * @return
     */
    @RequestMapping("/del-quarter")
    @ResponseBody
    public HaobanResponse delQuarter(String serviceName, String methodName, String referId) {
        if (StringUtils.isAnyBlank(serviceName, methodName, referId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        testApiService.delQuartzTask(serviceName, methodName, referId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("/sharing-import")
    @ResponseBody
    public HaobanResponse sharingImport(String key) {
        if (StringUtils.isBlank(key)) {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
        mqApiService.run(key);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("/sharing-import-batch")
    @ResponseBody
    public HaobanResponse sharingImportBatch(String key) {
        if (StringUtils.isBlank(key)) {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
        JSONArray jsonArray = JSONArray.parseArray(key);
        int num = jsonArray.size();
        int i = 0;
        for (Object obj : jsonArray) {
            i = i + 1;
            logger.info("执行num:" + i + ":total" + num);
            mqApiService.run(JSONObject.toJSONString(obj));
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 刷新好友
     *
     * @return
     */
    @RequestMapping("/flush-friend-batch")
    @ResponseBody
    public HaobanResponse flushFriend(String key) {
        if (StringUtils.isBlank(key)) {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
        String[] split = key.split(",");
        for (String staffId : split) {
            StaffDTO staff = staffApiService.selectById(staffId);
            if (null == staff) {
                continue;
            }
            String wxEnterpriseId = staff.getWxEnterpriseId();
            String taskName = "刷新企业微信好友（" + staff.getStaffName() + "）";
            String taskId = dealSyncOperationApiService.createWxFriendTaskSingle(staff.getWxEnterpriseId(), taskName, staffId, staff.getStaffName(), SyncTaskTypeEnum.FRIEND_SINGLE.getType());
            if (StringUtils.isNotBlank(taskId)) {
                dealSyncOperationApiService.dealWxFriendClerkSingle(taskId, staffId, staffId, wxEnterpriseId);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 刷新单个标签同步到队列
     *
     * @return
     */
    @RequestMapping("/qywx-tag-mq")
    @ResponseBody
    public HaobanResponse qywxTagMq(String key) {
        if (StringUtils.isBlank(key)) {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
        JSONArray jsonArray = JSONArray.parseArray(key);
        List<String> mqList = jsonArray.stream().map(qo -> JSONObject.toJSONString(qo)).collect(Collectors.toList());

        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            clientInstance.sendBatchMessages("qywxTagSyncDeal", mqList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("批量异常：{}", e);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 刷新单个标签同步到队列
     *
     * @return
     */
    @RequestMapping("/memberTag")
    @ResponseBody
    public HaobanResponse memberTag(String id, String tagId) {
        AllocationTaskQo taskQo = new AllocationTaskQo();
        taskQo.setType(AllocationTaskQo.COMPUTED);
        taskQo.setTaskAllocationId(id);

        TaskAllocationComputed task = new TaskAllocationComputed();
        task.setTaskAllocationId(id);
        task.setTaskSignKey(tagId);
        task.setTaskStatus(TaskAllocationComputed.TASK_STATUS_SUCCESS);
        taskQo.setParams(JSONObject.toJSONString(task));

        memberTagImportDealService.run(JSONObject.toJSONString(taskQo));
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 刷新整个企业好友
     *
     * @param wxEnterpriseId
     * @return
     */
    @RequestMapping("/flash-friend-wxEnterpriseId")
    public HaobanResponse sendStockMemberRelationMessage(String wxEnterpriseId) {
        if (org.apache.commons.lang.StringUtils.isEmpty(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        // 异步调用
        this.externalClerkRelatedApiService.initWxEnterpriseFriend(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 收费
     *
     * @param wxEnterpriseId
     * @return
     */
    @RequestMapping("/addFee")
    public HaobanResponse addFee(String wxEnterpriseId) {
        haobanQywxFeeApiService.addFee(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("/addHaobanRoleByWxEnterpriseId")
    public HaobanResponse addHaobanRoleByWxEnterpriseId(String wxEnterpriseId) {
        haobanRoleApiService.addHaobanRole(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("/addHaobanRoleInit")
    public HaobanResponse addHaobanRoleInit(String wxEnterpriseId) {
        haobanRoleApiService.addHaobanRoleInit(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("/addHaobanRoleInitAll")
    public HaobanResponse addHaobanRoleInitAll() {
        List<YwWxEnterpriseDTO> ywWxEnterpriseDTOS = wxEnterpriseApiService.listAll();
        for (YwWxEnterpriseDTO ywWxEnterpriseDTO : ywWxEnterpriseDTOS) {
            haobanRoleApiService.addHaobanRoleInit(ywWxEnterpriseDTO.getWxEnterpriseId());
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    @RequestMapping("/get-cache")
    public Object getCache(String key) {
        Object o = RedisUtil.getCache(key) ;
        return o ;
    }

    @RequestMapping("/del-cache")
    public Object delCache(String key) {
        Object o = RedisUtil.getCache(key) ;
        if(null != o) {
            RedisUtil.delCache(key);
        }
        return o ;
    }
}
