package com.xxfc.platform.tour.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.constant.RestCode;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.RandomUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.GoodDataVO;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.tour.dto.*;
import com.xxfc.platform.tour.entity.*;
import com.xxfc.platform.tour.mapper.*;
import com.xxfc.platform.tour.vo.TourGoodVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 旅游商品表
 *
 * @author zjw
 * @email nishijjo@qq.com
 * @date 2019-06-06 11:41:51
 */
@Service
@Slf4j
public class TourGoodBiz extends BaseBiz<TourGoodMapper, TourGood> {

    @Autowired
    private TourGoodBannerBiz bannerBiz;
    @Autowired
    private TourGoodSiteBiz siteBiz;
    @Autowired
    private TourGoodTagBiz tagBiz;
    @Autowired
    private TourGoodSpeBiz speBiz;
    @Autowired
    private TourGoodVerificationBiz verificationBiz;

    @Autowired
    private UserFeign userFeign;

    /**
     * 查询旅游路线列表
     * @param page
     * @param limit
     * @param query
     * @param latitude
     * @param longitude
     * @param tagId
     * @param distance
     * @return
     */
    public ObjectRestResponse<PageDataVO<TourGood>> getGoodList(int page, int limit , String query , Double latitude, Double longitude, Integer tagId, Double distance){
        Map<String, Object> params = initParam(page, limit, query, latitude, longitude, tagId, distance);
        PageDataVO<TourGood> dataVO=null;
        if(latitude!=null&&latitude>0&&longitude!=null&&longitude>0){
            dataVO=PageDataVO.pageInfo(page, limit, ()->mapper.getCoordinateList(params));
        }else {
            dataVO=PageDataVO.pageInfo(page, limit, ()->mapper.getGoodList(params));
        }
        return new ObjectRestResponse().status(RestCode.SUCCESS.getStatus()).msg(RestCode.SUCCESS.getMsg()).data(dataVO);
    }

