package com.docus.server.collect.user.view;

import com.docus.core.util.DateUtil;
import com.docus.core.util.Func;
import com.docus.core.util.ListUtils;
import com.docus.log.annotation.TrackRetryListener;
import com.docus.server.collect.ICollector;
import com.docus.server.collect.web.job.AbstractCollectJob;
import com.docus.server.entity.TaskConfig;
import com.docus.server.his.service.IHisService;
import com.docus.server.sys.common.pojo.dto.UserDTO;
import com.docus.server.sys.common.pojo.entity.PowerDept;
import com.docus.server.sys.common.pojo.entity.PowerThirdLogin;
import com.docus.server.sys.common.pojo.entity.PowerUser;
import com.docus.server.util.PeriodTime;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 主动view请求用户数据job
 *
 * @see AbstractCollectJob
 * @see com.docus.server.collect.IJob
 * @see ICollector
 */
@Component
public class UserViewCollectJob extends AbstractCollectJob<UserDTO> {
    @Resource
    private IHisService hisService;

    /**
     * xxl jobhandler 手工执行，全量执行
     */
    @XxlJob("startAllUserViewCollect")
    @TrackRetryListener("startAllUserViewCollect")
    public void startAllUserViewCollect(String param) {
        super.startCollectAll(getJobParam(param));
    }

    /**
     * xxl jobhandler 配置定时启动，如果未完成任务跳过。增量收集
     */
    @XxlJob("startIncUserViewCollect")
    @TrackRetryListener("startIncUserViewCollect")
    public void startIncUserViewCollect(String param) {
        super.startCollectIncrement(getJobParam(param));
    }

    @Override
    public void doHandle(List<UserDTO> results, String param) {
        //docus-BasicDataReceive同步user逻辑
        Collection<Object> userNames = ListUtils.distinctSelect(results, UserDTO::getUserName);
        List<PowerUser> powerUsers = userService.findByUserNameList(userNames);
        List<String> existUserNames = ListUtils.distinctSelect(powerUsers, PowerUser::getUserName);

        results.forEach(p -> {
            String userName = p.getUserName();
            String pwd = p.getPwd();
            if (existUserNames.contains(userName)) {
                thirdLoginService.updateThirdLogin(pwd, userName);
            } else {
                insertUserAndThirdLogin(p, userName);
            }
        });
    }

    @Override
    public List<UserDTO> execute(PeriodTime periodTime, TaskConfig taskConfig) {
        //每家医院按照固定的格式写sql，不同医院需要替换不同的sql即可。
        return hisService.getUserListView(periodTime.getPeriodStartDate(), periodTime.getPeriodEndDate(),
            taskConfig.getPageNum(), taskConfig.getPageSize());
    }

    private void insertUserAndThirdLogin(UserDTO userDTO, String userName) {

        if (Func.isEmpty(userDTO.getAuthorId())) {
            userDTO.setAuthorId("admin");
        }
        if (Func.isEmpty(userDTO.getAuthorName())) {
            userDTO.setAuthorName("admin");
        }

        if (Func.isNotBlank(userDTO.getDeptId())) {
            PowerDept powerDept = deptService.findByDeptCode(userDTO.getDeptId());
            if (!Objects.isNull(powerDept)) {
                userDTO.setDeptId(String.valueOf(powerDept.getDeptId()));
            }
        }

        PowerUser powerUser = userService.findByUserName(userName);

        PowerThirdLogin powerThirdLogin = new PowerThirdLogin();
        powerThirdLogin.setId(idService.getDateSeq());
        powerThirdLogin.setUser("0");
        if (Func.notNull(powerUser)) {
            powerThirdLogin.setPowerUserId(String.valueOf(powerUser.getUserId()));
        }
        powerThirdLogin.setUser(userName);
        powerThirdLogin.setPwd(userDTO.getPwd());
        powerThirdLogin.setSource(0);
        powerThirdLogin.setCreateTime(DateUtil.now());

        userDTO.setPwd(userProperties.getPassword());

        userService.insertOrUpdatePowerUser(userDTO);
        thirdLoginService.savePowerThirdLogin(powerThirdLogin);
    }

}
