package com.gree.mall.manager.logic.worker;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.worker.WebsitWorkerBean;
import com.gree.mall.manager.bean.worker.WorkerTeamVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.enums.ExamineWorkerStatusEnum;
import com.gree.mall.manager.enums.material.StateEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.User;
import com.gree.mall.manager.plus.entity.WebsitUser;
import com.gree.mall.manager.plus.entity.WorkerTeam;
import com.gree.mall.manager.plus.entity.WorkerTeamApply;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.WorkerTeamParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class WorkerTeamLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final WorkerTeamService workerTeamService;
    private final WebsitUserService websitUserService;
    private final UserService userService;
    private final WorkerTeamApplyService workerTeamApplyService;
    private final UserWaitService userWaitService;

    public IPage<WorkerTeamVO> list(WorkerTeamParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, WorkerTeamVO.class, adminUser);
        return commonMapper.workerTeamPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, zfireParamBean.getWorkerId());
    }

    public void add(WorkerTeam workerTeam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        workerTeam.setCompanyWechatId(adminUser.getCompanyWechatId())
                .setCompanyWechatName(adminUser.getCompanyName());
        this.validParams(workerTeam);
        this.checkUniqueTeam(workerTeam);

        workerTeam.insert();
    }

    public void update(WorkerTeam workerTeam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        final WorkerTeam old = workerTeamService.getById(workerTeam.getId());
        workerTeam.setCompanyWechatId(old.getCompanyWechatId())
                .setCompanyWechatName(old.getCompanyWechatName());
        this.validParams(workerTeam);

        workerTeam.updateById();
    }

    private void validParams(WorkerTeam workerTeam) {
        if (StringUtils.isBlank(workerTeam.getWebsitId())) {
            throw new RemoteServiceException("所属网点不能为空");
        }
        if (StringUtils.isBlank(workerTeam.getMasterWorkerId())) {
            throw new RemoteServiceException("大工师傅不能为空");
        }
        if (StringUtils.isBlank(workerTeam.getMasterWorkerName())) {
            workerTeam.setMasterWorkerName("");
        }
        if (StringUtils.isBlank(workerTeam.getAssistantWorkerId())) {
            throw new RemoteServiceException("小工师傅不能为空");
        }
        if (StringUtils.isBlank(workerTeam.getAssistantWorkerName())) {
            workerTeam.setAssistantWorkerName("");
        }
        final User user = userService.getById(workerTeam.getMasterWorkerId());
        if (Objects.isNull(user)) {
            throw new RemoteServiceException("大工师傅信息不存在");
        }
        final User user2 = userService.getById(workerTeam.getAssistantWorkerId());
        if (Objects.isNull(user2)) {
            throw new RemoteServiceException("小工师傅信息不存在");
        }
        workerTeam.setMasterWorkerNumber(user.getWorkerNumber())
                .setAssistantWorkerNumber(user2.getWorkerNumber());
    }

    private void checkUniqueTeam(WorkerTeam workerTeam) {
        final WorkerTeam count = workerTeamService.lambdaQuery()
                .eq(WorkerTeam::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WorkerTeam::getWebsitId, workerTeam.getWebsitId())
                .eq(WorkerTeam::getMasterWorkerId, workerTeam.getMasterWorkerId())
                .eq(WorkerTeam::getAssistantWorkerId, workerTeam.getAssistantWorkerId())
                .ne(StringUtils.isNotBlank(workerTeam.getId()), WorkerTeam::getId, workerTeam.getId())
                .last("limit 1")
                .one();
        if (Objects.nonNull(count)) {
            throw new RemoteServiceException(workerTeam.getWebsitId() + "已存在一组同样师傅的记录" + workerTeam.getMasterWorkerId()
                    + "," + workerTeam.getAssistantWorkerId() + (count.getStatus().equals(StateEnum.OFF.getKey()) ? ", 请设为“有效”" : ""));
        }

        final WorkerTeam count1 = workerTeamService.lambdaQuery()
                .eq(WorkerTeam::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WorkerTeam::getWebsitId, workerTeam.getWebsitId())
                .eq(WorkerTeam::getMasterWorkerId, workerTeam.getAssistantWorkerId())
                .eq(WorkerTeam::getAssistantWorkerId, workerTeam.getMasterWorkerId())
                .ne(StringUtils.isNotBlank(workerTeam.getId()), WorkerTeam::getId, workerTeam.getId())
                .last("limit 1")
                .one();
        if (Objects.nonNull(count1)) {
            throw new RemoteServiceException(workerTeam.getWebsitId() + "已存在一组同样师傅的记录" + workerTeam.getMasterWorkerId()
                    + "," + workerTeam.getAssistantWorkerId() + (count1.getStatus().equals(StateEnum.OFF.getKey()) ? ", 请设为“有效”" : ""));
        }


        final Integer count2 = workerTeamApplyService.lambdaQuery()
                .eq(WorkerTeamApply::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WorkerTeamApply::getWebsitId, workerTeam.getWebsitId())
                .eq(WorkerTeamApply::getStatus, ExamineStatusEnum.WAIT.getKey())
                .eq(WorkerTeamApply::getMasterWorkerId, workerTeam.getMasterWorkerId())
                .eq(WorkerTeamApply::getAssistantWorkerId, workerTeam.getAssistantWorkerId())
                .count();
        if (count2 > 0) {
            throw new RemoteServiceException(workerTeam.getWebsitId() + "已存在一组同样师傅的待师傅确认的申请记录" + workerTeam.getMasterWorkerId() + "," + workerTeam.getAssistantWorkerId());
        }

        final Integer count3 = workerTeamApplyService.lambdaQuery()
                .eq(WorkerTeamApply::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WorkerTeamApply::getWebsitId, workerTeam.getWebsitId())
                .eq(WorkerTeamApply::getStatus, ExamineStatusEnum.WAIT.getKey())
                .eq(WorkerTeamApply::getMasterWorkerId, workerTeam.getAssistantWorkerId())
                .eq(WorkerTeamApply::getAssistantWorkerId, workerTeam.getMasterWorkerId())
                .count();
        if (count3 > 0) {
            throw new RemoteServiceException(workerTeam.getWebsitId() + "已存在一组同样师傅的待师傅确认的申请记录" + workerTeam.getMasterWorkerId() + "," + workerTeam.getAssistantWorkerId());
        }
    }

    public List<WebsitWorkerBean> queryWebsitWorker(String websitId, String workerId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        final List<WebsitUser> websitUsers = websitUserService.lambdaQuery()
                .eq(WebsitUser::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(WebsitUser::getWebsitId, websitId)
                .ne(StringUtils.isNotBlank(workerId), WebsitUser::getUserId, workerId)
                .in(WebsitUser::getExamineStatus, ExamineWorkerStatusEnum.OK.getKey(), ExamineWorkerStatusEnum.EXPIRED.getKey())
                .list();
        if (CollectionUtil.isEmpty(websitUsers)) {
            return new ArrayList<>();
        }
        final List<User> userList = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, adminUser.getCompanyWechatId())
                .in(User::getUserId, websitUsers.stream().map(WebsitUser::getUserId).collect(Collectors.toList()))
                .list();

        final Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getUserId, Function.identity()));
        List<WebsitWorkerBean> beanList = new ArrayList<>();
        for (WebsitUser websitUser : websitUsers) {
            if (userMap.containsKey(websitUser.getUserId())) {
                final User user = userMap.get(websitUser.getUserId());
                WebsitWorkerBean bean = new WebsitWorkerBean();
                bean.setWorkerId(websitUser.getUserId());
                bean.setWorkerNumber(user.getWorkerNumber());
                bean.setWorkerName(user.getNickName());
                beanList.add(bean);
            }
        }
        return beanList;
    }

    @Transactional
    public void importData(MultipartFile file) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        String companyName = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyName() : null;

        if (org.apache.commons.lang3.StringUtils.isBlank(companyWechatId)) {
            throw new RemoteServiceException("商户编号缺失，导入中止");
        }

        List<Object> objects = ExcelUtils.importExcel(file);

        List<WorkerTeam> workerTeamList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            int rowIndex = i + 2;
            List<Object> row = (List<Object>) objects.get(i);
            CommonUtils.initList2(row, 3);
            if (Objects.isNull(row.get(0)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(0).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 网点编号不能为空");
            }
            if (Objects.isNull(row.get(1)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(1).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 大工师傅手机号不能为空");
            }
            if (Objects.isNull(row.get(2)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(2).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 小工师傅手机号不能为空");
            }
            WorkerTeam workerTeam = new WorkerTeam();
            workerTeam.setCompanyWechatId(companyWechatId)
                    .setCompanyWechatName(companyName)
                    .setWebsitId(row.get(0).toString().trim())
                    .setMasterWorkerId(row.get(1).toString().trim())
                    .setAssistantWorkerId(row.get(2).toString().trim())
                    .setStatus(StateEnum.ON.getKey());
            this.checkImportWorkerWebsit(workerTeam);

            workerTeamList.add(workerTeam);
        }

        List<User> userList = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, companyWechatId)
                .in(User::getMobile, workerTeamList.stream()
                        .map(WorkerTeam::getMasterWorkerId)
                        .collect(Collectors.toList()))
                .list();

        List<User> userList2 = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, companyWechatId)
                .in(User::getMobile, workerTeamList.stream()
                        .map(WorkerTeam::getAssistantWorkerId)
                        .collect(Collectors.toList()))
                .list();

        userList.addAll(userList2);

        Map<String, User> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userList)) {
            userMap = userList.stream()
                    .collect(Collectors.toMap(User::getMobile, Function.identity(), (key1, key2) -> key2));
        }

        for (WorkerTeam workerTeam : workerTeamList) {
            User masterWorker = userMap.get(workerTeam.getMasterWorkerId());
            User assistantWorker = userMap.get(workerTeam.getAssistantWorkerId());
            workerTeam.setMasterWorkerId(masterWorker.getUserId())
                    .setMasterWorkerNumber(masterWorker.getWorkerNumber())
                    .setMasterWorkerName(masterWorker.getNickName())
                    .setAssistantWorkerId(assistantWorker.getUserId())
                    .setAssistantWorkerNumber(assistantWorker.getWorkerNumber())
                    .setAssistantWorkerName(assistantWorker.getNickName());
            this.checkUniqueTeam(workerTeam);
            workerTeam.insert();
        }
    }

    private void checkImportWorkerWebsit(WorkerTeam workerTeam) throws Exception {
        final User user = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(User::getMobile, workerTeam.getMasterWorkerId())
                .one();
        if (Objects.isNull(user)) {
            throw new RemoteServiceException("师傅" + workerTeam.getMasterWorkerId() + "不存在");
        }
        final Integer count = websitUserService.lambdaQuery()
                .eq(WebsitUser::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WebsitUser::getUserId, user.getUserId())
                .eq(WebsitUser::getWebsitId, workerTeam.getWebsitId())
                .in(WebsitUser::getExamineStatus, ExamineWorkerStatusEnum.OK.getKey(), ExamineWorkerStatusEnum.EXPIRED.getKey())
                .count();
        if (count == 0) {
            throw new RemoteServiceException("师傅" + workerTeam.getMasterWorkerId() + "未入驻成功");
        }
        final User user2 = userService.lambdaQuery()
                .eq(User::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(User::getMobile, workerTeam.getAssistantWorkerId())
                .one();
        if (Objects.isNull(user2)) {
            throw new RemoteServiceException("师傅" + workerTeam.getAssistantWorkerId() + "不存在");
        }
        final Integer count2 = websitUserService.lambdaQuery()
                .eq(WebsitUser::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WebsitUser::getUserId, user2.getUserId())
                .eq(WebsitUser::getWebsitId, workerTeam.getWebsitId())
                .in(WebsitUser::getExamineStatus, ExamineWorkerStatusEnum.OK.getKey(), ExamineWorkerStatusEnum.EXPIRED.getKey())
                .count();
        if (count2 == 0) {
            throw new RemoteServiceException("师傅" + workerTeam.getAssistantWorkerId() + "未入驻成功");
        }
    }

    public void del(List<String> ids) {
        workerTeamService.removeByIds(ids);
    }
}
