package com.mortals.xhx.module.workman.service.impl;

import com.mortals.framework.common.code.UserType;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.workman.dao.WorkmanDao;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.service.WorkmanService;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * WorkmanService
 * 工作人员 service实现
 *
 * @author zxfei
 * @date 2022-01-12
 */
@Service("workmanService")
public class WorkmanServiceImpl extends AbstractCRUDServiceImpl<WorkmanDao, WorkmanEntity, Long> implements WorkmanService {

    @Autowired
    private UserService userService;

    @Override
    protected void saveBefore(WorkmanEntity entity, Context context) throws AppException {
        //新增 添加
        try {
            UserEntity userEntity = new UserEntity();
            userEntity.initAttrValue();
            userEntity.setRealName(entity.getName());
            userEntity.setLoginName(entity.getUserName());
            userEntity.setLoginPwd(SecurityUtil.md5DoubleEncoding(entity.getPassword()));
            userEntity.setMobile(entity.getMobile());
            userEntity.setUserType(2);
            userEntity.setCreateTime(new Date());
            userEntity.setCreateUser(context.getUser().getLoginName());
            userEntity.setCreateUserName(context.getUser().getRealName());
            userEntity.setSiteId(entity.getSiteId());
            userEntity.setSiteName(entity.getSiteName());
            userService.save(userEntity);
            entity.setSystemUserId(userEntity.getId());
        } catch (Exception e) {
            log.error("创建工作人员异常！", e);
            throw new AppException();
        }
        super.saveBefore(entity, context);
    }


    @Override
    protected void updateBefore(WorkmanEntity entity, Context context) throws AppException {
        if (!ObjectUtils.isEmpty(entity.getSystemUserId())) {
            try {
                UserEntity userEntity = userService.get(entity.getSystemUserId(), context);
                userEntity.setLoginPwd(SecurityUtil.md5DoubleEncoding(entity.getPassword()));
                userService.update(userEntity, context);
            } catch (Exception e) {
                log.error("更新密码异常", e);
            }
        }
        super.updateBefore(entity, context);
    }
}