package com.younike.system.service.impl;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.core.domain.model.LoginUser;
import com.younike.common.exception.GlobalException;
import com.younike.common.utils.SecurityUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.OrderVo;
import com.younike.system.domain.vo.PublishManageVo;
import com.younike.system.domain.vo.PublishQuoteVo;
import com.younike.system.domain.vo.PublishUpdateVo;
import com.younike.system.mapper.*;
import com.younike.system.param.PublishQueryParam;
import com.younike.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 发布需求Service业务层处理
 *
 * @author elev
 * @date 2022-01-20
 */
@Service
public class PublishServiceImpl implements IPublishService {
    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private IMemberAddressService memberAddressService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private PublishAddressMapper publishAddressMapper;

    @Autowired
    private PublishImageMapper publishImageMapper;

    @Autowired
    private PublishQuoteMapper publishQuoteMapper;

    @Autowired
    private IServerUserFollowService followService;

    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private IGoodsService goodsServer;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IServerUserService serverUserService;

    @Override
    public List<PublishManageVo> publishAdminList(PublishQueryParam param) {


        List<PublishManageVo> publishManageList = publishMapper.publishManageList(param);
        if (publishManageList == null || publishManageList.size() == 0) {
            return publishManageList;
        }

        publishManageList.forEach(publishManageVo -> {
            if (publishManageVo.getPublishQuoteList() == null || publishManageVo.getPublishQuoteList().size() == 0) {
                publishManageVo.setQuoteCount(0);
            } else {
                publishManageVo.setQuoteCount(publishManageVo.getPublishQuoteList().size());
            }
        });
        return publishManageList;
    }

    @Override
    public List<PublishManageVo> publishManageList(PublishQueryParam param) {
        List<PublishManageVo> publishManageList = publishMapper.publishManageList(param);
        if (publishManageList == null || publishManageList.size() == 0) {
            return publishManageList;
        }

        publishManageList.forEach(publishManageVo -> {
            if (publishManageVo.getPublishQuoteList() == null || publishManageVo.getPublishQuoteList().size() == 0) {
                // 没有人报价
                publishManageVo.setQuoteCount(0);
                if (publishManageVo.getPublishState().equals("001")) {
                    publishManageVo.setStatus(0);
                }
                if (publishManageVo.getPublishState().equals("004")) {
                    publishManageVo.setStatus(4);
                }
            } else {
                // 有人报价
                publishManageVo.setQuoteCount(publishManageVo.getPublishQuoteList().size());
                if (publishManageVo.getPublishState().equals("001")) {
                    List<PublishQuote> collect = publishManageVo.getPublishQuoteList().stream()
                            .filter(publishQuote -> Objects.equals(publishQuote.getMerchantId(), param.getMerchantId()))
                            .collect(Collectors.toList());
                    if (collect.size() == 0) {
                        publishManageVo.setStatus(0);
                    } else {
                        publishManageVo.setStatus(1);
                    }
                }
                if (publishManageVo.getPublishState().equals("002") || publishManageVo.getPublishState().equals("003")) {
                    if (Objects.equals(publishManageVo.getBidMerchantId(), param.getMerchantId())) {
                        publishManageVo.setStatus(2);
                    } else {
                        publishManageVo.setStatus(3);
                    }
                }
                if (publishManageVo.getPublishState().equals("004")) {
                    publishManageVo.setStatus(4);
                }
            }

        });
        return publishManageList;
    }

