package com.testor.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.duty.model.domain.TSysDuty;
import com.testor.module.duty.service.DutyService;
import com.testor.module.emergency.model.domain.TEmergencyRehearsal;
import com.testor.module.emergency.service.TEmergencyRehearsalService;
import com.testor.module.safe.model.domain.TSafeHazardOrg;
import com.testor.module.safe.service.TSafeHazardOrgService;
import com.testor.module.sys.model.domian.SysUserExtend;
import com.testor.module.sys.model.dto.CustomerRemovalDto;
import com.testor.module.sys.service.SysUserExtendService;
import com.testor.module.sys.service.TSysUserService;
import com.tongtech.tfw.backend.common.models.exceptions.ServiceException;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.TodoListRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author rsq
 * @program zlmy_boot
 * @return
 **/
@Service
public class TSysUserServiceImpl implements TSysUserService {

    @Autowired
    private TSafeHazardOrgService tSafeHazardOrgService;

    @Autowired
    private TEmergencyRehearsalService tEmergencyRehearsalService;

    @Autowired
    private DutyService dutyService;

    @Autowired
    private WfTaskController wfTaskController;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TSysPostService tSysPostService;
    @Autowired
    private SysUserExtendService sysUserExtendService;

    @Override
    @Transactional(rollbackFor = Exception.class)

    public void customerRemoval(CustomerRemovalDto dto) {
        String userId = dto.getUserId();
        String newOrgId = dto.getNewOrgId();
        SysUser byId = sysUserService.getById(userId);
        if (byId == null) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("用户不存在").build());
        }
        //校验隐患台账是否有 整改人、验收人、指派人
        verificationLedger(userId);
        //校验未结束的应急演练
        checkDrill(userId);
        //校验值班列表
        checkWatch(userId);
        //校验代办
        verificationAgent(userId,byId.getOrgId());
        //执行用户迁移
        userMigration(newOrgId, byId, dto.getPostId(), dto.getDeptId(), dto.getDeputyPostId());
    }

    @Override
    public SysUser getUserByLoginName(String loginName) {
        return sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getLoginName,loginName));
    }

    @Override
    public String getUserNamesByUserIds(String userIds) {
        String[] split = new String[]{};
        if (StringUtils.isNotBlank(userIds)) {
            split = userIds.split(",");
        }
        List<String> userNames = new ArrayList<>();
        for (String userId : split) {
            SysUser sysUser = sysUserService.getById(userId);
            if (sysUser != null) {
                userNames.add(sysUser.getUserName());
            }
        }
        return String.join(",", userNames);
    }

    /**
     * 用户迁移
     *
     * @param newOrgId
     */
    private void userMigration(String newOrgId, SysUser byId, String postId, String deptId, String deputyPostId) {
        String userId = byId.getUserId();
        SysOrg newOrg = sysOrgService.getById(newOrgId);
        if (newOrg == null) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("迁移的机构不存在").build());
        }
        //删除原有用户
//        SysUser delUser = new SysUser();
//        delUser.setUserId(userId);
//        delUser.setStatus("1");
//        sysUserService.updateById(delUser);
        //新建用户
//        byId.setUserId(null);
        byId.setOrgId(newOrgId);
        byId.setOrgName(newOrg.getOrgName());
        //所属部门、主岗位、副岗位字段
        TSysPost post = tSysPostService.getById(postId);
        if (post == null) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("主岗位不存在").build());
        }
        byId.setPostId(postId);
        byId.setPostName(post.getPostName());
        if (StringUtils.isNotEmpty(deputyPostId)) {
            TSysPost deputyPost = tSysPostService.getById(deputyPostId);
            if (deputyPost == null) {
                throw new ServiceException(ResponseInfo.builder().code(400).msg("副岗位不存在").build());
            }
            byId.setDeputyPostId(deputyPostId);
        }
        SysOrg dept = sysOrgService.getById(deptId);
        if (dept == null) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("部门不存在").build());
        }
        byId.setDeptId(deptId);
        byId.setStatus("0");
        byId.setUpdateDate(new Date());
        sysUserService.updateById(byId);
        /*SysUserExtend sysUserExtend = sysUserExtendService.getById(userId);
        if (sysUserExtend != null) {
            sysUserExtendService.addOrUpdateUserType(byId.getUserId(),sysUserExtend.getUserTypeCode());
        }*/
    }


    /**
     * 校验当前是否有待办
     *
     * @param userId
     * @param orgId
     */
    private void verificationAgent(String userId, String orgId) {
        TodoListRequest todoListRequest = new TodoListRequest();
        todoListRequest.setUsername(userId);
        todoListRequest.setLimit("10");
        todoListRequest.setPage("1");
        todoListRequest.setOrgId(orgId);
        Long total = wfTaskController.toDoTaskList(todoListRequest).getData().getTotal();
        if (total > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("当前用户还有未完成的待办任务").build());
        }
    }


    /**
     * 校验当前是否有排期
     *
     * @param userId
     */
    private void checkWatch(String userId) {
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        int count = dutyService.count(new QueryWrapper<TSysDuty>().eq("user_id", userId).eq("status", "0").ge("duty_date", date.format(formatter)));
        if (count > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("转岗用户在【值班列表】中还有未完成的值班").build());
        }
    }


    /**
     * 校验未结束的应急演练中是否有总指挥的数据
     *
     * @param userId
     */
    private void checkDrill(String userId) {
        int count = tEmergencyRehearsalService.count(new QueryWrapper<TEmergencyRehearsal>().eq("total_command                                                                          ", userId)
                .eq("status", "0").ne("rehearsal_status", "4").ne("rehearsal_status", "5"));
        if (count > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("转岗用户在【应急预案演练】中是总指挥，演练还未完成").build());
        }
    }


    /**
     * 校验未结束的隐患台账是否有 整改人、验收人、指派人的数据
     *
     * @param userId
     */
    private void verificationLedger(String userId) {
        //整改人
        int corrector = tSafeHazardOrgService.count(new QueryWrapper<TSafeHazardOrg>().eq("rectify_people", userId)
                .ne("process_status", "4").ne("process_status", "5").eq("status", "0"));
        //验收人
        int acceptor = tSafeHazardOrgService.count(new QueryWrapper<TSafeHazardOrg>().eq("acceptance", userId)
                .ne("process_status", "4").ne("process_status", "5").eq("status", "0"));
        //指派人
        int appointor = tSafeHazardOrgService.count(new QueryWrapper<TSafeHazardOrg>().eq("assigner", userId)
                .ne("process_status", "4").ne("process_status", "5").eq("status", "0"));
        if (corrector > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("转岗用户在【隐患台账】中是整改人，台账还未完成").build());
        } else if (acceptor > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("转岗用户在【隐患台账】中是验收人，台账还未完成").build());
        } else if (appointor > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg("转岗用户在【隐患台账】中是指派人，台账还未完成").build());
        }
    }
}
