package cn.com.ctop.kuaishou.modules.ai.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouMaterialPoolOperationRecord;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouMaterialPoolOperationRecordMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouMaterialPoolOperationRecordService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 物料池操作记录表
 *
 * @author jeecg-boot
 * 2021-07-19
 * @version V1.0
 */
@Slf4j
@Service
public class KuaishouMaterialPoolOperationRecordServiceImpl extends ServiceImpl<KuaishouMaterialPoolOperationRecordMapper, KuaishouMaterialPoolOperationRecord> implements IKuaishouMaterialPoolOperationRecordService {

    @Autowired
    private KuaishouMaterialPoolOperationRecordMapper operationRecordMapper;

    static ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Override
    public void addRecord(JSONObject data, String methodName, Integer materialType, String type) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            insertInfo(data, methodName, materialType, type);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                log.info("添加物料池操作记录完成");
            }
        };
        thread.start();
    }

    private void insertInfo(JSONObject data, String methodName, Integer materialType, String type) {
        KuaishouMaterialPoolOperationRecord record = new KuaishouMaterialPoolOperationRecord();
        record.setData(JSONObject.toJSONString(data));
        record.setMethod_name(methodName);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!Check.isNull(user)) {
            record.setUserId(user.getId());
        }
        record.setProjectId(data.getLong("projectId"));
        record.setMaterialType(materialType);
        record.setType(type);
        operationRecordMapper.insert(record);
    }
}