    private Map<String, Object> initParam(int page, int limit, String query, Double latitude, Double longitude, Integer tagId, Double distance) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("query",query);
        params.put("latitude",latitude);
        params.put("longitude",longitude);
        params.put("tagId",tagId);
        params.put("distance",distance);
        return params;
    }

    public TourGood getOne(Integer id) {
        return mapper.getOne(id);
    }


   //获取商品列表
    public PageDataVO<TourGoodVo> getAll(GoodSearchDTO dto){
        PageHelper.startPage(dto.getPage(),dto.getLimit());
        PageInfo<TourGoodVo> goodPageInfo = new PageInfo<>(mapper.findGoodList(dto));
        return PageDataVO.pageInfo(goodPageInfo);
    }

    //获取商品列表
    public ObjectRestResponse goodsEdit(TourGoodDTO dto){
      if(dto==null){
          return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
      }
        TourGood good=new TourGood();
        try {
            Long times=System.currentTimeMillis();
            BeanUtils.copyProperties(good,dto);
            Integer goodId=good.getId();
            good.setUpdTime(times);
            if(goodId==null||goodId==0){
                good.setCrtTime(times);
                mapper.insertSelective(good);
                goodId=good.getId();
            }else {
                mapper.updateByPrimaryKeySelective(good);
            }
            if(goodId>0){

               List<GoodBannerDTO>  bannerList=dto.getBannerDTOS();
               if(bannerList.size()>0){
                   List<Integer> bannerIds=new ArrayList<>();
                   for (GoodBannerDTO bannerDTO:bannerList){
                      Integer bannerId=bannerDTO.getId();
                       TourGoodBanner goodBanner=new TourGoodBanner();
                       BeanUtils.copyProperties(goodBanner,bannerDTO);
                       goodBanner.setGoodId(goodId);
                      if(bannerId==null||bannerId==0){
                          bannerBiz.insertSelective(goodBanner);
                          bannerId=goodBanner.getId();
                      }else {
                          bannerBiz.updateSelectiveById(goodBanner);
                      }
                       bannerIds.add(bannerId);
                   }
                   if(bannerIds.size()>0){
                       bannerBiz.delGoodBanner(goodId,bannerIds);
                   }

               }else{
                   bannerBiz.delGoodBanner(goodId,null);
               }
                List<GoodSiteDTO>  siteDTOList=dto.getSiteDTOS();
                List<Integer> sites=new ArrayList<>();
                if(siteDTOList.size()>0){
                    List<Integer> siteIds=new ArrayList<>();
                    for (GoodSiteDTO siteDTO:siteDTOList){
                        Integer siteId=siteDTO.getId();
                        TourGoodSite site=new TourGoodSite();
                        BeanUtils.copyProperties(site,siteDTO);
                        site.setGoodId(goodId);
                        if(siteId==null||siteId==0){
                            siteBiz.insertSelective(site);
                            siteId=site.getId();
                        }else {
                            siteBiz.updateSelectiveById(site);
                        }
                        siteIds.add(siteId);
                        if(site.getType()==0){
                            sites.add(siteId);
                        }
                    }
                    if(siteIds.size()>0){
                        siteBiz.delGoodSite(goodId,siteIds);
                    }
                }
                List<GoodTagDTO>  tagList=dto.getTagDTOS();
                if(tagList.size()>0){
                    List<Integer> tagIds=new ArrayList<>();
                    for (GoodTagDTO tagDTO:tagList){
                        Integer tagId=tagDTO.getTagId();
                        TourGoodTag tag=new TourGoodTag();
                        BeanUtils.copyProperties(tag,tagDTO);
                        tag.setGoodId(goodId);
                        TourGoodTag  tag1=tagBiz.selectOne(tag);
                        if(tag1==null){
                            tagBiz.insertSelective(tag);
                            tagId=tag.getId();
                        }else {
                           /* tag.setId(tag.getId());
                            tagBiz.updateSelectiveById(tag);*/
                            tagId=tag1.getId();
                        }
                        tagIds.add(tagId);
                    }
                    if(tagIds.size()>0){
                        tagBiz.delGoodTag(goodId,tagIds);
                    }
                }else{
                    tagBiz.delGoodTag(goodId,null);
                }
                List<GoodSpePriceDTO>  priceDTOList=dto.getPriceDTOS();
                List<Integer> prices=new ArrayList<>();
                if(siteDTOList.size()>0){
                    for (GoodSpePriceDTO priceDTO:priceDTOList){
                        Integer priceId=priceDTO.getId();
                        TourGoodSpePrice spePrice=new TourGoodSpePrice();
                        BeanUtils.copyProperties(spePrice,priceDTO);
                        BigDecimal price=good.getPrice();
                        BigDecimal childPrice=good.getChildPrice();
                        spePrice.setPrice(price);
                        spePrice.setChildPrice(childPrice);
                        spePrice.setGoodId(goodId);
                        List<BaseUserMemberLevel> levelsList=userFeign.levels();
                        if(levelsList.size()>0){
                            JSONArray array=new JSONArray();
                            for(BaseUserMemberLevel memberLevel :levelsList){
                                JSONObject obj=new JSONObject();
                                Integer level=memberLevel.getLevel();
                                Integer discount=memberLevel.getDiscount();
                                BigDecimal price1=price.multiply(new BigDecimal(discount+"")).divide(new BigDecimal("100"))
                                        .setScale(2, RoundingMode.HALF_UP);
                                BigDecimal price2=childPrice.multiply(new BigDecimal(discount+"")).divide(new BigDecimal("100"))
                                        .setScale(2, RoundingMode.HALF_UP);
                                obj.put("level",level);
                                obj.put("price",price1);
                                obj.put("childPrice",price2);
                                array.add(obj);
                            }
                            if(array.size()>0){
                                String json=array.toJSONString();
                                spePrice.setMemberPrice(json);
                            }
                        }
                        if(priceId==null||priceId==0){
                            speBiz.insertSelective(spePrice);
                            priceId=spePrice.getId();
                        }else {
                            speBiz.updateSelectiveById(spePrice);
                        }
                        prices.add(priceId);
                    }
                    if(prices.size()>0){
                        speBiz.delGoodSpe(goodId,prices);
                    }
                }
                if(sites.size()>0){
                    List<Integer> vids=new ArrayList<>();
                    List<TourGoodVerification> verifications=new ArrayList<>();
                    for (Integer siteId:sites){
                        if(prices.size()>0){
                            for(Integer priceId:prices){
                                TourGoodVerification verification=new TourGoodVerification();
                                verification.setGoodId(goodId);
                                verification.setSiteId(siteId);
                                verification.setSpeId(priceId);
                                verification.setIsDel(0);
                                TourGoodVerification  verification1=verificationBiz.selectOne(verification);
                                if(verification1==null){
                                    verification.setTotalPerson(0);
                                    verification.setVerificationPerson(0);
                                    verification.setStatus(0);
                                    verifications.add(verification);
                                }else {
                                    vids.add(verification1.getId());
                                }

                            }
                        }

                    }

                    if(vids.size()>0){
                        verificationBiz.delGoodVerification(goodId,vids);
                    }
                    if(verifications.size()>0){
                        for (TourGoodVerification verif:verifications)
                        verificationBiz.insertSelective(verif);
                    }

                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return   ObjectRestResponse.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
        return ObjectRestResponse.succ();
    }

    //删除商品
    public ObjectRestResponse delGoodById(Integer id) {
        if (id == null || id == 0) {
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        try {
            TourGood TourGood=new TourGood();
            TourGood.setId(id);
            TourGood.setIsDel(1);
            updateSelectiveById(TourGood);
            return ObjectRestResponse.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("---商品详情---id=====" + id + "----异常---msg===" + e.getMessage());
            return ObjectRestResponse.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    //上下架商品
    public ObjectRestResponse upStatusById(Integer id,Integer status) {
        if (id == null || id == 0||status == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        try {
            TourGood TourGood=new TourGood();
            TourGood.setId(id);
            TourGood.setStatus(status);
            updateSelectiveById(TourGood);
            return ObjectRestResponse.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("---商品详情---id=====" + id + "----异常---msg===" + e.getMessage());
            return ObjectRestResponse.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    /**
     * 首页旅游列表
     * @param page
     * @param limit
     * @return
     */
    public  List<GoodDataVO> getAllByHome(Integer page, Integer limit){
        return  mapper.findAllByHome((page-1)*limit,limit);
    };

    /**
     * 获取指定数量的随机旅游路线
     * @return
     */
    public ObjectRestResponse findRandomVehicle(Integer number) {
        number = number == null ? 2 : number;
        Map<String, Object> param = new HashMap<>();
        List<TourGood> list = mapper.getCoordinateList(param);
        Set<TourGood> resultList = new HashSet<>();
        if(CollectionUtils.isNotEmpty(list)) {
            if(number >= list.size()) {
                return ObjectRestResponse.succ(list);
            }
            Set<Integer> set = new HashSet<>();
            RandomUtil.randomSet(list.size(), number, set, number);
            for(Integer i : set) {
                resultList.add(list.get(i));
            }
        }
        return ObjectRestResponse.succ(resultList);
    }
}


