package com.usoftchina.uas.office.dingtalk.listener;

import com.usoftchina.dingtalk.sdk.MessageSdk;
import com.usoftchina.dingtalk.sdk.dto.SendMessageReq;
import com.usoftchina.dingtalk.sdk.util.UrlUtils;
import com.usoftchina.uas.office.context.MasterHolder;
import com.usoftchina.uas.office.dingtalk.entity.Employee;
import com.usoftchina.uas.office.dingtalk.entity.JProcess;
import com.usoftchina.uas.office.dingtalk.manage.entity.DingTalkAgent;
import com.usoftchina.uas.office.dingtalk.manage.service.DingTalkAgentService;
import com.usoftchina.uas.office.dingtalk.service.UasEmployeeService;
import com.usoftchina.uas.office.dingtalk.service.UasJProcessService;
import com.usoftchina.uas.office.dto.UasEvent;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.listener.UasEventListener;
import com.usoftchina.uas.office.util.Try;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.List;

/**
 * @author yingp
 * @date 2020/2/16
 */
@Component
public class UasProcessListener {

    @Autowired
    private MessageSdk messageSdk;

    @Autowired
    private UasJProcessService jProcessService;

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

    @Autowired
    private DingTalkAgentService agentService;

    @Autowired
    private UasEmployeeService employeeService;

    /**
     * uas保存审批任务，发送消息到钉钉
     *
     * @param event
     */
    @UasEventListener(caller = "JProcess", operation = "SAVE")
    public void onProcessSave(UasEvent event) {
        if (event.getKey() instanceof List) {
            List<Integer> jpIdList = (List<Integer>) event.getKey();
            jpIdList.forEach(jpId -> {
                sendProcessMessage(event, jpId);
            });
        } else {
            sendProcessMessage(event, (int) event.getKey());
        }
    }

    private void sendProcessMessage(UasEvent event, Integer jpId) {
        JProcess process = Try.call(() -> jProcessService.getById(jpId), 10);
        if (null == process) {
            logger.warn("can not find process {}, {}", jpId, event);
            return;
        }
        Employee employee = getDealMan(process);
        if (null == employee) {
            return;
        }
        DataCenter dataCenter = DataCenter.INSTANCE;
        String title = process.getJp_launchername() + "的" + process.getJp_name();
        String description = "单据编号:" + process.getJp_codevalue();
        try {
            // 往uas应用发送
            DingTalkAgent agent = getUasAgent();
            String paramsStr = "{\"master\":\"" + event.getMaster() + "\",\"nodeId\":" + process.getJp_nodeid() + ",\"baseUrl\":\"" + URLEncoder.encode(agent.getOuterUrl(), "utf-8") + "\"}";
            String msgUrl = UrlUtils.generateAuthUrl(messageSdk.getCorpId(), event.getMaster(), "Uas", agent.getOuterUrl(),
                    dataCenter.getOuterUrl() + "authorize", "uas/approval/" + URLEncoder.encode(paramsStr, "utf-8"));
            messageSdk.send("Uas", new SendMessageReq()
                    .actionCard(title, description, msgUrl)
                    .toUser(employee.getEm_ding()));
        } catch (Exception e) {
            logger.error("send process message error", e);
        }
    }

    public Employee getDealMan(JProcess process) {
        try {
            DataSourceHolder.set(DataCenter.INSTANCE);
            Employee employee = employeeService.getByCode(process.getJp_nodedealman());
            if (null == employee || null == employee.getEm_ding()) {
                return null;
            }
            return employee;
        } finally {
            DataSourceHolder.set(MasterHolder.get());
        }
    }

    public DingTalkAgent getUasAgent() {
        try {
            DataSourceHolder.set(DataCenter.INSTANCE);
            return agentService.findByCode("Uas");
        } finally {
            DataSourceHolder.set(MasterHolder.get());
        }
    }
}
