package com.liquidnet.service.platform.service.impl.smile;

import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.goblin.constant.SmileRedisConst;
import com.liquidnet.service.goblin.dto.vo.CommissionVO;
import com.liquidnet.service.goblin.dto.vo.SmileSellDataDetailVO;
import com.liquidnet.service.goblin.dto.vo.SellDataOneVO;
import com.liquidnet.service.goblin.dto.vo.SmileSellDataVO;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketsMapper;
import com.liquidnet.service.platform.utils.ObjectUtil;
import com.liquidnet.service.smile.entity.SmileUser;
import com.liquidnet.service.smile.mapper.SmileUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-20
 */
@Service
@Slf4j
public class SellDataInfoImpl {
    @Autowired
    RedisDataSourceUtil redisDataSourceUtil;
    @Autowired
    SmileUserMapper smileUserMapper;
    @Autowired
    private KylinOrderTicketsMapper orderTicketsMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;


    public static void main(String[] args) {
    }

   public void setData(){
       int count=smileUserMapper.getCount();
       int pageSize=1000;
       int page=(count/pageSize);
       for(int p=0;p<=page;p++){
           int offest=p*pageSize;
           log.info("用户{}",offest);
           List<SmileUser>  list=smileUserMapper.pageUser(offest,pageSize);
           userJob(list);
       }
   }
   // 每个用户执行的
    public void userJob( List<SmileUser>  list){
        for(SmileUser smileUser:list){
            //-- 看这个人有哪些演出维度的订单  (支付的、演出id，该用户的。)
            if(StringUtil.isNotBlank(smileUser.getUid())){
                try {
                    //  //获取 该人 该演出 的所有订单 (6个月)
                    List<Map> list1=orderTicketsMapper.getUserOrder(smileUser.getUid());
                    for(Map a:list1){
                        String performanceId=a.get("yanchuId")==null?"":a.get("yanchuId").toString();
                        String yanChuName=a.get("title")==null?"":a.get("title").toString();
                            //判断是否 已经跑过一遍了
                        if(redisDataSourceUtil.getRedisSweetUtil().hasKey(SmileRedisConst.SELL_SHOW_PAYMENT_ENDJOB.concat(performanceId).concat(smileUser.getUid()))){
                            continue;
                        }
                        //获取 该人 该演出 的所有订单
                        List<Map> list2=orderTicketsMapper.getUserSellOneDate(smileUser.getUid(),performanceId);
                        ArrayList<SellDataOneVO> listSellDataOneVo= ObjectUtil.getSellDataOneVOArrayList();
                        Map commission=orderTicketsMapper.getUserCommission(smileUser.getUid());
                        for(Map a1:list2){
                            SellDataOneVO sellDataOneVO=SellDataOneVO.getNew();
                            //票务类型
                            sellDataOneVO.setTicketName(a1.get("title")==null?"":a1.get("title").toString());
                            //数量
                            sellDataOneVO.setTicketNumber(a1.get("number")==null?0:Integer.parseInt(a1.get("number").toString()));
                            //总金额
                            sellDataOneVO.setSellPrice(new BigDecimal(a1.get("price")==null?"0":a1.get("price").toString()));
                            //票提
                            sellDataOneVO.setPiaoTi(new BigDecimal(a1.get("paioTi")==null?"":a1.get("paioTi").toString()));
                            //佣金
                            sellDataOneVO.setCommission(new BigDecimal(a1.get("commiss")==null?"0":a1.get("commiss").toString()));
                            sellDataOneVO.setTicketId(a1.get("ticketId")==null?"":a1.get("ticketId").toString());
                            if(null!=a){
                                sellDataOneVO.setChouChengCommission(new BigDecimal(commission.get("commiss")==null?"0":commission.get("commiss").toString()));
                            }
                            //sellDataOneVO
                            listSellDataOneVo.add(sellDataOneVO);
                            if(StringUtils.isNotBlank(sellDataOneVO.getTicketId())){
                                setDataDetial(smileUser.getUid(),a1.get("ticketId").toString());
                            }
                        }
                        Map allDate=orderTicketsMapper.getUserSellAllDate(smileUser.getUid(),performanceId);
                        SmileSellDataVO smileSellDataVO = SmileSellDataVO.getNew();
                        if(null!=allDate){
                            //活动名称   需要再查 目前没有
                            smileSellDataVO.setDeltag(0);
                            smileSellDataVO.setSellDataId(smileUser.getUid().concat(performanceId));
                            smileSellDataVO.setActiveName(yanChuName);
                            smileSellDataVO.setSellAmount(new BigDecimal(allDate.get("price")==null?"0":allDate.get("price").toString()));
                            smileSellDataVO.setSellNumber(new BigDecimal(allDate.get("number")==null?"0":allDate.get("number").toString()));
                            smileSellDataVO.setTotalCommission(new BigDecimal(allDate.get("commiss")==null?"0":allDate.get("commiss").toString()));
                            smileSellDataVO.setSellDataOneVO(listSellDataOneVo);
                            smileSellDataVO.setUpdateTime(LocalDateTime.now());
                            //redis 里面放入
                            redisDataSourceUtil.getRedisSweetUtil().set(SmileRedisConst.SELL_DATA.concat(smileUser.getUid()).concat(performanceId), smileSellDataVO);
                            Query query = Query.query(Criteria.where("sellDataId").is(smileSellDataVO.getSellDataId()));
                            Document document = (Document)mongoConverter.convertToMongoType(smileSellDataVO);
                            Update update = Update.fromDocument(document);
                            mongoTemplate.upsert(query, update, SmileSellDataVO.class, SmileSellDataVO.class.getSimpleName());
/*
                            if(mongoTemplate.exists(Query.query(Criteria.where("sellDataId").is(smileSellDataVO.getSellDataId())), SmileSellDataVO.class, SmileSellDataVO.class.getSimpleName())){
                                mongoTemplate.remove(Query.query(Criteria.where("sellDataId").is(smileSellDataVO.getSellDataId())), SmileSellDataVO.class, SmileSellDataVO.class.getSimpleName());
                            }
                            //mongodb 里面放入
                            mongoTemplate.insert(smileSellDataVO, SmileSellDataVO.class.getSimpleName());*/
                        }
                        if(redisDataSourceUtil.getRedisSweetUtil().hasKey(SmileRedisConst.SELL_SHOW_PAYMENT.concat(performanceId).concat(smileUser.getUid()))){
                            redisDataSourceUtil.getRedisSweetUtil().set(SmileRedisConst.SELL_SHOW_PAYMENT_ENDJOB.concat(performanceId).concat(smileUser.getUid()),"1");
                        }
                    }

                }catch (Exception e){
                    log.info(String.valueOf(e));
                    log.info("用户的uid{}",smileUser.getUid());
                }

            }

        }
    }
    /**
     * 设置票维度 的订单详情
     */
   public void setDataDetial(String agentId,String ticketId){
       List<Map> list= orderTicketsMapper.getUserSellDetail(agentId,ticketId);
       SmileSellDataDetailVO smileSellDataDetailVO = SmileSellDataDetailVO.getNew();
       smileSellDataDetailVO.setDataId(agentId+ticketId);
       smileSellDataDetailVO.setList(list);
       // mongodb
       Query query = Query.query(Criteria.where("dataId").is(smileSellDataDetailVO.getDataId()));
       Document document = (Document)mongoConverter.convertToMongoType(smileSellDataDetailVO);
       Update update = Update.fromDocument(document);
       mongoTemplate.upsert(query, update, SmileSellDataDetailVO.class, SmileSellDataDetailVO.class.getSimpleName());
      /* mongoTemplate.insert(smileSellDataDetailVO, SmileSellDataDetailVO.class.getSimpleName());*/
   }

