package com.casic.missiles.service.Impl.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.business.interchange.*;
import com.casic.missiles.dto.customer.sample.CustomerSampleListVO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessInterchangeMapper;
import com.casic.missiles.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.model.business.BusinessInterchange;
import com.casic.missiles.model.business.BusinessOrderSampleRelation;
import com.casic.missiles.service.business.IBusinessInterchangeService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业务管理-设备交接单 服务实现类
 * </p>
 *
 * @author cz
 * @since 2023-02-02
 */
@Service
@AllArgsConstructor
public class BusinessInterchangeServiceImpl extends ServiceImpl<BusinessInterchangeMapper, BusinessInterchange> implements IBusinessInterchangeService {

    private final IBaseExportService iBaseExportService;
    private final BusinessOrderSampleRelationMapper sampleRelationMapper;

    /**
     * 送检人查询条件不在设备交接单中，需要联查才可以实现
     */
    @Override
    public Page<InterchangeListResponse> exchangeListPage(Page<InterchangeListResponse> page, InterchangeListRequest request) throws Exception {
        page.setRecords(this.baseMapper.selectInterchangeListPage(page, request));
        return page;
    }

    @Override
    public BusinessInterchangeDetailResponse exchangeDetail(Long id) {
        BusinessInterchangeDetailResponse businessExchange = this.baseMapper.getInfoById(id);
        QueryWrapper<BusinessOrderSampleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", businessExchange.getOrderId());
        List<BusinessOrderSampleRelation> orderSampleList = sampleRelationMapper.selectList(queryWrapper);
        List<CustomerSampleListVO> customerSampleList = new ArrayList<>();
        for (BusinessOrderSampleRelation businessOrderSampleRelation : orderSampleList) {
            CustomerSampleListVO customerSampleListVO = sampleRelationMapper.getInterChangeSampleList(businessOrderSampleRelation.getOrderId(), businessOrderSampleRelation.getSampleId());
            customerSampleList.add(customerSampleListVO);
        }
        businessExchange.setCustomerSampleList(customerSampleList);
        return businessExchange;
    }

    @Override
    @Transactional
    public ReturnDTO deleteExchange(Long id) {
        int deleteFlag = this.baseMapper.deleteById(id);
        //交接单绑定的肯定有样品，所以sampleUpdateFlag肯定为true
        boolean sampleUpdateFlag = sampleStatusDeletor(id) > 0;
        if (deleteFlag > 0 && sampleUpdateFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 更新只是交接单的变更，没有任何其他单位的变化
     */
    @Override
    public ReturnDTO updateExchange(BusinessInterchange businessInterchange) {
        int updateFlag = this.baseMapper.updateById(businessInterchange);
        if (updateFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 交接单新增，同时在样品委托书管理表中新增交接单记录id
     */
    @Override
    @Transactional
    public ReturnDTO addExchange(BusinessInterchange businessInterchange) {
        populationExchange(businessInterchange);
        int addFlag = this.baseMapper.insert(businessInterchange);
        boolean sampleAddFlag = true;
        if (!CollectionUtils.isEmpty(businessInterchange.getCustomerSampleList())) {
            for (CustomerSampleListVO sampleInfo : businessInterchange.getCustomerSampleList()) {
                sampleAddFlag = sampleAddFlag && sampleStatusUpdator(sampleInfo, businessInterchange.getId()) > 0;
            }
        }
        if (addFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    /**
     * 选中判断ids存在，进行其他条件的清空
     */
    @Override
    public void exportExchange(InterchangeListRequest request, HttpServletResponse response) {
        try {
            List<InterchangeListResponse> resultList;
            if (!CollectionUtils.isEmpty(request.getIds())) {
                initFlushEmpty(request);
            } else {
                request.setIds(null);
            }
            Page<InterchangeListResponse> page = PageFactory.defaultPage();
            page.setCurrent(1);
            page.setSearchCount(false);
            page.setSize(Integer.MAX_VALUE);
            resultList = this.baseMapper.selectInterchangeListPage(page, request);
            iBaseExportService.exportExcel(response, InterchangeListResponse.class, resultList, ExportEnum.EXCHANGE_DATA.getSheetName());
        } catch (Exception e) {
            log.error("样品导出出现异常，异常信息为{}", e);
        }
    }


    private void initFlushEmpty(InterchangeListRequest request) {
        request.setEndTime(null);
        request.setInterchangeCode(null);
        request.setCustomerNo(null);
        request.setCustomerName(null);
        request.setDeliverer(null);
        request.setReciever(null);
        request.setStartTime(null);
    }

    private void populationExchange(BusinessInterchange businessInterchange) {
        Long maxNo = this.baseMapper.selectMaxExchangeNo();
        String orderNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.INTER_CHANGE_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        businessInterchange.setCreateUser(authUser.getId());
        businessInterchange.setInterchangeCode(orderNo);
    }

    private Integer sampleStatusDeletor(Long interChangeId) {
        QueryWrapper<BusinessOrderSampleRelation> orderSampleWrapper = new QueryWrapper<>();
        orderSampleWrapper.eq("interchange_id", interChangeId);
        BusinessOrderSampleRelation businessOrderSampleRelation = new BusinessOrderSampleRelation();
        businessOrderSampleRelation.setInterchangeId(null);
        return sampleRelationMapper.update(businessOrderSampleRelation, orderSampleWrapper);
    }

    private Integer sampleStatusUpdator(CustomerSampleListVO sampleInfo, Long interChangeId) {
        QueryWrapper<BusinessOrderSampleRelation> orderSampleWrapper = new QueryWrapper<>();
        orderSampleWrapper.eq("order_id", sampleInfo.getOrderId());
        orderSampleWrapper.eq("sample_id", sampleInfo.getSampleId());
        BusinessOrderSampleRelation businessOrderSampleRelation = new BusinessOrderSampleRelation();
        businessOrderSampleRelation.setInterchangeId(interChangeId);
        return sampleRelationMapper.update(businessOrderSampleRelation, orderSampleWrapper);
    }

}
