package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dao.PreFryApprovalRecordsDAO;
import com.cool.store.dao.PreFryQualificationApplyDAO;
import com.cool.store.dao.RegionDao;
import com.cool.store.dto.pre.fry.*;
import com.cool.store.entity.PreFryApprovalRecordsDO;
import com.cool.store.entity.PreFryQualificationApplyDO;
import com.cool.store.enums.AuditOperationTypeEnum;
import com.cool.store.enums.AuditStatusEnum;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.PreFryApplyTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.service.PreFryQualificationApplyService;
import com.cool.store.userholder.CurrentUser;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.vo.PartnerUserInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2025/6/21 14:49
 * @Version 1.0
 */
@Service
public class PreFryQualificationApplyServiceImpl implements PreFryQualificationApplyService {

    @Resource
    private PreFryQualificationApplyDAO preFryQualificationApplyDAO;
    @Resource
    private PreFryApprovalRecordsDAO preFryApprovalRecordsDAO;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private RegionDao regionDao;


    @Override
    public Long submitApply(ApplyDTO request, PartnerUserInfoVO user) {
        // 1. 参数校验
        validateRequest(request);


        // 2. 检查是否已有同类型申请
        PreFryQualificationApplyDO preFryQualificationApplyDO = preFryQualificationApplyDAO.selectByStoreCodeAndType(request.getStoreCode(), request.getApplyType());
        if(preFryQualificationApplyDO!=null){
            throw new ServiceException(ErrorCodeEnum.PRE_FRY_RECORD_EXIST);
        }

        // 3. 创建申请记录
        PreFryQualificationApplyDO apply = createApplyRecord(request,user);

        // 4. 创建审批操作记录
        createApprovalRecord(apply.getId(), AuditOperationTypeEnum.APPLY.getCode(),1, user.getUsername(),"");

        return apply.getId();
    }

    @Override
    public Long reSubmitApply(ApplyDTO request, PartnerUserInfoVO user) {
        // 1. 参数校验
        validateRequest(request);
        // 2. 检查是否已有同类型申请
        PreFryQualificationApplyDO preFryQualificationApplyDO = preFryQualificationApplyDAO.selectByStoreCodeAndType(request.getStoreCode(), request.getApplyType());
        if(preFryQualificationApplyDO!=null&& !preFryQualificationApplyDO.getId().equals(request.getId())){
            throw new ServiceException(ErrorCodeEnum.PRE_FRY_RECORD_EXIST);
        }
        // 3. 创建申请记录
        PreFryQualificationApplyDO old = preFryQualificationApplyDAO.queryById(request.getId());
        old.setApplyType(request.getApplyType());
        old.setColdStorageBoxPhoto(request.getColdStorageBoxPhoto());
        old.setProtectiveCoverPhoto(request.getProtectiveCoverPhoto());
        old.setRefrigeratorPlatePhoto(request.getRefrigeratorPlatePhoto());
        old.setRefrigeratorPhoto(request.getRefrigeratorPhoto());
        old.setAuditStatus(AuditStatusEnum.TODO.getCode());
        old.setUpdatedTime(new Date());

        preFryQualificationApplyDAO.updateForce(old);
        // 4. 创建审批操作记录
        createApprovalRecord(old.getId(), AuditOperationTypeEnum.APPLY.getCode(),1, user.getUsername(),"");

        return old.getId();
    }


