package com.zcloud.safetyDutyList.command.tasklist;

import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.safetyDutyList.domain.enums.SwitchFlagEnum;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskListGateway;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskListE;
import com.zcloud.safetyDutyList.dto.clientobject.tasklist.TaskListCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskListAddCmd;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 清单新增执行器
 * <p>
 * 处理新增安全责任清单的业务逻辑：
 *   1. 创建清单实体，初始化开关为开启
 *   2. 保存清单到数据库
 *   3. 返回新增后的清单信息
 */
@Component
@AllArgsConstructor
public class TaskListAddExe {
    private final TaskListGateway taskListGateway;

    @Transactional(rollbackFor = Exception.class)
    public TaskListCO execute(TaskListAddCmd cmd) {

        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser == null) {
            throw new BizException("用户未登录");
        }

        TaskListE taskListE = new TaskListE();
        BeanUtils.copyProperties(cmd, taskListE);
        taskListE.init();

        // 创建者信息
        taskListE.setCreateCorpId(ssoUser.getTenantId());
        taskListE.setCreateDepartmentId(ssoUser.getOrgId());
        taskListE.setCreateUserId(ssoUser.getUserId());

        taskListE.setSwitchFlag(SwitchFlagEnum.ON.getCode());
        boolean res = taskListGateway.add(taskListE);
        if (!res) {
            throw new BizException("保存失败");
        }

        TaskListCO co = new TaskListCO();
        BeanUtils.copyProperties(taskListE, co);
        return co;
    }
}
