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.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IForwardOrderService;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.enumtype.SysEnums;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.presale.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class ForwardOrderServiceImpl implements IForwardOrderService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ICptradePositionapplyMapper iCptradePositionapplyMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private IGoodsMapper iGoodsMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IDeliveryrelationMapper iDeliveryrelationMapper;
    @Resource
    private IWrstandardMapper iWrstandardMapper;
    @Resource
    private IMarketrunMapper iMarketrunMapper;
    @Resource
    private ICptradePositioncancelMapper iCptradePositioncancelMapper;

    @Override
    public PageResult<ForwardOrderApplyResult> queryForward(ForwardOrderApplyParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setUserid(systemmanager.getAreauserid());
        }
        PageResult<ForwardOrderApplyResult> pageResult = new PageResult<>();
        IPage<ForwardOrderApplyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ForwardOrderApplyResult> resultIPage = iCptradePositionapplyMapper.queryForward(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<ForwardOrderApplyResult> forwardView(String applyid, HttpServletRequest request) {
        ForwardOrderApplyParam param = new ForwardOrderApplyParam();
        param.setApplyid(applyid);
        List<ForwardOrderApplyResult> results = iCptradePositionapplyMapper.queryForward(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results.get(0));
    }

    @Override
    public PageResult<ForwardOrderQueryResult> queryOrder(ForwardOrderQueryParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setUserid(systemmanager.getAreauserid());
        }
        PageResult<ForwardOrderQueryResult> pageResult = new PageResult<>();
        IPage<ForwardOrderQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ForwardOrderQueryResult> resultIPage = iCptradePositionapplyMapper.queryOrder(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 PageResult<ForwardCancelApplyResult> queryCancelApply(ForwardCancelApplyParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype().intValue() != SysConstants.SYS_TYPE_MANAGE) {
            param.setUserid(systemmanager.getAreauserid());
        }
        PageResult<ForwardCancelApplyResult> pageResult = new PageResult<>();
        IPage<ForwardCancelApplyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<ForwardCancelApplyResult> resultIPage = iCptradePositionapplyMapper.queryCancelApply(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<ForwardCancelApplyResult> cancelApplyView(Long cancelid, HttpServletRequest request) {
        ForwardCancelApplyParam param = new ForwardCancelApplyParam();
        param.setCancelid(cancelid);
        List<ForwardCancelApplyResult> results = iCptradePositionapplyMapper.queryCancelApply(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results.get(0));
    }

    @Override
    public AjaxResult<ForwardAddMarketAndGoods> forwardAddInit(Long marketid,Long goodid, HttpServletRequest request) {
        ForwardAddMarketAndGoods result = new ForwardAddMarketAndGoods();
        List<Market> marketList = iMarketMapper.selectList(new QueryWrapper<Market>()
                .eq("tradeProperty", 2)
                .in("tradeMode", 10, 13, 16, 70, 49));
        result.setMarketList(marketList);
        if (marketid != null) {
            List<Goods> goods = iGoodsMapper.selectList(new QueryWrapper<Goods>().eq("goodsstatus", 3)
                    .eq("marketid", marketid));
            Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", marketid));
            List<Goods> goodsList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(goods)) {
                goods.forEach(p -> {
                    if (market != null) {
                        if (market.getTrademode().equals(SysEnums.TradeMode.DJZR.getCode())) {
                            //定金转让市场49 只取未预售的商品
                            if (p.getPresaleflag() != null && p.getPresaleflag().equals(1)) {
                                goodsList.add(p);
                            }
                        } else {
                            //其它市场无此限制
                            goodsList.add(p);
                        }
                    }
                });
            }
            result.setGoods(goodsList);

            if(CollectionUtils.isNotEmpty(goodsList)){
                goodsList.forEach(p -> {
                    p.setProviderusername(iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid",p.getProvideruserid())).getAccountname());
                });
            }
        }

        if(goodid != null){
            ForwardAddOtherInit otherInit = iCptradePositionapplyMapper.queryDRelation(goodid);
            Deliveryrelation dr = iDeliveryrelationMapper.selectOne(new QueryWrapper<Deliveryrelation>().eq("goodsid",goodid));
            Wrstandard  wr = iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("wrstandardid",dr.getWrstandardid()));
            otherInit.setWrstandardid(wr.getWrstandardid());
            otherInit.setWrstandardcode(wr.getWrstandardcode());
            otherInit.setWrstandardname(wr.getWrstandardname());
            result.setOtherInit(otherInit);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult forwardAdd(ForwardAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Market market = iMarketMapper.selectOne(new QueryWrapper<Market>().eq("marketid", param.getMarketid()));
        Goods good = iGoodsMapper.selectOne(new QueryWrapper<Goods>().eq("goodsid", param.getGoodsid()));
        //定金转让市场(49)只允许添加商品发行方的远期订单
        if (market.getTrademode().equals(SysEnums.TradeMode.DJZR.getCode())) {
            if (!Objects.equals(param.getUserid(), good.getProvideruserid())) {
                Object[] objects = {good.getProvideruserid()};
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.INVESTOR_ERROR_CODE_008.getCode(), objects, request.getHeader("Accept-Language"));
            }
        }

        Long applyid = SerialNumberUtils.getSerialNumber(SerialNumberUtils.prefix_capacity);

        Marketrun mr = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid",0L));

        CptradePositionapply pa = new CptradePositionapply();
        BeanUtils.copyProperties(param, pa);
        pa.setApplyid(applyid);
        pa.setApplystatus(1);
        pa.setApplytime(new Date());
        pa.setCreatorid(systemmanager.getAutoid());
        pa.setCreatetime(new Date());
        if (mr != null) {
            pa.setTradedate(mr.getTradedate());
        }
        iCptradePositionapplyMapper.insert(pa);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<ForwardCancelApplyInit> cancelApplyAddInit(Long accountid, HttpServletRequest request) {
        List<ForwardCancelApplyInit> init = iCptradePositionapplyMapper.cancelApplyAddInit(accountid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"),init);
    }

    @Override
    public AjaxResult cancelApplyAdd(ForwardCancelAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Marketrun mr = iMarketrunMapper.selectOne(new QueryWrapper<Marketrun>().eq("marketid",0L));
        CptradePositioncancel pa = new CptradePositioncancel();
        BeanUtils.copyProperties(param, pa);
        pa.setApplystatus(1);
        pa.setApplytime(new Date());
        pa.setCreatorid(systemmanager.getAutoid());
        pa.setCreatetime(new Date());
        if(mr != null){
            pa.setTradedate(mr.getTradedate());
        }
        iCptradePositioncancelMapper.insert(pa);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }
}
