package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.TkernelMI1;
import com.muchinfo.mtp.proto.TkernelMI2;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IPresaleService;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.Calculator;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.presale.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class PresaleServiceImpl implements IPresaleService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ICptradePresalegoodsexMapper iCptradePresalegoodsexMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Resource
    private IWskhOpenaccountconfigMapper iWskhOpenaccountconfigMapper;

    @Override
    public PageResult<PresaleQueryResult> query(PresaleQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        PageResult<PresaleQueryResult> pageResult = new PageResult<>();
        IPage<PresaleQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<PresaleQueryResult> resultIPage = iCptradePresalegoodsexMapper.query(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<PresaleQueryDetailResult> view(String applyid, HttpServletRequest request) {
        PresaleQueryDetailResult result = iCptradePresalegoodsexMapper.view(applyid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<PresalePresaleLotteryResult> viewPresaleLottery(Long goodsid, HttpServletRequest request) {
        List<PresalePresaleLotteryResult> result = iCptradePresalegoodsexMapper.viewPresaleLottery(goodsid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<PresaleFinishResult> viewfinsh(Long goodsid, HttpServletRequest request) {
        List<PresaleFinishResult> result = iCptradePresalegoodsexMapper.viewfinsh(goodsid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult lottery(Long goodsid, Integer lotteryqty, HttpServletRequest request) {
        CptradePresalegoodsex paramObj = iCptradePresalegoodsexMapper.selectOne(new QueryWrapper<CptradePresalegoodsex>().eq("goodsid", goodsid));

        //调用51201 服务“预售摇号”接口
        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_capacitytwo);
        Calculator ca = new Calculator(uuid, FunCodeConstants.FunCode_Trade_OrderPresaleLotteryReq);
        SerialNumberUtils.lockMap.put(uuid, ca);

        TkernelMI1.OrderPresaleLotteryReq.Builder builder = TkernelMI1.OrderPresaleLotteryReq.newBuilder();

        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setUUID(String.valueOf(uuid));
        hd.setFunCode(FunCodeConstants.FunCode_Trade_OrderPresaleLotteryReq);
        hd.setMarketID(paramObj.getMarketid().intValue());
        hd.setAccountID(paramObj.getAccountid());
        hd.setUserID(paramObj.getUserid().intValue());
        builder.setHeader(hd);
        builder.setGoodsID(paramObj.getGoodsid().intValue());
        builder.setLotteryQty(lotteryqty);
        builder.setClientTicket(String.valueOf(uuid));

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_OrderPresaleLotteryReq);

        rabbitTemplate.send(SysConstants.TradeCpReq, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(ca.getOutTime());
                Object rsp = ca.obj;
                if (rsp != null) {
                    TkernelMI1.OrderPresaleLotteryRsp rsp_ = (TkernelMI1.OrderPresaleLotteryRsp) rsp;
                    if (rsp_.getRetCode() == 0) {
                        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM013.getCode(), request.getHeader("Accept-Language"));
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "");
                    }
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                log.error("预售摇号失败，失败信息：" + Arrays.toString(e.getStackTrace()));
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }

    @Override
    public AjaxResult<PresaleQueryResult> complatesView(Long goodsid, HttpServletRequest request) {
        PresaleQueryParam param = new PresaleQueryParam();
        param.setGoodsid(goodsid);
        List<PresaleQueryResult> resultIPage = iCptradePresalegoodsexMapper.query(param);

        Integer qty = 0;
        if (resultIPage.get(0).getLuckyqty() != null) {
            qty = resultIPage.get(0).getPresaleqty() - resultIPage.get(0).getLuckyqty();
        } else {
            qty = resultIPage.get(0).getPresaleqty();
        }
        resultIPage.get(0).setQty(qty);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultIPage.get(0));
    }

    @Override
    public AjaxResult<PresaleFinishInitAddResult> getAccountIds(Long goodsid, HttpServletRequest request) {
        PresaleInitResult result = new PresaleInitResult();
        PresaleQueryParam param = new PresaleQueryParam();
        param.setGoodsid(goodsid);
        List<PresaleQueryResult> resultIPage = iCptradePresalegoodsexMapper.query(param);

        List<PresaleFinishInitAddResult> listWRPresaleInfo = iCptradePresalegoodsexMapper.queryUserList(resultIPage.get(0).getUserid());
        result.setResults(listWRPresaleInfo);
        result.setPrice(resultIPage.get(0).getRefprice());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult saveComplates(PresaleComplatesParam param, HttpServletRequest request) {
        CptradePresalegoodsex paramObj = iCptradePresalegoodsexMapper.selectOne(new QueryWrapper<CptradePresalegoodsex>().eq("goodsid", param.getGoodsid()));

        //调用51201 服务“预售完成”接口
        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_capacitytwo);
        Calculator ca = new Calculator(uuid, FunCodeConstants.FunCode_Trade_OrderPresaleFinishReq);
        SerialNumberUtils.lockMap.put(uuid, ca);

        TkernelMI1.OrderPresaleFinishReq.Builder builder = TkernelMI1.OrderPresaleFinishReq.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setUUID(String.valueOf(uuid));
        hd.setFunCode(FunCodeConstants.FunCode_Trade_OrderPresaleFinishReq);
        hd.setMarketID(paramObj.getMarketid().intValue());
        hd.setAccountID(paramObj.getAccountid());
        hd.setUserID(paramObj.getUserid().intValue());
        builder.setHeader(hd);
        builder.setGoodsID(paramObj.getGoodsid().intValue());
        builder.setClientTicket(String.valueOf(uuid));

        if (CollectionUtils.isNotEmpty(param.getResults())) {
            for (PresaleFinishInitAddResult result : param.getResults()) {
                if (result.getUserid() != null && result.getAccountid() != null && result.getPlaceqty() != null) {
                    TkernelMI1.OrderPresalePlaceInfo.Builder child = TkernelMI1.OrderPresalePlaceInfo.newBuilder();
                    child.setAccountId(result.getAccountid());
                    child.setUserId(result.getUserid().intValue());
                    child.setPlaceQty(result.getPlaceqty());
                    builder.addPlaceInfos(child);
                }

            }
        }

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_OrderPresaleFinishReq);

        rabbitTemplate.send(SysConstants.TradeCpReq, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(ca.getOutTime());
                Object rsp = ca.obj;
                if (rsp != null) {
                    TkernelMI2.OrderPresaleFinishRsp rsp_ = (TkernelMI2.OrderPresaleFinishRsp) rsp;
                    if (rsp_.getRetCode() == 0) {
                        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM014.getCode(), request.getHeader("Accept-Language"));
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "");
                    }
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                log.error("预售完成失败，失败信息：" + Arrays.toString(e.getStackTrace()));
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }

    @Override
    public PageResult<PresaleApplyResult> queryApply(PresaleApplyParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setAreauserid(systemmanager.getAreauserid());
        }
        PageResult<PresaleApplyResult> pageResult = new PageResult<>();
        IPage<PresaleApplyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<PresaleApplyResult> resultIPage = iCptradePresalegoodsexMapper.queryApply(page, param);
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(resultIPage.getPages());
        pageResult.setCurrent(resultIPage.getCurrent());
        pageResult.setTotal(resultIPage.getTotal());
        pageResult.setPageSize(resultIPage.getSize());
        pageResult.setData(resultIPage.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<PresaleApplyResult> applyView(String applyid, HttpServletRequest request) {
        PresaleApplyParam param = new PresaleApplyParam();
        param.setApplyid(applyid);
        List<PresaleApplyResult> resultIPage = iCptradePresalegoodsexMapper.queryApply(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), resultIPage.get(0));
    }

    @Override
    public AjaxResult save(PresaleApplyAddParam param, HttpServletRequest request) {

        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_capacitytwo);
        Calculator ca = new Calculator(uuid, FunCodeConstants.FunCode_Trade_CpPresaleReq);
        SerialNumberUtils.lockMap.put(uuid, ca);

        TkernelMI1.CpPresaleReq.Builder builder = TkernelMI1.CpPresaleReq.newBuilder();
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_CpPresaleReq);
        hd.setUUID(String.valueOf(uuid));
        hd.setClientTime(System.currentTimeMillis());
        //header里使用二级商品的市场ID
        hd.setMarketID(param.getRelatedmarketid().intValue());
        builder.setHeader(hd);

        builder.setAccountID(param.getAccountid());
        builder.setUserID(param.getUserid().intValue());
        builder.setRelatedGoodsID(param.getRelatedgoodsid().intValue());
        builder.setStartTime(param.getStarttime());
        builder.setEndTime(param.getEndtime());
        builder.setPresaleMode(param.getPresalemode());
        builder.setPresaleQty(param.getPresaleqty());
        //一口价（全额）
        if (param.getPresalemode() == 1) {
            builder.setRefPrice(param.getRefprice().doubleValue());
        }
        //大宗竞拍（全额、定金）
        if (param.getPresalemode() == 2) {
            builder.setStartPrice(param.getStartprice().doubleValue());
            builder.setFloorPrice(param.getFloorprice().doubleValue());
            //goodsdetail字段作废
            builder.setGoodsDetail("");
            //缩略图
            builder.setAttachmentUrl(param.getAttachmenturl());
        }
        //71:预售挂牌-海商
        if (param.getPresalemode() == 3) {
            builder.setRefPrice(param.getRefprice().doubleValue());
        }
        //48 定金预售(大宗)
        if (param.getPresalemode() == 4) {
            builder.setStartPrice(param.getStartprice().doubleValue());
            builder.setFloorPrice(param.getFloorprice().doubleValue());
        }
        //51:定金预售(中签)
        if (param.getPresalemode() == 5) {
            builder.setRefPrice(param.getRefprice().doubleValue());
            builder.setBaseQty(param.getBaseqty());
            builder.setMaxBuyQty(param.getMaxbuyqty());
        }
        //48 定金预售(大宗) 51:定金预售(中签) 上传新字段AttachmentUrl、PictureUrls、BannerPicUrl、PresaleDepositAlgorithm、PresaleDepositValue
        if (param.getPresalemode() == 4 || param.getPresalemode() == 5) {
            //goodsdetail字段作废
            builder.setGoodsDetail("");
            //缩略图
            builder.setAttachmentUrl(param.getAttachmenturl());
            builder.setPictureUrls(param.getPictureurls());
            builder.setBannerPicUrl(param.getBannerpicurl());
            builder.setPresaleDepositAlgorithm(param.getPresaledepositalgorithm());
            if (param.getPresaledepositvalue() != null) {
                if (param.getPresaledepositalgorithm().equals(1)) {
                    builder.setPresaleDepositValue(param.getPresaledepositvalue().divide(new BigDecimal(100)).doubleValue());
                } else {
                    builder.setPresaleDepositValue(param.getPresaledepositvalue().doubleValue());
                }
            }
        }

        builder.setClientTicket(String.valueOf(uuid));
        //此处使用界面选择的市场ID
        builder.setMarketID(param.getMarketid().intValue());

        if (param.getApplyremark() != null) {
            builder.setApplyRemark(param.getApplyremark());
        }

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(),
                FunCodeConstants.FunCode_Trade_CpPresaleReq);

        rabbitTemplate.send(SysConstants.TradeCpReq, new Message(body, new MessageProperties()));

        synchronized (ca) {
            try {
                ca.wait(ca.getOutTime());
                Object rsp = ca.obj;
                if (rsp != null) {
                    TkernelMI1.CpPresaleRsp rsp_ = (TkernelMI1.CpPresaleRsp) rsp;
                    if (rsp_.getRetCode() == 0) {
                        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM015.getCode(), request.getHeader("Accept-Language"));
                    } else {
                        return AjaxResult.error(Constants.Error_Code_Design, ProtoErrorCodes.resultMsg(rsp_.getRetCode()), "");
                    }
                } else {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM006.getCode(), request.getHeader("Accept-Language"));
                }
            } catch (InterruptedException e) {
                log.error("预售申请失败，失败信息：" + Arrays.toString(e.getStackTrace()));
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
        return null;
    }

    @Override
    public AjaxResult<PresaleApplyAddInitResult> saveInit(HttpServletRequest request) {
        PresaleApplyAddInitResult result = new PresaleApplyAddInitResult();
        List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>()
                .eq("MARKETSTATUS",2)
                .in("TRADEMODE",40,41,71,48,51));
        result.setMarketList(marketList);
        Marketrun marketrun = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid", 0));
        if(Objects.nonNull(marketrun)){
            result.setNexttradedate(marketrun.getNexttradedate());
        }

        //获取图片上传大小
        WskhOpenaccountconfig config = iWskhOpenaccountconfigMapper.selectOne(new QueryWrapper<WskhOpenaccountconfig>().eq("configtype",25));
        if (config != null) {
            result.setMaxsize(config.getConfigvalue());
        } else {
            //默认文件最大10M
            result.setMaxsize(String.valueOf(10 * 1024 * 1024));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }
}
