package com.docus.server.collect.web.service;

import com.docus.core.util.Func;
import com.docus.log.annotation.TrackRetryListener;
import com.docus.server.record.common.pojo.dto.TBasicDTO;
import com.docus.server.record.service.ITBasicService;
import com.docus.server.sys.common.pojo.dto.DeptDTO;
import com.docus.server.sys.common.pojo.dto.UserDTO;
import com.docus.server.sys.service.IPowerDeptService;
import com.docus.server.sys.service.IPowerUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class CollectService {
    protected final static String DEL_TYPE = "D";
    @Resource
    private IPowerDeptService deptService;
    @Resource
    private IPowerUserService userService;
    @Resource
    private ITBasicService tBasicService;

    /**
     * 科室数据
     */
    @TrackRetryListener("dept")
    public void insertOrUpdateDept(DeptDTO deptDTO) {
        //异步写入归档系统，失败自动重试。
        if (checkType(deptDTO.getOperateType(), DEL_TYPE)) {
            deptService.delDeptByDeptCode(deptDTO.getDeptCode());
        } else {
            deptService.insertOrUpdatePowerDept(deptDTO);
        }
    }

    /**
     * 用户信息
     *
     * @see TrackRetryListener 重试监听器
     */
    @TrackRetryListener("user")
    public void insertOrUpdateUser(UserDTO userDTO) {
        // 判断操作类型
        if (checkType(userDTO.getOperateType(), DEL_TYPE)) {
            userService.delUserByUserName(userDTO.getUserName());
        } else {
            userService.insertOrUpdatePowerUser(userDTO);
        }
    }

    /**
     * 基础数据
     */
    @TrackRetryListener("basic")
    public void insertOrUpdateBasic(TBasicDTO tBasicDTO) {
        Integer num = tBasicService.findByJzh(tBasicDTO.getJzh());
        if (num > 0) {
            tBasicService.updateTBasic(tBasicDTO);
        } else {
            tBasicService.insertTBasic(tBasicDTO);
        }
    }


    protected boolean checkType(String operateType, String delType) {
        return Func.isNotEmpty(operateType)
            && operateType.contains(delType);
    }
}
