package com.sifang.modules.taskdispatch.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.dao.CrmReviewGroupMemberDao;
import com.sifang.modules.taskdispatch.entity.CrmReviewGroupMember;
import com.sifang.modules.taskdispatch.vo.GroupMemberInfo;
import com.sifang.modules.taskdispatch.vo.SignStatus;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 审核组成员信息Service
 *
 * @author gaols
 */
@Component
public class CrmReviewGroupMemberService extends BaseService {

    @Autowired
    private CrmReviewGroupMemberDao crmReviewGroupMemberDao;
    @Autowired
    private CrmPlatformEmpDao platformEmpDao;

    private static final Logger log = LoggerFactory.getLogger(CrmReviewGroupMemberService.class);

    public CrmReviewGroupMember get(String id) {
        return crmReviewGroupMemberDao.get(id);
    }

    public void listData(LayuiPage<Record> page, Map<String, String> params) {
        crmReviewGroupMemberDao.listData(page, params);
        crmReviewGroupMemberDao.listDataCount(page, params);
    }

    public static boolean mock() {
        return false;
    }

    public SignStatus signStatus(GroupMemberInfo groupMemberInfo) {
        if (mock()) {
            return new SignStatus(true, true);
        }
        if (groupMemberInfo == null) {
            return new SignStatus(false, false);
        }
        List<Record> members = groupMemberInfo.getGroupMembers();
        if (CollectionUtils.isEmpty(members)) {
            return new SignStatus(false, false);
        }
        return new SignStatus(true, isAnyMemberNeedSignin(members));
    }

    private boolean isAnyMemberNeedSignin(List<Record> members) {
        for (Record member : members) {
            Date signinTime = member.getDate("signin_time");
            Date signoutTime = member.getDate("signout_time");
            if (signinTime == null || signoutTime != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 会根据 userId 去重，因为用户可以属于多个审核组，查询出来会有重复。
     */
    public List<Record> findAllMembers() {
        List<Record> allMembers = crmReviewGroupMemberDao.findAllMembers();
        List<Record> ret = new ArrayList<>();
        Set<String> existsUserIds = new HashSet<>();
        for (Record member : allMembers) {
            String userId = member.getStr("user_id");
            if (!existsUserIds.contains(userId)) {
                existsUserIds.add(userId);
                ret.add(member);
            }
        }
        return ret;
    }

    public List<Record> groupMembers(String groupId) {
        Map<String, String> params = new HashMap<>();
        params.put("groupId", groupId);
        return crmReviewGroupMemberDao.listData(null, params);
    }

    public List<Record> groupMembersWithoutLeader(String groupId) {
        Map<String, String> params = new HashMap<>();
        params.put("groupId", groupId);
        params.put("leadership", "0");
        return crmReviewGroupMemberDao.listData(null, params);
    }

    public boolean isGroupLeader(GroupMemberInfo groupMemberInfo) {
        if (groupMemberInfo == null) {
            return false;
        }
        return groupMemberInfo.isLeader();
    }

    @Transactional(rollbackFor = Exception.class)
    public String signin(String userId) {
        CrmPlatformEmployee employee = ensureGroupMember(userId);
        List<CrmReviewGroupMember> members = crmReviewGroupMemberDao.findMemberByEmployeeId(employee.getId());
        if (CollectionUtils.isEmpty(members)) {
            throw new BusinessException("审核组成员不存在！");
        }
        Date signinTime = new Date();
        for (CrmReviewGroupMember member : members) {
            if (member.getSigninTime() != null && member.getSignoutTime() == null) {
                continue;
            }
            member.setSigninTime(signinTime);
            member.setSignoutTime(null);
            crmReviewGroupMemberDao.save(member);
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(signinTime);
    }

    @Transactional(rollbackFor = Exception.class)
    public String signout(String userId) {
        CrmPlatformEmployee employee = ensureGroupMember(userId);
        List<CrmReviewGroupMember> members = crmReviewGroupMemberDao.findMemberByEmployeeId(employee.getId());
        if (CollectionUtils.isEmpty(members)) {
            throw new BusinessException("审核组成员不存在！");
        }
        for (CrmReviewGroupMember member : members) {
            if (member.getSigninTime() == null || member.getSignoutTime() != null) {
                // 尚未签到或者已经签退的点签退没有意义
                continue;
            }
            Date timeout = new Date();
            member.setSignoutTime(timeout);
            if (member.getSigninTime() != null) {
                long subtract = (timeout.getTime() - member.getSigninTime().getTime()) / 1000;
                String insertsql = "insert into crm_review_group_member_sign_record (id,group_id,employee_id,user_id,leadership,signin_time,signout_time,length) " +
                        "values(?,?,?,?,?,?,?,?)";
                Db.update(insertsql, IdGen.uuid(), member.getGroupId(), member.getEmployeeId(), member.getUserId(), member.getLeadership(), member.getSigninTime(),
                        member.getSignoutTime(), subtract);
            }
            crmReviewGroupMemberDao.save(member);
        }

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    @NotNull
    private CrmPlatformEmployee ensureGroupMember(String userId) {
        CrmPlatformEmployee employee = platformEmpDao.findByUserId(userId);
        if (employee == null) {
            log.error("用户不属于审核组, userId:" + userId);
            throw new BusinessException("用户不属于审核组！");
        }
        List<Record> members = crmReviewGroupMemberDao.findByEmployeeId(employee.getId());
        if (CollectionUtils.isEmpty(members)) {
            throw new BusinessException("只有审单组成员才需要签到！");
        }
        return employee;
    }

    public GroupMemberInfo getGroupMemberInfo(String userId) {
        CrmPlatformEmployee employee = platformEmpDao.findByUserId(userId);
        if (employee == null) {
            return null;
        }
        List<Record> members = crmReviewGroupMemberDao.findByEmployeeId(employee.getId());
        if (CollectionUtils.isEmpty(members)) {
            return null;
        }
        return new GroupMemberInfo(employee, members);
    }

    /**
     * 重派
     */
    @Transactional(rollbackFor = Exception.class)
    public void redispatch() {
    }

}
