package com.younike.system.service.impl;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.common.utils.geo.DistanceUtil;
import com.younike.system.domain.Merchant;
import com.younike.system.domain.Publish;
import com.younike.system.domain.PublishQuote;
import com.younike.system.domain.vo.PublishManageVo;
import com.younike.system.domain.vo.PublishQuoteVo;
import com.younike.system.domain.vo.ServerUserVo;
import com.younike.system.mapper.PublishMapper;
import com.younike.system.mapper.PublishQuoteMapper;
import com.younike.system.mapper.SysConfigMapper;
import com.younike.system.param.PublishQuoteParam;
import com.younike.system.service.IMerchantService;
import com.younike.system.service.IPublishQuoteService;
import com.younike.system.service.IPublishService;
import com.younike.system.service.IServerUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 需求报价Service业务层处理
 *
 * @author elev
 * @date 2022-01-20
 */
@Service
public class PublishQuoteServiceImpl implements IPublishQuoteService {
    @Autowired
    private PublishQuoteMapper publishQuoteMapper;
    @Autowired
    private IPublishService publishService;
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private IServerUserService serverUserService;

    /**
     * 查询需求报价
     *
     * @param quoteId 需求报价主键
     * @return 需求报价
     */
    @Override
    public PublishQuote selectPublishQuoteByQuoteId(Long quoteId) {

        return publishQuoteMapper.selectPublishQuoteByQuoteId(quoteId);
    }

    /**
     * 查询需求报价列表
     *
     * @param publishQuote 需求报价
     * @return 需求报价
     */
    @Override
    public List<PublishQuote> selectPublishQuoteList(PublishQuote publishQuote) {
        return publishQuoteMapper.selectPublishQuoteList(publishQuote);
    }

    /**
     * 新增需求报价
     *
     * @param publishQuote 需求报价
     * @return 结果
     */
    @Override
    public int insertPublishQuote(PublishQuote publishQuote) {
        publishQuote.setCreateTime(LocalDateTime.now());
        return publishQuoteMapper.insertPublishQuote(publishQuote);
    }

    /**
     * 修改需求报价
     *
     * @param publishQuote 需求报价
     * @return 结果
     */
    @Override
    public int updatePublishQuote(PublishQuote publishQuote) {
        publishQuote.setUpdateTime(LocalDateTime.now());
        return publishQuoteMapper.updatePublishQuote(publishQuote);
    }

    /**
     * 批量删除需求报价
     *
     * @param quoteIds 需要删除的需求报价主键
     * @return 结果
     */
    @Override
    public int deletePublishQuoteByQuoteIds(Long[] quoteIds) {
        return publishQuoteMapper.deletePublishQuoteByQuoteIds(quoteIds);
    }

    /**
     * 删除需求报价信息
     *
     * @param quoteId 需求报价主键
     * @return 结果
     */
    @Override
    public int deletePublishQuoteByQuoteId(Long quoteId)
    {
        return publishQuoteMapper.deletePublishQuoteByQuoteId(quoteId);
    }

    /**
     * 获取发布需求详细信息(报价集合（包含留言）)
     * @param publishId
     * @return
     */
    @Override
    public List<PublishQuoteVo> getQuoteList(Long publishId) {
        List<PublishQuoteVo> quoteList = publishQuoteMapper.getQuoteList(publishId);
//        if (CollectionUtils.isNotEmpty(quoteList)) {
//            // 查询服务人员信息
//            for (PublishQuoteVo publishQuoteVo : quoteList) {
//                ServerUserListVo serverUserVo = serverUserService.getByServerId(publishQuoteVo.getServerUserId());
//                publishQuoteVo.setServerUser(serverUserVo);
//            }
//        }
         return quoteList;
    }

    /**
     * 删除报价
     * @param quoteId 报价id
     * @return
     */
    @Override
    public AjaxResult deleteQuote(Long quoteId) {

        //校验报价是否已经被指派
        PublishQuote publishQuote = publishQuoteMapper.selectPublishQuoteByQuoteId(quoteId);
        if(ObjectUtils.isEmpty(publishQuote)){
            throw new ArithmeticException("报价信息不存在");
        }
        Publish publish = publishService.selectPublishByPublishId(publishQuote.getPublishId());
        if(ObjectUtils.isEmpty(publish)){
            throw new ArithmeticException("需求信息不存在");
        }
        //只有待预约状态的需求的所属报价可删除
        if(!"001".equals(publish.getPublishState())){
            throw new ArithmeticException("当前报价不可删除");
        }
        PublishQuote quote = new PublishQuote();
        quote.setQuoteId(quoteId);
        quote.setDelFlag("2");
        quote.setUpdateTime(LocalDateTime.now());
        if(publishQuoteMapper.updatePublishQuote(quote)<1){
            throw new ArithmeticException("删除报价失败");
        }
        return AjaxResult.success();
    }

