package com.cool.store.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.dao.HyOpenAreaInfoDAO;
import com.cool.store.dto.inspection.interview.InspectionRevocationDTO;
import com.cool.store.dto.inspection.interview.InspectionSubmissionDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.InspectionOperationTypeEnum;
import com.cool.store.enums.InspectionStatusEnum;
import com.cool.store.exception.ApiException;
import com.cool.store.mapper.HyInspectionMapper;
import com.cool.store.request.GetInterviewInspectionListReq;
import com.cool.store.request.GetInterviewInspectionResultListReq;
import com.cool.store.mapper.HyInterviewInspectionLogMapper;
import com.cool.store.service.InterviewInspectionService;
import com.cool.store.service.MDMAreaService;
import com.cool.store.service.OpenAreaService;
import com.cool.store.utils.StringUtil;
import com.cool.store.vo.interview.InterviewInspectionHistoryInfo;
import com.cool.store.vo.interview.InterviewInspectionInfo;
import com.cool.store.vo.interview.InterviewInspectionResultVO;
import com.cool.store.vo.interview.InterviewInspectionVO;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Fun Li
 * @version 1.0
 * @date 2023/7/19 16:50
 */
@Service
public class InterviewInspectionServiceImpl implements InterviewInspectionService {

    @Autowired
    private HyInspectionMapper inspectionMapper;

    @Autowired
    private HyInterviewInspectionLogMapper interviewInspectionLogMapper;


    @Resource
    private HyOpenAreaInfoDAO hyOpenAreaInfoDAO;

    @Override
    public void submit(InspectionSubmissionDTO dto) throws ApiException {
        HyInspectionDO rawInspection = inspectionMapper.selectByPrimaryKey(dto.getInspectionId());
        if (Objects.isNull(rawInspection)) {
            throw new ApiException(ErrorCodeEnum.INSPECTION_INFO_NOT_EXIST);
        }
        HyInspectionDO hyInspectionDO = new HyInspectionDO();
        //稽核结果和说明及文件等
        hyInspectionDO.setId(dto.getInspectionId());
        if (dto.getWhetherPass().equals(0)) {
            hyInspectionDO.setStatus(InspectionStatusEnum.NOT_PASS.getCode());
        } else if (dto.getWhetherPass().equals(1)) {
            hyInspectionDO.setStatus(InspectionStatusEnum.PASS.getCode());
        }
        hyInspectionDO.setDescription(dto.getDescription());
        String filesStr = spliceFiles(dto.getFiles());
        hyInspectionDO.setFiles(filesStr);
        //稽核人，稽核时间，创建人
        hyInspectionDO.setOperatorUserId(CurrentUserHolder.getUserId());
        hyInspectionDO.setUpdator(CurrentUserHolder.getUserId());
        hyInspectionDO.setInspectionTime(DateUtil.now());
        hyInspectionDO.setCreator(rawInspection.getCreator() == null ? CurrentUserHolder.getUserId() : rawInspection.getCreator());
        inspectionMapper.updateByPrimaryKeySelective(hyInspectionDO);
    }

    @Override
    @Transactional
    public void revoke(InspectionRevocationDTO dto) throws ApiException {
        //2.1 查询之前的一次操作
        HyInspectionDO hyInspectionDO = inspectionMapper.selectByPrimaryKey(dto.getInspectionId());
        if (Objects.isNull(hyInspectionDO)) {
            throw new ApiException(ErrorCodeEnum.INSPECTION_INFO_NOT_EXIST);
        }
        //1. 撤销操作记录写入数据库面试稽核操作记录表
        HyInterviewInspectionLogDO inspectionLog = new HyInterviewInspectionLogDO();
        inspectionLog.setOperatorUserId(CurrentUserHolder.getUserId());
        inspectionLog.setInspectionId(dto.getInspectionId());
        inspectionLog.setOperationType(InspectionOperationTypeEnum.REVOCATION.getCode());
        inspectionLog.setDescription(dto.getDescription());
        String filesStr = spliceFiles(dto.getFiles());
        inspectionLog.setOperationTime(DateUtil.now());
        inspectionLog.setFiles(filesStr);
        interviewInspectionLogMapper.insertSelective(inspectionLog);
        //2. 撤销操作之前的一次操作写入面试稽核操作记录表
        inspectionLog.setOperatorUserId(hyInspectionDO.getOperatorUserId());
        inspectionLog.setInspectionId(hyInspectionDO.getId());
        if (hyInspectionDO.getStatus().equals(1)) {
            inspectionLog.setOperationType(InspectionOperationTypeEnum.PASS.getCode());
        } else if (hyInspectionDO.getStatus().equals(2)) {
            inspectionLog.setOperationType(InspectionOperationTypeEnum.NOT_PASS.getCode());
        }
        inspectionLog.setDescription(hyInspectionDO.getDescription());
        inspectionLog.setFiles(hyInspectionDO.getFiles());
        inspectionLog.setOperationTime(hyInspectionDO.getInspectionTime());
        interviewInspectionLogMapper.insertSelective(inspectionLog);
        //3. 撤销操作之前的一次操作稽核信息状态修改为未稽核，并且将数据状态（其他字段）也恢复到未稽核时的状态
        hyInspectionDO.setOperatorUserId(null);
        hyInspectionDO.setStatus(InspectionStatusEnum.NOT_INSPECT.getCode());
        hyInspectionDO.setFiles(null);
        hyInspectionDO.setDescription(null);
        hyInspectionDO.setInspectionTime(null);
        hyInspectionDO.setUpdator(null);
        inspectionMapper.updateByPrimaryKey(hyInspectionDO);
    }