    @Override
    public ApplyDTO getByStoreCodeAndApplyType(String storeCode, Integer applyType) {
        if (applyType == null|| StringUtils.isEmpty(storeCode)){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        PreFryQualificationApplyDO preFryQualificationApplyDO = preFryQualificationApplyDAO.selectByStoreCodeAndType(storeCode, applyType);
        if (preFryQualificationApplyDO != null) {
            ApplyDTO applyDTO = new ApplyDTO();
            BeanUtils.copyProperties(preFryQualificationApplyDO, applyDTO);
            return applyDTO;
        }
        return null;
    }

    @Override
    public List<ApprovalRecordDTO> getApprovalRecordById(Long recordId) {
        if (recordId == null) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        List<PreFryApprovalRecordsDO> records = preFryApprovalRecordsDAO.getRecordsByApplyId(recordId);
        List<ApprovalRecordDTO> result = new ArrayList<>();
        if (records != null){
            records.forEach(record -> {
                ApprovalRecordDTO recordDTO = new ApprovalRecordDTO();
                BeanUtils.copyProperties(record, recordDTO);
                result.add(recordDTO);
            });
        }
        return result;
    }

    @Override
    public PageInfo<ApplyManagementDTO> queryApplyManagementList(ApplyManagementQueryDTO query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ApplyManagementDTO> applyManagementDTOS = preFryQualificationApplyDAO.selectApplyManagementList(query);
//        if (CollectionUtils.isNotEmpty(applyManagementDTOS)){
//            Set<String> userIds = applyManagementDTOS.stream().map(ApplyManagementDTO::getInvestmentManagerId).collect(Collectors.toSet());
//            Map<String, String> userNameMap = enterpriseUserDAO.getUserNameMap(new ArrayList<>(userIds));
//            Set<Long> regionIds = applyManagementDTOS.stream().map(ApplyManagementDTO::getRegionId).collect(Collectors.toSet());
//            Map<Long, String> regionNameMap = regionDao.getRegionNameMap(new ArrayList<>(regionIds));
//            for (ApplyManagementDTO applyManagementDTO:applyManagementDTOS){
//                applyManagementDTO.setInvestmentManagerName(userNameMap.getOrDefault(applyManagementDTO.getInvestmentManagerId(), ""));
//                applyManagementDTO.setRegionName(regionNameMap.getOrDefault(applyManagementDTO.getRegionId(), ""));
//            }
//        }
        return new PageInfo<>(applyManagementDTOS);
    }

    @Override
    public ApplyDetailDTO getApplyDetail(Long id) {
        ApplyDetailDTO applyDetail = preFryQualificationApplyDAO.getApplyDetail(id);
        if (applyDetail==null){
            throw new ServiceException(ErrorCodeEnum.PRE_FRY_APPLY_NOT_EXIST);
        }
        return applyDetail;
    }

    @Override
    public Boolean audit(ApplyAuditDTO applyAuditDTO, LoginUserInfo currentUser) {
        PreFryQualificationApplyDO preFryQualificationApplyDO = preFryQualificationApplyDAO.queryById(applyAuditDTO.getId());
        if (preFryQualificationApplyDO==null){
            throw new ServiceException(ErrorCodeEnum.PRE_FRY_APPLY_NOT_EXIST);
        }
        preFryQualificationApplyDO.setAuditStatus(applyAuditDTO.getAuditStatus());
        preFryQualificationApplyDAO.updateForce(preFryQualificationApplyDO);
        createApprovalRecord(applyAuditDTO.getId(), 2,applyAuditDTO.getAuditStatus(),currentUser.getName(),applyAuditDTO.getAuditRemark());
        return Boolean.TRUE;
    }

    @Override
    public Integer getMinApplyType(String storeCode) {
        PreFryQualificationApplyDO minApplyTypeByStoreCode = preFryQualificationApplyDAO.getMinApplyTypeByStoreCode(storeCode);
        if (minApplyTypeByStoreCode == null){
            return -1;
        }
        return minApplyTypeByStoreCode.getApplyType();
    }

    @Override
    public List<PreFryQualificationApplyDTO> getListByStoreCode(String storeCode) {
        if (StringUtils.isBlank(storeCode)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        List<PreFryQualificationApplyDO> preFryQualificationApplyDOS = preFryQualificationApplyDAO.listByStoreCode(storeCode);
        List<PreFryQualificationApplyDTO> preFryQualificationApplyDTOS = new ArrayList<>();
        preFryQualificationApplyDOS.forEach(x->{
            PreFryQualificationApplyDTO preFryQualificationApplyDTO = new PreFryQualificationApplyDTO();
            preFryQualificationApplyDTO.setId(x.getId());
            preFryQualificationApplyDTO.setApplyType(x.getApplyType());
            preFryQualificationApplyDTO.setAuditStatus(x.getAuditStatus());
            preFryQualificationApplyDTO.setStoreCode(x.getStoreCode());
            preFryQualificationApplyDTOS.add(preFryQualificationApplyDTO);
        });
        return preFryQualificationApplyDTOS;
    }


    private void validateRequest(ApplyDTO request) {
        if (request == null || StringUtils.isBlank(request.getStoreCode())
                || request.getApplyType() == null) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
    }

    private PreFryQualificationApplyDO createApplyRecord(ApplyDTO request,PartnerUserInfoVO user) {
        PreFryQualificationApplyDO apply = new PreFryQualificationApplyDO();
        BeanUtils.copyProperties(request, apply);
        apply.setAuditStatus(AuditStatusEnum.TODO.getCode());
        apply.setCreatedTime(new Date());
        apply.setCreatedUserId(user.getPartnerId());
        apply.setApplyCode(getPreFlyQualificationApplyCode());
        preFryQualificationApplyDAO.createQualificationApply(apply);
        return apply;
    }

    private void createApprovalRecord(Long applyId, Integer recordType,Integer operationStatus,String userName,String remark) {
        PreFryApprovalRecordsDO record = new PreFryApprovalRecordsDO();
        record.setApplyId(applyId);
        record.setRecordType(recordType);
        record.setOperationStatus(operationStatus);
        record.setOperatorName(userName);
        record.setRemark(remark);
        record.setCreatedTime(new Date());
        preFryApprovalRecordsDAO.createApprovalRecord(record);
    }

    public String getPreFlyQualificationApplyCode() {
        //当前日期
        String today = CoolDateUtils.getToday();
        return "13" + today + String.format("%04d", ThreadLocalRandom.current().nextInt(100000));
    }







}