    /**
     * （服务人员）添加报价信息
     * @param param
     * @return
     */
    @Override
    public AjaxResult AddQuote(PublishQuoteParam param) {
        //根据服务人id查询服务人员数据
        ServerUserVo serverUserVo =   serverUserService.selectUserTime(param.getServerUserId());
        if(ObjectUtils.isEmpty(serverUserVo)){
            return AjaxResult.error("服务人员不存在，不可进行报价");
        }
        if(serverUserVo.getStopOrder() != 0){
            return AjaxResult.error("当前服务人员停止接单，不可进行报价");
        }

        //校验需求状态是未预约状态
        PublishManageVo publish = publishMapper.getPublishByPublishId(param.getPublishId());
        if(ObjectUtils.isEmpty(publish)){
            throw new ArithmeticException("需求不存在");
        }
        if(!"001".equals(publish.getPublishState())){
            throw new ArithmeticException("当前状态不可报价");
        }
        //查询是否进行过报价
       PublishQuote quote = publishQuoteMapper.selectPublishQuote(param);
        if(ObjectUtils.allNotNull(quote)){
            throw new ArithmeticException("同一需求不可重复报价");
        }

        //查询服务人员商家数据，校验商家是否营业
        Merchant merchant = merchantService.selectMerchantByServerId(param.getServerUserId());
        if(ObjectUtils.isEmpty(merchant)){
            throw new ArithmeticException("服务人员所属商家不存在");
        }
        if(!"001".equals(merchant.getBusinessState()) || !"002".equals(merchant.getShopState())){
            throw new ArithmeticException("当前商家状态不可进行报价");
        }

        //判断需求是否在商家服务范围内
        //商家与会员距离
        BigDecimal shortestDistance = null;
        // 计算距离
        shortestDistance = DistanceUtil.getShortestDistance( merchant.getLatitude(), merchant.getLongitude(),publish.getPublishAddress().getAddressLatitude(),
                publish.getPublishAddress().getAddressLongitude());

        BigDecimal maxDeliverDistance =null;
        if(merchant.getServiceDistance()==null){
            maxDeliverDistance = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("home.server.distance").getConfigValue());

        }else {
            maxDeliverDistance  = new BigDecimal(String.valueOf(merchant.getServiceDistance()));
        }
        //验证坐标是否超出范围
        if(shortestDistance.compareTo(maxDeliverDistance)>0){
            //超出配送范围
            throw new ArithmeticException("不可报价，需求超出商家服务范围");
        }

        PublishQuote publishQuote = new PublishQuote();
        BeanUtils.copyProperties(param, publishQuote);
        publishQuote.setMerchantId(merchant.getMerchantId());
        //单次服务标准时长为空时默认为1
        if(publishQuote.getSingleTime() == null){
            publishQuote.setTotalTime(new BigDecimal(1));
        } else {
            //报价总时长为报价数量乘以单次服务标准时长
            publishQuote.setTotalTime(publishQuote.getSingleTime().multiply(new BigDecimal(publishQuote.getQuoteCounts())));
        }

        //服务总价为报价单价乘以数量
        publishQuote.setTotalPrice(publishQuote.getSinglePrice().multiply(new BigDecimal(publishQuote.getQuoteCounts())));
        publishQuote.setCreateTime(LocalDateTime.now());

        if(publishQuoteMapper.insertPublishQuote(publishQuote)<1){
            throw new ArithmeticException("报价失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult showQuote(Long serverId) {
        //根据服务人id查询服务人员数据
        ServerUserVo serverUserVo =   serverUserService.selectUserTime(serverId);
        if(ObjectUtils.isEmpty(serverUserVo)){
            return AjaxResult.error("服务人员不存在，不可进行报价");
        }
        if(serverUserVo.getStopOrder() != 0){
            return AjaxResult.error("当前服务人员停止接单，不可进行报价");
        }

        //查询服务人员商家数据，校验商家是否营业
        Merchant merchant = merchantService.selectMerchantByServerId(serverId);
        if(ObjectUtils.isEmpty(merchant)){
            return AjaxResult.error("服务人员所属商家不存在");
        }
        if(!"001".equals(merchant.getBusinessState()) || !"002".equals(merchant.getShopState())){
            return AjaxResult.error("当前商家状态不可进行报价");
        }
        return AjaxResult.success();
    }

    /**
     * (服务人员)修改报价信息
     * @param param
     * @return
     */
    @Override
    public AjaxResult editQuote(PublishQuoteParam param) {
        PublishQuote quote = publishQuoteMapper.selectPublishQuoteByQuoteId(param.getQuoteId());
        if(ObjectUtils.isEmpty(quote)){
            throw new ArithmeticException("报价信息不存在");
        }
        Publish publish = publishMapper.selectPublishByPublishId(quote.getPublishId());
        if(ObjectUtils.isEmpty(publish)){
            throw new ArithmeticException("需求不存在");
        }
        if(!"001".equals(publish.getPublishState())){
            throw new ArithmeticException("当前状态不可修改报价信息");
        }
        PublishQuote publishQuote = new PublishQuote();
        BeanUtils.copyProperties(param, publishQuote);
        //单次服务标准时长为空时默认为1
        if(publishQuote.getSingleTime() == null){
            publishQuote.setSinglePrice(new BigDecimal(1));
        }
        //报价总时长为报价数量乘以单次服务标准时长
        publishQuote.setTotalTime(publishQuote.getSingleTime().multiply(new BigDecimal(publishQuote.getQuoteCounts())));
        //服务总价为报价单价乘以数量
        publishQuote.setTotalPrice(publishQuote.getSinglePrice().multiply(new BigDecimal(publishQuote.getQuoteCounts())));
        publishQuote.setUpdateTime(LocalDateTime.now());
        if(publishQuoteMapper.updatePublishQuote(publishQuote) < 1){
            throw new ArithmeticException("报价信息编辑失败");
        }
        return AjaxResult.success();

    }

    /**
     * 查询报价详情
     * @param quoteId
     * @return
     */
    @Override
    public PublishQuoteVo selectQuoteByQuoteId(Long quoteId) {
        return publishQuoteMapper.selectQuoteByQuoteId(quoteId);
    }

}