    @Override
    public InterviewInspectionInfo interviewInspectionGetDetail(Long id) {
        InterviewInspectionInfo interviewInspectionInfo = inspectionMapper.interviewInspectionGetDetail(id);
        if (ObjectUtil.isNotNull(interviewInspectionInfo) && ObjectUtil.isNotNull(interviewInspectionInfo.getFilesStr())) {
            List<String> list = Arrays.asList(interviewInspectionInfo.getFilesStr().split(","));
            interviewInspectionInfo.setFiles(list);
        }
        return interviewInspectionInfo;
    }

    @Override
    public List<InterviewInspectionHistoryInfo> interviewInspectionGetHistoryDetail(Long id) {
        List<InterviewInspectionHistoryInfo> interviewInspectionHistoryInfos = interviewInspectionLogMapper.interviewInspectionGetHistoryDetail(id);
        for (InterviewInspectionHistoryInfo interviewInspectionHistoryInfo : interviewInspectionHistoryInfos) {
            if (ObjectUtil.isNotNull(interviewInspectionHistoryInfo) && ObjectUtil.isNotNull(interviewInspectionHistoryInfo.getFilesStr())) {
                List<String> list = Arrays.asList(interviewInspectionHistoryInfo.getFilesStr().split(","));
                interviewInspectionHistoryInfo.setFiles(list);
            }
        }
        return interviewInspectionHistoryInfos;
    }

    @Override
    public List<InterviewInspectionResultVO> interviewInspectionResultGetList(GetInterviewInspectionResultListReq request) {
        //给个默认时间
        if (StringUtil.isEmpty(request.getStartTime()) && StringUtil.isEmpty(request.getEndTime())) {
            request.setStartTime(getHourDayDate(0, -6, true)).setEndTime(getHourDayDate(0, 0, false));
        }
        //意向开店区域 不为空
        if (StringUtil.isNotEmpty(request.getWantShopArea())) {
            HyOpenAreaInfoDO hyOpenAreaInfoDO =hyOpenAreaInfoDAO.selectById(Convert.toLong(request.getWantShopArea()));
            if (ObjectUtil.isNull(hyOpenAreaInfoDO.getParentId())) {
                //是省
                PageHelper.startPage(request.getPageNum(), request.getPageSize());
                return inspectionMapper.interviewInspectionResultGetProvinceList(request.setUserId(CurrentUserHolder.getUserId()));
            } else {
                //并非省
                List<Long> codeList = hyOpenAreaInfoDAO.getAllAreaCode(request.getWantShopArea()).stream().map(HyOpenAreaInfoDO::getId).collect(Collectors.toList());
                request.setCodeList(codeList);
            }
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        return inspectionMapper.interviewInspectionResultGetList(request.setUserId(CurrentUserHolder.getUserId()));
    }

    private String spliceFiles(List<String> files) {
        if (files == null || files.size() == 0) {
            return null;
        }
        return files.stream().map(String::valueOf).collect(Collectors.joining(","));
    }

    @Override
    public List<InterviewInspectionVO> interviewInspectionGetList(GetInterviewInspectionListReq request) {
        //给个默认时间
        if (StringUtil.isEmpty(request.getStartTime()) && StringUtil.isEmpty(request.getEndTime())) {
            request.setStartTime(getHourDayDate(0, -6, true)).setEndTime(getHourDayDate(0, 0, false));
        }
        //意向开店区域 不为空
        if (StringUtil.isNotEmpty(request.getWantShopArea())) {
            HyOpenAreaInfoDO hyOpenAreaInfoDO =hyOpenAreaInfoDAO.selectById(Convert.toLong(request.getWantShopArea()));
            if (ObjectUtil.isNull(hyOpenAreaInfoDO.getParentId())) {
                //是省
                PageHelper.startPage(request.getPageNum(), request.getPageSize());
                return inspectionMapper.interviewInspectionGetProvinceList(request.setUserId(CurrentUserHolder.getUserId()));
            } else {
                //并非省
                List<Long> codeList = hyOpenAreaInfoDAO.getAllAreaCode(request.getWantShopArea()).stream().map(HyOpenAreaInfoDO::getId).collect(Collectors.toList());
                request.setCodeList(codeList);
            }
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        return inspectionMapper.interviewInspectionGetList(request.setUserId(CurrentUserHolder.getUserId()));
    }


    private String getHourDayDate(int hour, int day, boolean pan) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(Calendar.HOUR, hour);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        Date twoDay = calendar.getTime();
        String partner = pan ? "yyyy-MM-dd 00:00:00" : "yyyy-MM-dd 24:00:00";
        return new SimpleDateFormat(partner).format(twoDay);
    }


}
