package cn.ibizlab.businesscentral.core.extensions.service;

import cn.ibizlab.businesscentral.core.odoo_base.domain.Res_partner;
import cn.ibizlab.businesscentral.core.odoo_base.service.IRes_partnerService;
import cn.ibizlab.businesscentral.core.odoo_mail.domain.Mail_message;
import cn.ibizlab.businesscentral.core.odoo_mail.service.impl.Mail_messageServiceImpl;
import cn.ibizlab.businesscentral.core.util.helper.EBSServiceImpl;
import cn.ibizlab.businesscentral.util.domain.EntityMP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Slf4j
@Primary
@Service("Mail_messageExService")
public class Mail_messageExService extends Mail_messageServiceImpl {

    @Autowired
    IRes_partnerService res_partnerService ;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    @Transactional
    public <T extends EntityMP> void add_default_create_message(EBSServiceImpl service, T et) {
        Mail_message message = new Mail_message();
        message.setModel(service.getIrModel());
        message.setResId(((Long) et.get("id")).intValue());
        message.setBody(service.getIrModel() + " create");
        message.setSubtypeId(2l);
        message.setMessageType("notification");

        Res_partner res_partner = res_partnerService.get(3l);
        message.setAuthorId(res_partner.getId());
        message.setEmailFrom(String.format("\"%s\" <%s>", res_partner.getName(), res_partner.getEmail()));
        message.setReplyTo("");
        message.setAddSign(true);
        message.setWebsitePublished(true);
        this.create(message);
    }

    @Override
    public Mail_message generate_tracking_message_id(Mail_message et) {
        System.out.println(System.currentTimeMillis()/1000);

        et.setMessageId(String.format("<%s.%s.%s-openerp-%s@%s>",getRandom(),System.currentTimeMillis()/1000,getRandom(),et.getMessageId(),"a3f3484997ea"));
        return super.generate_tracking_message_id(et);
    }

    static private String getRandom(){
        Random random = new Random(System.currentTimeMillis());
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < 15; i++) {
            int num = random.nextInt(9);
            str.append(num);
        }
        return str.toString();
    }

}
