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.material.StateEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
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.ZfireParamBean;
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.io.IOException;
import java.util.*;
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(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, WorkerTeamVO.class, adminUser);
        return commonMapper.workerTeamPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    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("");
        }
    }

    private void checkUniqueTeam(WorkerTeam workerTeam) {
        final Integer 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())
                .count();
        if (count > 0) {
            throw new RemoteServiceException(workerTeam.getWebsitId() + "已存在一组同样师傅的记录" + workerTeam.getMasterWorkerId() + "," + workerTeam.getAssistantWorkerId());
        }

        final Integer count1 = workerTeamApplyService.lambdaQuery()
                .eq(WorkerTeamApply::getCompanyWechatId, workerTeam.getCompanyWechatId())
                .eq(WorkerTeamApply::getStatus, ExamineStatusEnum.WAIT.getKey())
                .eq(WorkerTeamApply::getMasterWorkerId, workerTeam.getMasterWorkerId())
                .eq(WorkerTeamApply::getAssistantWorkerId, workerTeam.getAssistantWorkerId())
                .count();
        if (count1 > 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::getWorkerNumber, workerId)
                .eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.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 List<UserWait> waitList = userWaitService.lambdaQuery()
//                .eq(UserWait::getCompanyWechatId, adminUser.getCompanyWechatId())
//                .in(UserWait::getWorkerNumber, websitUsers.stream().map(WebsitUser::getWorkerNumber).collect(Collectors.toList()))
//                .list();

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

    @Transactional
    public void importData(MultipartFile file) throws IOException {
        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());
            workerTeamList.add(workerTeam);
        }

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

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

        userList.addAll(userList2);

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

        for (WorkerTeam workerTeam : workerTeamList) {
            String masterWorkerName = userMap.get(workerTeam.getMasterWorkerId());
            String assistantWorkerName = userMap.get(workerTeam.getAssistantWorkerId());
            workerTeam.setMasterWorkerName(masterWorkerName)
                    .setAssistantWorkerName(assistantWorkerName);
            this.checkUniqueTeam(workerTeam);
            workerTeam.insert();
        }
    }
}