    /**
     * 设置佣金
     */
   public void setCommission(){
       //1、查到用户
       List<SmileUser>  list=smileUserMapper.selectUserList(null);
       for(SmileUser smileUser:list){
           if(StringUtil.isNotBlank(smileUser.getUid())){
               BigDecimal daiRuZhang=new BigDecimal(0);
               BigDecimal keJieSuan=new BigDecimal(0);
               //查看该用户的演出列表
               List<Map> userPerformanceList=orderTicketsMapper.getUserPerformance(smileUser.getUid());
               for(Map a: userPerformanceList){
                    //取出id 查看是否结算
                   String performanceId= a.get("performanceId")==null?"":a.get("performanceId").toString();
                   if(redisDataSourceUtil.getRedisSweetUtil().hasKey(SmileRedisConst.SELL_SHOW_PAYMENT.concat(performanceId).concat(smileUser.getUid()))){
                       //已结算（已完成）
                       a.put("status","3");
                   }else{
                       if(null!=a.get("timeEnd")){
                           java.sql.Timestamp  timeEnd= (java.sql.Timestamp) a.get("timeEnd");
                           if(timeEnd.after(new Date(System.currentTimeMillis()))){
                               //待入账（项目未结束）
                               a.put("status","1");
                               daiRuZhang=daiRuZhang.add(a.get("commiss")==null?new BigDecimal(0):new BigDecimal(a.get("commiss").toString()));
                           }else{
                               //演出已结束（可结算）
                               a.put("status","2");
                               keJieSuan=keJieSuan.add(a.get("commiss")==null?new BigDecimal(0):new BigDecimal(a.get("commiss").toString()));
                           }
                       }
                   }

               }
               CommissionVO commissionVO=CommissionVO.getNew();
               commissionVO.setList(userPerformanceList);
               //待入账
               commissionVO.setDaiRuZhang(daiRuZhang);
               commissionVO.setKeJieSuan(keJieSuan);
               commissionVO.setZongYingShou((BigDecimal) redisDataSourceUtil.getRedisSweetUtil().get(SmileRedisConst.SELL_USER_REVENUE.concat(smileUser.getUid())));
               redisDataSourceUtil.getRedisSweetUtil().set(SmileRedisConst.SELL_DATA_COMMISSION.concat(smileUser.getUid()),commissionVO);
           }
       }
   }

}
