package com.mortals.xhx.common.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.common.code.PerformTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.dingding.CheckDingMsg;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.mortals.xhx.module.perform.model.PerformAttendAppealEntity;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffService;
import com.mortals.xhx.utils.SpringUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;


@RequiredArgsConstructor
@Slf4j
public class SendAppealDingDingMsgThread implements Runnable {

    private IDingPersonService dingPersonService;

    private StaffService staffService;

    private MessageService messageService;

    @NonNull
    private PerformAttendAppealEntity entity;


    @Override
    public void run() {
        String ruleStr = String.format("%s/%s/%s", PerformTypeEnum.考勤绩效.getDesc(), entity.getCategoryName(), entity.getRuleName());

        dingPersonService = SpringUtils.getBean(IDingPersonService.class);
        staffService = SpringUtils.getBean(StaffService.class);
        messageService = SpringUtils.getBean(MessageService.class);

        StaffEntity staffCache = staffService.getCache(entity.getStaffId().toString());
        Rest<String> personRest = dingPersonService.getPersonByMobile(staffCache.getPhoneNumber());
        if (YesNoEnum.YES.getValue() == personRest.getCode()) {
            CheckDingMsg checkDingMsg = new CheckDingMsg();
            checkDingMsg.setUserIds(personRest.getData());
            checkDingMsg.setDateTime(DateUtil.formatDateTime(entity.getAppealTime() == null ? new Date() : entity.getAppealTime()));
            checkDingMsg.setRuleStr(ruleStr);
            checkDingMsg.setScore(entity.getScore().toString());
            checkDingMsg.setAppealResult(entity.getAppealResult());
            checkDingMsg.setAppealDesc(entity.getAppealDesc());


            Rest<String> msgRest = messageService.sendDingTalkAppealMsg(checkDingMsg);

            log.info("钉钉消息发送结果：{}", JSONObject.toJSONString(msgRest));
        } else {
            log.error("根据手机号码获取人员错误，msg:{}", personRest.getMsg());
        }


    }

}