    @Override
    public AjaxResult deleteByPublishId(Long publishId) {
        Publish publish = this.publishMapper.selectPublishByPublishId(publishId);
        if (publish == null) {
            return AjaxResult.error("参数错误");
        }
        if (StringUtils.isEmpty(publish.getPublishState())
                || publish.getPublishState().equals("002")
                || publish.getPublishState().equals("003")) {
            return AjaxResult.error("当前任务已预约不可删除");
        }
        Publish updatePublish = new Publish();
        updatePublish.setPublishId(publishId);
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            updatePublish.setUpdateBy(loginUser.getUsername());
            updatePublish.setUpdateTime(LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
        }
        updatePublish.setDelFlag("2");
        return this.publishMapper.updatePublish(updatePublish) > 0 ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult publishInsert(PublishUpdateVo publishUpdateVo) {
        if (publishUpdateVo == null
                || StringUtils.isEmpty(publishUpdateVo.getName())
                || publishUpdateVo.getCategoryId() == null
                || publishUpdateVo.getAddressId() == null) {
            return AjaxResult.error("参数错误");
        }
        MemberAddress memberAddress = memberAddressService.selectMemberAddressByAddressId(publishUpdateVo.getAddressId());
        Category category = categoryService.selectCategoryByCategoryId(publishUpdateVo.getCategoryId());
        if (memberAddress == null) {
            return AjaxResult.error("地址选择错误");
        }
        if (category == null) {
            return AjaxResult.error("分类选择错误");
        }
        Publish publish = new Publish();
        publish.setPublishDesc(publishUpdateVo.getPublishDesc());
        publish.setCateId(publishUpdateVo.getCategoryId());
        if(!ObjectUtils.isEmpty(category.getParentId())){
            publish.setParentCateId(Long.parseLong(category.getParentId()));
        }
        publish.setName(publishUpdateVo.getName());
        publish.setCreateTime(LocalDateTime.now());
        publish.setMemberId(publishUpdateVo.getMemberId());


        int insertPublish = this.publishMapper.insertPublish(publish);
        if (insertPublish < 1) {
            throw new GlobalException("发布失败");
        }
        PublishAddress publishAddress = new PublishAddress();
        BeanUtils.copyProperties(memberAddress, publishAddress);
        publishAddress.setCreateTime(LocalDateTime.now());
        publishAddress.setPublishId(publish.getPublishId());
        publishAddress.setAddressLongitude(memberAddress.getLongitude());
        publishAddress.setAddressLatitude(memberAddress.getLatitude());
        int insertPublishAddress = publishAddressMapper.insertPublishAddress(publishAddress);
        if (insertPublishAddress < 1) {
            throw new GlobalException("发布失败");
        }
        if (publishUpdateVo.getPublishImageList() == null || publishUpdateVo.getPublishImageList().size() == 0) {
            return AjaxResult.success("发布成功");
        }
        AtomicInteger sort = new AtomicInteger();
        publishUpdateVo.getPublishImageList().forEach(publishImage -> {
            publishImage.setPublishId(publish.getPublishId());
            if (StringUtils.isEmpty(publishImage.getType())) {
//                publishImage.setType("001");
                publishImage.setSorting(sort.incrementAndGet());
            }
        });
        int insertBatch = publishImageMapper.insertBatch(publishUpdateVo.getPublishImageList());
        if (insertBatch < 0) {
            throw new GlobalException("保存图片失败");
        }
        return AjaxResult.success("发布成功");
    }

    /**
     * 查询发布需求
     *
     * @param publishId 发布需求主键
     * @return 发布需求
     */
    @Override
    public Publish selectPublishByPublishId(Long publishId) {
        return publishMapper.selectPublishByPublishId(publishId);
    }

    /**
     * 查询发布需求列表
     *
     * @param publish 发布需求
     * @return 发布需求
     */
    @Override
    public List<Publish> selectPublishList(Publish publish) {
        return publishMapper.selectPublishList(publish);
    }

    /**
     * 新增发布需求
     *
     * @param publish 发布需求
     * @return 结果
     */
    @Override
    public int insertPublish(Publish publish) {
        publish.setCreateTime(LocalDateTime.now());
        return publishMapper.insertPublish(publish);
    }

    /**
     * 修改发布需求
     *
     * @param publish 发布需求
     * @return 结果
     */
    @Override
    public int updatePublish(Publish publish) {
        publish.setUpdateTime(LocalDateTime.now());
        return publishMapper.updatePublish(publish);
    }

    /**
     * 批量删除发布需求
     *
     * @param publishIds 需要删除的发布需求主键
     * @return 结果
     */
    @Override
    public int deletePublishByPublishIds(Long[] publishIds) {
        return publishMapper.deletePublishByPublishIds(publishIds);
    }

    /**
     * 删除发布需求信息
     *
     * @param publishId 发布需求主键
     * @return 结果
     */
    @Override
    public int deletePublishByPublishId(Long publishId)
    {
        return publishMapper.deletePublishByPublishId(publishId);
    }

    /**
     * 查询我发布需求列表
     * @param param
     * @return
     */
    @Override
    public List<PublishManageVo> mePublishList(PublishQueryParam param) {
        List<PublishManageVo> publishManageList = publishMapper.mePublishList(param);
        return publishManageList;
    }

    /**
     * 下架需求
     * @param publishId 需求id
     * @return
     */
    @Override
    public AjaxResult soldOut(Long publishId) {
        //校验需求状态是否可以进行下架
        Publish publish = publishMapper.selectPublishByPublishId(publishId);
        if(ObjectUtils.isEmpty(publish)){
            throw  new ArithmeticException("需求不存在");
        }
        if(!publish.getPublishState().equals("001")){
            throw new ArithmeticException("需求当前不可下架");
        }
        Publish publish1 = new Publish();
        publish1.setPublishId(publishId);
        publish1.setPublishState("004");
        if(publishMapper.updatePublish(publish1)<1){
            return AjaxResult.error("下架失败");
        }
        return AjaxResult.success();
    }

    /**
     *上架需求
     * @param publishId
     * @return
     */
    @Override
    public AjaxResult putaway(Long publishId) {
        //校验需求状态是否可以进行上架
        Publish publish = publishMapper.selectPublishByPublishId(publishId);
        if(ObjectUtils.isEmpty(publish)){
            throw  new ArithmeticException("需求不存在");
        }
        if(!publish.getPublishState().equals("004")){
            throw new ArithmeticException("需求当前不可上架");
        }
        Publish publish1 = new Publish();
        publish1.setPublishId(publishId);
        publish1.setPublishState("001");
        if(publishMapper.updatePublish(publish1)<1){
            return AjaxResult.error("下架失败");
        }
        return AjaxResult.success();
    }

    /**
     * 获取发布需求详细信息(包含地址信息)
     * @param publishId
     * @return
     */
    @Override
    public AjaxResult getPublishByPublishId(Long publishId) {

        PublishManageVo publishByPublishId = publishMapper.getPublishByPublishId(publishId);
        if(ObjectUtils.isEmpty(publishByPublishId)){
            throw new ArithmeticException("需求不存在");
        }
        return AjaxResult.success(publishByPublishId);
    }

    /**
     * 编辑需求
     * @param publish
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editPublish(PublishUpdateVo publish) {

        if (publish == null
                || StringUtils.isEmpty(publish.getName())
                || publish.getCategoryId() == null
                || publish.getAddressId() == null) {
            return AjaxResult.error("参数错误");
        }

        //根据需求id查询数据判断是否已经有报价（有报价的情况下不可更改）
        PublishManageVo publishByPublishId = publishMapper.getPublishByPublishId(publish.getPublishId());
        if(ObjectUtils.isEmpty(publishByPublishId)){
            throw new ArithmeticException("需求不存在");
        }
        if(publishByPublishId.getQuoteCount()>0){
            throw new ArithmeticException("已经有报价，不可编辑");
        }

        Category category = categoryService.selectCategoryByCategoryId(publish.getCategoryId());
        if (category == null) {
            return AjaxResult.error("分类选择错误");
        }
        Publish publishUpdet = new Publish();
        publishUpdet.setPublishId(publish.getPublishId());
        publishUpdet.setPublishDesc(publish.getPublishDesc());
        publishUpdet.setCateId(publish.getCategoryId());
        publishUpdet.setParentCateId(Long.parseLong(category.getParentId()));
        publishUpdet.setName(publish.getName());
        publishUpdet.setUpdateTime(LocalDateTime.now());

        int insertPublish = this.publishMapper.updatePublish(publishUpdet);
        if (insertPublish < 1) {
            throw new GlobalException("更新失败");
        }

        //判断地址是否重新进行选择,如果重新进行选择，则更新需求地址数据
        if(!ObjectUtils.isEmpty(publish.getUpdateAddress()) || publish.getUpdateAddress()){
            MemberAddress memberAddress = memberAddressService.selectMemberAddressByAddressId(publish.getAddressId());
            if (memberAddress == null) {
                return AjaxResult.error("地址选择错误");
            }
            PublishAddress publishAddress = new PublishAddress();
            BeanUtils.copyProperties(memberAddress, publishAddress);
            publishAddress.setUpdateTime(LocalDateTime.now());
            publishAddress.setPublishId(publish.getPublishId());
            publishAddress.setAddressLongitude(memberAddress.getLongitude());
            publishAddress.setAddressLatitude(memberAddress.getLatitude());
            publishAddress.setPublishId(publishUpdet.getPublishId());
            int insertPublishAddress = publishAddressMapper.updatePublishAddress(publishAddress);
            if (insertPublishAddress < 1) {
                throw new GlobalException("更新失败");
            }
        }

        //要添加的资源集合List
        List<PublishImage> publishImages = new ArrayList<>();

        AtomicInteger sort = new AtomicInteger();
        publish.getPublishImageList().forEach(publishImage -> {

            //发布需求id为空的为新增
            if(publishImage.getImageId()==null){
                if (StringUtils.isEmpty(publishImage.getType())) {
//                    publishImage.setType("001");
                    publishImage.setSorting(sort.incrementAndGet());
                }
                publishImage.setPublishId(publish.getPublishId());
                publishImages.add(publishImage);
            }
        });
        if(publishImages.size()>0){
            int insertBatch = publishImageMapper.insertBatch(publishImages);
            if (insertBatch < 1) {
                throw new GlobalException("保存图片失败");
            }
        }

        //删除资源集合
        if( publish.getDelList().length > 0){
            if(publishImageMapper.deletePublishImageByImageIds(publish.getDelList()) < 1){
                throw new GlobalException("删除图片失败");
            }
        }

        return AjaxResult.success("发布成功");
    }

    /**
     * 查询我发布需求条数
     * @param memberId
     * @return
     */
    @Override
    public AjaxResult mePublishCount(Long memberId) {
      List<Publish> publishList = publishMapper.mePublishCount(memberId);
        return AjaxResult.success(publishList.size());
    }

    /**
     * 服务端查询任务广场列表
     * @param param
     * @return
     */
    @Override
    public List<PublishManageVo> publishServerList(PublishQueryParam param) {

        List<PublishManageVo> publishManageVos = new ArrayList<>();

        //查询关注类型列表
//        ServerUserFollow serverUserFollow = new ServerUserFollow();
//        serverUserFollow.setServerUserId(param.getServerId());
//        List<ServerUserFollow> serverUserFollows = followService.selectServerUserFollowList(serverUserFollow);
//        if(ObjectUtils.isEmpty(serverUserFollows) || serverUserFollows.size()<0){
//            return publishManageVos;
//        }
//        List<Long> longs = new ArrayList<>();
//        serverUserFollows.forEach(follow -> {
//            longs.add(follow.getCategoryId());
//        });
//        param.setParentCateIdS(longs);

        //查询服务人员对应的店铺
//       Merchant merchant = merchantService.selectMerchantByServerId(param.getServerId());
//       if(ObjectUtils.isEmpty(merchant)){
//           throw new ArithmeticException("服务人员或所属商家不存在");
//       }
//
//        //筛选在服务范围内的数据
//        //服务人员服务范围
//        BigDecimal maxDeliverDistance =null;
//        if(merchant.getServiceDistance()==null){
//            maxDeliverDistance = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("home.server.distance").getConfigValue());
//        }else {
//            maxDeliverDistance  = new BigDecimal(String.valueOf(merchant.getServiceDistance()));
//        }
//
//        param.setMerchantLatitude(merchant.getLatitude());
//        param.setMerchantLongitude(merchant.getLongitude());
//        param.setMaxDeliverDistance(maxDeliverDistance);

        List<PublishManageVo> publishServerList =  publishMapper.publishServerList(param);
//
//        BigDecimal finalMaxDeliverDistance = maxDeliverDistance;
//        publishServerList.forEach(publishManageVo -> {
//            //商家与会员距离
//            BigDecimal shortestDistance = null;
//            // 计算距离
//            shortestDistance = DistanceUtil.getShortestDistance( merchant.getLatitude(), merchant.getLongitude(),publishManageVo.getPublishAddress().getAddressLatitude(),
//                    publishManageVo.getPublishAddress().getAddressLongitude());
//            //验证坐标是否超出范围
//            if(shortestDistance.compareTo(finalMaxDeliverDistance)<0){
//                //在配送范围内
//                publishManageVos.add(publishManageVo);
//            }
//
//       });
//
//
        return publishServerList;
    }

    /**
     * 服务端查询任务广场我报价的需求列表
     * @param param
     * @return
     */
    @Override
    public List<PublishManageVo> publishList(PublishQueryParam param) {

        List<PublishManageVo> publishServerList =  publishMapper.quoteList(param);

        if(ObjectUtils.isEmpty(publishServerList) || publishServerList.size()<1){
            return publishServerList;
        }


        publishServerList.forEach(publishManageVo -> {
                //判断发布状态是否为publish_state 待预约001 ，002已预约，003已完成，004已下架）
                /**
                 * 任务状态  未报价 0 已报价 1 被选中 2 被抢单 3
                 */
                if("001".equals(publishManageVo.getPublishState())){
                    publishManageVo.setStatus(1);
                }else {
                    //判断中标用户是否是当前服务人员
                    if(publishManageVo.getBidServerUserId().equals(param.getServerId())){
                        publishManageVo.setStatus(2);
                    }else {
                        publishManageVo.setStatus(3);
                    }
                }
        });

        return publishServerList;
    }

    /**
     * （服务人员） 获取发布需求详细信息
     * @param param
     * @return
     */
    @Override
    public AjaxResult selectPublishBy(PublishQueryParam param) {
        PublishManageVo publishByPublishId = publishMapper.selectPublishBy(param);
        if(ObjectUtils.isEmpty(publishByPublishId)){
            throw new ArithmeticException("需求不存在");
        }
        return AjaxResult.success(publishByPublishId);
    }

    /**
     * 订单变更  （任务状态变更）
     * 如果是未付款则任务回到未指派状态  商品进行逻辑删除
     * 如果服务人员未开始服务则任务回到未指派状态  商品进行逻辑删除
     * 根据订单号查询，判断服务人员是否开始服务，
     * 如果服务人员已经开始服务则任务完成，
     * 如果订单已经完成则任务完成
     * @param orderId
     * @return
     */
    @Override
    public Boolean cancelPublishOrder(Long orderId){

        OrderVo orderVo = orderService.selectPublishInfo(orderId);
        if(ObjectUtils.isEmpty(orderVo)){
            return false;
        }
        //服务id为空直接跳过
        if(ObjectUtils.isEmpty(orderVo.getPublishId())){
            return true;
        }
        Publish publish = new Publish();
        publish.setPublishId(orderVo.getPublishId());
        //未开始服务(未付款)
        if("000".equals(orderVo.getOrderState())){
            publish.setPublishState("001");
            Goods goods = new Goods();
            goods.setGoodsId(Long.parseLong(orderVo.getGoodsId()));
            goods.setDelFlag("2");
            if(goodsServer.updateGoods(goods) < 1 || this.updatePublish(publish) < 1){
                return false;
            }
        }
        //未开始服务
        if( "001".equals(orderVo.getOrderState())){
            publish.setPublishState("001");
            Goods goods = new Goods();
            goods.setGoodsId(Long.parseLong(orderVo.getGoodsId()));
            goods.setDelFlag("2");
            if(goodsServer.updateGoods(goods)<1 && this.updatePublish(publish)<1) {
                return false;
            }
        }
        //已经开始服务
        if("002".equals(orderVo.getOrderState())){
            publish.setPublishState("003");
            if(this.updatePublish(publish)<1){
                return false;
            }
        }
        //订单已完成
        if("004".equals(orderVo.getOrderState())){
            publish.setPublishState("003");
            if(this.updatePublish(publish)<1){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询任务广场入口数据
     * @param param
     * @return
     */
    @Override
    public List<PublishManageVo> taskList(PublishQueryParam param) {
        return publishMapper.taskList(param);
    }

    /**
     * 查询发布需求详细信息
     *
     * @param publishId
     * @return
     */
    @Override
    public AjaxResult getPublishDetail(Long publishId) {
        PublishManageVo publishManageVo = publishMapper.getPublishDetail(publishId);
        if (publishManageVo == null) {
            return AjaxResult.error("需求详情不存在!");
        }
        // 查询需求资源列表
        PublishImage publishImage = new PublishImage();
        publishImage.setPublishId(publishId);
        List<PublishImage> publishImageList = publishImageMapper.selectPublishImageList(publishImage);
        publishManageVo.setPublishImageList(publishImageList);

        // 查询需求报价列表
        List<PublishQuoteVo> quoteVoList = publishQuoteMapper.getQuoteList(publishId);
        publishManageVo.setQuoteVoList(quoteVoList);
        if (CollectionUtils.isEmpty(quoteVoList)) {
            // 没有人报价
            publishManageVo.setQuoteCount(0);
            if (Objects.equals(publishManageVo.getPublishState(), "001")) {
                publishManageVo.setStatus(0);
            } else if (Objects.equals(publishManageVo.getPublishState(), "004")) {
                publishManageVo.setStatus(4);
            }
        } else {
            // 有人报价
            publishManageVo.setQuoteCount(quoteVoList.size());
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            // 查询用户对应商家信息
            Merchant merchant = merchantService.selectMerchantByAdminId(loginUser == null ? null : loginUser.getUserId());
            Long merchantId = merchant == null ? null : merchant.getMerchantId();
            if (Objects.equals(publishManageVo.getPublishState(), "001")) {
                List<PublishQuoteVo> collect = quoteVoList.stream()
                        .filter(publishQuoteVo -> Objects.equals(publishQuoteVo.getMerchantId(), merchantId))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    publishManageVo.setStatus(0);
                } else {
                    publishManageVo.setStatus(1);
                }
            } else if (Objects.equals(publishManageVo.getPublishState(), "002") || Objects.equals(publishManageVo.getPublishState(), "003")) {
                if (Objects.equals(publishManageVo.getBidMerchantId(), merchantId)) {
                    publishManageVo.setStatus(2);
                } else {
                    publishManageVo.setStatus(3);
                }
            } else if (Objects.equals(publishManageVo.getPublishState(), "004")) {
                publishManageVo.setStatus(4);
            }
        }

        // 查询需求地址信息
        PublishAddress publishAddress = publishAddressMapper.selectPublishAddressByPublishId(publishId);
        publishManageVo.setPublishAddress(publishAddress);

        return AjaxResult.success("查询成功", publishManageVo);
    }

}
