package com.kingdee.eas.custom.integration.feishu.app;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.integration.base.config.AppConfig;
import com.kingdee.eas.custom.integration.base.util.SpringContextHolder;
import com.kingdee.eas.custom.integration.base.service.IntegrationConfigService;
import com.kingdee.eas.custom.integration.feishu.FeishuMessageInfo;
import com.kingdee.eas.custom.integration.feishu.bizEnum.MsgTypeEnum;
import com.kingdee.eas.custom.integration.feishu.bizEnum.SyncStatusEnum;
import com.kingdee.shr.base.syssetting.api.bean.SHRCodingRule;
import com.kingdee.shr.base.syssetting.util.NumberRuleHelper;
import com.kingdee.util.DateTimeUtils;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.text.MessageFormat;
import java.util.Date;

/**
 * 飞书消息
 */
public class FeishuMessageControllerBean extends AbstractFeishuMessageControllerBean {
    private static Logger logger = Logger.getLogger(FeishuMessageControllerBean.class);

    @Override
    protected IObjectPK _save(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        IObjectPK iObjectPK = super._save(ctx, model);
        //同步飞书消息
        syncMessage(ctx, iObjectPK.toString());
        return iObjectPK;
    }

    /**
     * 新增
     *
     * @param ctx
     * @param model
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected IObjectPK _addnew(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        FeishuMessageInfo feishuMessageInfo = (FeishuMessageInfo) model;
        feishuMessageInfo.setBizDate(DateTimeUtils.truncateDate(new Date()));
        String number = feishuMessageInfo.getNumber();
        if (StringUtils.isBlank(number)) {
            try {
                SHRCodingRule shrCodingRule = NumberRuleHelper.getCodingNumber(ctx, feishuMessageInfo, "00000000-0000-0000-0000-000000000000CCE7AED4");
                feishuMessageInfo.setNumber(shrCodingRule.getCodingRuleNumber());
            } catch (Exception e) {
                e.printStackTrace();
                throw new BOSException("生成飞书消息记录编码失败，请检查规则定义是否存在 : " + e.getMessage());
            }
        }
        //重置状态
        feishuMessageInfo.setSyncStatus(SyncStatusEnum.UNSYNC);
        return super._addnew(ctx, feishuMessageInfo);
    }

    /**
     * 同步飞书消息
     *
     * @param ctx
     * @param billId
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _syncMessage(Context ctx, String billId) throws BOSException, EASBizException {
        logger.info("同步飞书消息, billId: " + billId);
        //获取默认配置
        //IFeishuConfig iFeishuConfig = FeishuConfigFactory.getLocalInstance(ctx);
        //获取飞书应用默认配置
        IntegrationConfigService integrationConfigService = SpringContextHolder.getBean(IntegrationConfigService.class);
        AppConfig appConfig = integrationConfigService.getPrimaryApp("feishu");
        if (appConfig == null) {
            throw new BOSException("没有获取到飞书应用默认配置!");
        }
        if (!appConfig.isPushBusinessMessage()) {
            logger.error("同步飞书消息 不推送, billId: " + billId);
            return;
        }
        //更新字段
        SelectorItemCollection updateSic = new SelectorItemCollection();
        updateSic.add("syncStatus");
        updateSic.add("syncResult");
        //查询字段
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("receive.feishuUserId");
        //sic.add("receive.person.idmusercode");
        //sic.add("receive.person.number");
        //飞书消息
        FeishuMessageInfo feishuMessageInfo = getFeishuMessageInfo(ctx, new ObjectUuidPK(billId), sic);
        try {
            //消息接收人
            UserInfo receive = feishuMessageInfo.getReceive();
//                PersonInfo personInfo = receive.getPerson();
//                if (personInfo == null) {
//                    throw new BOSException("消息接收人用户 [" + receive.getNumber() + "] 没有实际操作人");
//                }
//                String iDMUserCode = personInfo.getString("idmusercode");
//                if (StringUtils.isBlank(iDMUserCode)) {
//                    throw new BOSException("消息接收人 [" + personInfo.getNumber() + "]的IDM用户编码为空!");
//                }
            //飞书userId
            String feishuUserId = receive.getString("feishuUserId");
            if (StringUtils.isBlank(feishuUserId)) {
                throw new BOSException("消息接收人用户 [" + receive.getNumber() + "]的飞书userId为空!");
            }
            //消息内容
            String content = feishuMessageInfo.getContent();
            if (StringUtils.isBlank(content)) {
                throw new BOSException("消息内容为空!");
            }
            //消息类型
            MsgTypeEnum msgType = feishuMessageInfo.getMsgType();
            if (msgType == null) {
                throw new BOSException("消息类型为空!");
            }
            // 构建client
            Client client = Client.newBuilder(appConfig.getAppId(), appConfig.getAppSecret()).build();

            // 创建请求对象
            CreateMessageReq req = CreateMessageReq.newBuilder()
                    .receiveIdType("user_id")
                    .createMessageReqBody(CreateMessageReqBody.newBuilder()
                            .receiveId(feishuUserId)
                            .msgType(msgType.getValue())
                            .content(content)
                            .uuid(feishuMessageInfo.getId().toString())//id,去重
                            .build())
                    .build();

            // 发起请求
            CreateMessageResp result = client.im().v1().message().create(req);
            logger.info("同步飞书消息请求结果: " + Jsons.DEFAULT.toJson(result.getData()));

            // 处理服务端错误
            if (!result.success()) {
                String msgFormat = "错误码: {0}\n报错信息: {1}\n完整错误信息: {2}";
                throw new BOSException(MessageFormat.format(msgFormat, result.getCode(), result.getMsg(), result.getError()));
            }
            // 成功,业务数据处理
            feishuMessageInfo.setSyncStatus(SyncStatusEnum.SUCCESS);
            feishuMessageInfo.setSyncResult(result.getMsg());
        } catch (Exception e) {
            logger.error("同步飞书消息失败: " + e.getMessage(), e);
            feishuMessageInfo.setSyncStatus(SyncStatusEnum.FAIL);
            feishuMessageInfo.setSyncResult(e.getMessage());
        }
        //更新
        updatePartial(ctx, feishuMessageInfo, updateSic);
    }
}