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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp.proto.Common;
import com.muchinfo.mtp.proto.WarehouseReceiptMI1;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IWarehouseService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
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.DateTimeUtils;
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.mtp3common.utils.SerialNumberUtils;
import com.muchinfo.mtp3pojos.vo.LineTreeNode;
import com.muchinfo.mtp3pojos.vo.ProtoErrorCodes;
import com.muchinfo.mtp3pojos.vo.common.OrganSelectResult;
import com.muchinfo.mtp3pojos.vo.warehouse.*;
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.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

@Service
public class WarehouseServiceImpl implements IWarehouseService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private IWroutinapplyMapper iWroutinapplyMapper;
    @Resource
    private IWrstandardMapper iWrstandardMapper;
    @Resource
    private IWroutinexpressMapper iWroutinexpressMapper;
    @Resource
    private IWroutindetailMapper iWroutindetailMapper;
    @Resource
    private IDgfactoryitemtypeMapper iDgfactoryitemtypeMapper;
    @Resource
    private IWroutinfactorydetailMapper iWroutinfactorydetailMapper;
    @Resource
    private IDgfactoryitemMapper iDgfactoryitemMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IDeliverygoodsMapper iDeliverygoodsMapper;
    @Resource
    private IWarehouseinfoMapper iWarehouseinfoMapper;
    @Resource
    private IDivisionMapper iDivisionMapper;
    @Resource
    private IWrstandardfactoryitemMapper iWrstandardfactoryitemMapper;
    @Resource
    private IWrholdlbMapper iWrholdlbMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;
    @Resource
    private IThjSpotgoodsdepositMapper iThjSpotgoodsdepositMapper;

    @Override
    public PageResult<WarehouseQueryResult> query(WarehouseQueryParam 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());
        }
        if ((param.getApplytype() == 3 || param.getApplytype() == 4) && param.getFlag() != 0) {
            param.setApplystatus(param.getFlag());
        }
        IPage<WarehouseQueryResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseQueryResult> userAccountVos = iWroutinapplyMapper.queryWROutInApplyPage(page, param);
        PageResult<WarehouseQueryResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<WarehouseDetailResult> queryDetail(String applyid, HttpServletRequest request) {
        WarehouseDetailResult result = new WarehouseDetailResult();
        WarehouseQueryParam param = new WarehouseQueryParam();
        param.setApplyid(applyid);
        List<WarehouseQueryResult> userAccountVos = iWroutinapplyMapper.queryWROutInApplyPage(param);
        BeanUtils.copyProperties(userAccountVos.get(0), result);

        result.setWrstandard(iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("WRSTANDARDID", result.getWrstandardid())));
        Wroutinexpress wrOutInExpress = iWroutinexpressMapper.selectOne(new QueryWrapper<Wroutinexpress>().eq("WRSTANDARDID", result.getWrstandardid()));
        Wroutindetail wrOutInDetail = iWroutindetailMapper.selectOne(new QueryWrapper<Wroutindetail>().eq("WRSTANDARDID", result.getWrstandardid()));
        HashMap<Long, String> map = new HashMap<>();

        List<Dgfactoryitemtype> dgFactoryItemTypes = iDgfactoryitemtypeMapper.selectList(new QueryWrapper<Dgfactoryitemtype>().eq("deliverygoodsid", result.getDeliverygoodsid()));
        if (CollectionUtils.isNotEmpty(dgFactoryItemTypes)) {
            for (Dgfactoryitemtype dGFactoryItemType : dgFactoryItemTypes) {
                map.put(dGFactoryItemType.getDgfactoryitemtypeid(), dGFactoryItemType.getItemtypename());
            }
        }

        List<Wroutinfactorydetail> wrOutInFactoryDetails = iWroutinfactorydetailMapper.selectList(new QueryWrapper<Wroutinfactorydetail>().eq("applyid", param.getApplyid()));
        if (CollectionUtils.isNotEmpty(wrOutInFactoryDetails)) {
            for (Wroutinfactorydetail wROutInFactoryDetail : wrOutInFactoryDetails) {
                if (wROutInFactoryDetail.getItemtypemode() == 1 && StringUtils.isNotBlank(wROutInFactoryDetail.getTypevalue())) {
                    Dgfactoryitem dgfi = iDgfactoryitemMapper.selectOne(new QueryWrapper<Dgfactoryitem>()
                            .eq("dgfactoryitemtypeid", wROutInFactoryDetail.getTypeid())
                            .eq("dgfactoryitemid", Long.valueOf(wROutInFactoryDetail.getTypevalue())));
                    if (dgfi != null) {
                        wROutInFactoryDetail.setTypevaluename(dgfi.getDgfactoryitemvalue());
                    }
                    if (wROutInFactoryDetail.getTypevalue2() != null) {
                        if (!wROutInFactoryDetail.getTypevalue().equals(wROutInFactoryDetail.getTypevalue2())) {
                            wROutInFactoryDetail.setIssame(0);
                        }
                        Dgfactoryitem dgfi2 = iDgfactoryitemMapper.selectOne(new QueryWrapper<Dgfactoryitem>()
                                .eq("dgfactoryitemtypeid", wROutInFactoryDetail.getTypeid())
                                .eq("dgfactoryitemid", Long.valueOf(wROutInFactoryDetail.getTypevalue2())));
                        if (dgfi2 != null) {
                            wROutInFactoryDetail.setTypevaluename2(dgfi2.getDgfactoryitemvalue());
                        }
                    }
                } else {
                    Dgfactoryitemtype dgfit = iDgfactoryitemtypeMapper.selectOne(new QueryWrapper<Dgfactoryitemtype>().eq("dgfactoryitemtypeid", wROutInFactoryDetail.getTypeid()));
                    Enumdicitem enumDicItem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                            .eq("enumitemname", dgfit.getUnitid())
                            .eq("enumdiccode", "goodsunit"));
                    if (enumDicItem != null) {
                        wROutInFactoryDetail.setUnitname(enumDicItem.getEnumdicname());
                    }
                    if (wROutInFactoryDetail.getTypevalue2() != null) {
                        if (!wROutInFactoryDetail.getTypevalue().equals(wROutInFactoryDetail.getTypevalue2())) {
                            wROutInFactoryDetail.setIssame(0);
                        }
                    }
                }

                wROutInFactoryDetail.setTypename(map.get(wROutInFactoryDetail.getTypeid()));
            }
        }
        result.setWrOutInDetail(wrOutInDetail);
        result.setWroutinexpress(wrOutInExpress);
        result.setWrOutInFactoryDetails(wrOutInFactoryDetails);
        HashMap<Long, String> map2 = new HashMap<>();
        List<Systemmanager> systemManagers = iSystemmanagerMapper.selectList(new QueryWrapper<Systemmanager>().eq("managertype", 1));
        if (CollectionUtils.isNotEmpty(systemManagers)) {
            for (Systemmanager systemManager : systemManagers) {
                map2.put(systemManager.getAutoid(), systemManager.getUsername());
            }
        }
        result.setCreatorname(map2.get(result.getCreatorid()));
        result.setFirstauditname(map2.get(result.getFirstauditid()));
        result.setSecondauditname(map2.get(result.getSecondauditid()));
        result.setFirstauditname2(map2.get(result.getFirstauditid2()));
        result.setSecondauditname2(map2.get(result.getSecondauditid2()));

        Deliverygoods deliveryGoods = iDeliverygoodsMapper.selectOne(new QueryWrapper<Deliverygoods>().eq("deliverygoodsid", result.getDeliverygoodsid()));
        result.setDeliverygoodsname(deliveryGoods.getDeliverygoodsname());

        Warehouseinfo byProerties = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("autoid", result.getWarehouseid()));
        if (byProerties != null) {
            result.setWarehousename(byProerties.getWarehousename());
        }
        if (result.getApplytype() == 2 || result.getApplytype() == 4) {
            List<Division> divisions = iDivisionMapper.selectList(new QueryWrapper<>());
            HashMap<Long, String> map3 = new HashMap<>();
            if (CollectionUtils.isNotEmpty(divisions)) {
                for (Division divisiono : divisions) {
                    map3.put(divisiono.getAutoid(), divisiono.getDivisionname());
                }
            }
            String address = null;
            if (result.getProvinceid() != null && result.getProvinceid() != 0 &&
                    result.getCityid() != null && result.getCityid() != 0 &&
                    result.getDistrictid() != null && result.getDistrictid() != 0) {
                address = map3.get(result.getProvinceid()) + map3.get(result.getCityid()) +
                        map3.get(result.getDistrictid()) + result.getAddress();
            } else if (byProerties != null) {
                address = byProerties.getCountrystr() + (StringUtils.isNotEmpty(byProerties.getCitystr()) ? byProerties.getCitystr() : "")
                        + (StringUtils.isNotEmpty(result.getAddress()) ? result.getAddress() : byProerties.getAddress());
            }
            result.setAddressinfo(address);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult<LineTreeNode> warehouseTree(Long categoryid, HttpServletRequest request) {
        List<LineTreeNode> allNode = new ArrayList<>();
        String p = iCommonService.getSystemParam(Constants.REDIS_HEADER_SYSPARAM, SysConstants.SYSPAMA_CODE_WRCATEGORY_LEVEL);
        if (categoryid == null) {
            categoryid = 0L;
        }
        if ("0".equals(p)) {
            List<Deliverygoods> dgList = iDeliverygoodsMapper.selectList(new QueryWrapper<Deliverygoods>().eq("isvalid", 1));
            for (Deliverygoods d : dgList) {
                LineTreeNode node = new LineTreeNode();
                node.setId(d.getDeliverygoodsid().toString());
                node.setPid(d.getCategoryid() == null ? null : d.getCategoryid().toString());
                node.setName(d.getDeliverygoodsname());
                node.setNodeType("1");
                node.setObjs(d);
                allNode.add(node);
            }
        } else {
            //查询分类
            List<Wrcategory> categoryList = iWroutinapplyMapper.loadWRCategoryGoodsTree(categoryid);
            //查询品种
            List<Deliverygoods> dgList = iDeliverygoodsMapper.selectList(new QueryWrapper<Deliverygoods>().eq("isvalid", 1));
            for (Wrcategory ca : categoryList) {
                LineTreeNode node = new LineTreeNode();
                node.setId(ca.getCategoryid().toString());
                node.setPid(ca.getParentcategoryid() == null ? "0" : ca.getParentcategoryid().toString());
                node.setName(ca.getCategoryname());
                node.setNodeType("1");
                node.setObjs(ca);
                allNode.add(node);
                //获取品种
                List<LineTreeNode> gpchildren = getChildren(dgList, ca.getCategoryid());
                if (CollectionUtils.isNotEmpty(gpchildren)) {
                    //添加品种
                    allNode.addAll(gpchildren);
                }
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), allNode);
    }

    @Override
    public AjaxResult<Dgfactoryitemtype> querydgfactory(Long wrstandardid, HttpServletRequest request) {
        Wrstandard ws = iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("wrstandardid", wrstandardid));
        // 品种要素项表
        List<Dgfactoryitemtype> dgfitlist = iDgfactoryitemtypeMapper.selectList(new QueryWrapper<Dgfactoryitemtype>().eq("deliverygoodsid", ws.getDeliverygoodsid()));
        for (int i = 0; i < dgfitlist.size(); i++) {
            Dgfactoryitemtype dgfit = dgfitlist.get(i);
            if (dgfit.getItemtypemode() == 2) {
                double num = Math.pow(10, dgfit.getMinivaluedp());
                dgfit.setMinivalue2(BigDecimal.valueOf(dgfit.getMinivalue().doubleValue()).divide(new BigDecimal(num)).setScale(2, RoundingMode.HALF_UP));

                Enumdicitem enumDicItem = iEnumdicitemMapper.selectOne(new QueryWrapper<Enumdicitem>()
                        .eq("enumitemname", dgfit.getUnitid())
                        .eq("enumdiccode", "goodsunit"));
                dgfit.setUnitname(enumDicItem.getEnumdicname());
            }
            Long deliverygoodsid;
            if (dgfit.getItemtypemode() == 3) {
                deliverygoodsid = 0L;
            } else {
                deliverygoodsid = ws.getDeliverygoodsid();
            }
            // 品种选择项定义
            List<Dgfactoryitem> dgfilist = iDgfactoryitemMapper.selectList(new QueryWrapper<Dgfactoryitem>()
                    .eq("deliverygoodsid", deliverygoodsid)
                    .eq("dgfactoryitemtypeid", dgfit.getDgfactoryitemtypeid()));
            for (int j = 0; j < dgfilist.size(); j++) {
                Dgfactoryitem dgfi = dgfilist.get(j);
                Wrstandardfactoryitem wrsfi = iWrstandardfactoryitemMapper.selectOne(new QueryWrapper<Wrstandardfactoryitem>()
                        .eq("wrstandardid", wrstandardid)
                        .eq("dgfactoryitemtypeid", dgfit.getDgfactoryitemtypeid())
                        .eq("dgfactoryitemid", dgfi.getDgfactoryitemid()));
                if (wrsfi == null) {
                    dgfi.setIschecked(0);
                } else {
                    dgfi.setIschecked(1);
                    if (dgfit.getItemtypemode() == 3) {
                        dgfit.setTypevalue(dgfi.getDgfactoryitemvalue());
                    }
                }

            }

            dgfit.setDgfilist(dgfilist);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), dgfitlist);
    }

    @Override
    public AjaxResult wrInApply(WarehouseInAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        String sm = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_CANGDANWRIN);
        Wroutinapply wroutinapply = new Wroutinapply();
        wroutinapply.setWrstandardid(param.getWrstandardid());
        wroutinapply.setWarehouseid(param.getWarehouseid());
        wroutinapply.setWrstandardcode(param.getWrstandardcode());
        wroutinapply.setDeliverygoodsid(param.getDeliverygoodsid());
        wroutinapply.setUserid(param.getUserid());
        wroutinapply.setAccountid(param.getAccountid());
        wroutinapply.setMobile(param.getMobile());
        wroutinapply.setInqty(param.getInqty());
        wroutinapply.setAppointmentremark(param.getAppointmentremark());
        wroutinapply.setAppointmentmodel(param.getAppointmentmodel());
        if ("5".equals(sm)) {
            wroutinapply.setApplytype(3);
            wroutinapply.setApplystatus(5);
            wroutinapply.setApplystatus2(2);
            wroutinapply.setInrealqty(param.getInqty());
            wroutinapply.setFirstauditid(systemmanager.getAutoid());
            wroutinapply.setFirstaudittime(new Date());
            wroutinapply.setSecondauditid(systemmanager.getAutoid());
            wroutinapply.setSecondaudittime(new Date());
        } else {
            wroutinapply.setApplystatus(1);
            wroutinapply.setApplytype(1);
        }
        wroutinapply.setCreatorid(systemmanager.getAutoid());
        wroutinapply.setCreatetime(new Date());
        wroutinapply.setApplytime(new Date());
        if (StringUtils.isNotBlank(param.getAppointmentdatestr())) {
            try {
                wroutinapply.setAppointmentdate(DateTimeUtils.parseDate(param.getAppointmentdatestr()));
            } catch (Exception e) {
                log.error("wrInApply 时间格式转换失败");
            }
        }
        Long applyid = SerialNumberUtils.getSerialNumber(SerialNumberUtils.prefix_wroutin);
        wroutinapply.setApplyid(applyid);
        iWroutinapplyMapper.insert(wroutinapply);
        List<Wroutinfactorydetail> wrOutInFactoryDetails = param.getWrOutInFactoryDetails();
        if (CollectionUtils.isNotEmpty(wrOutInFactoryDetails)) {
            for (Wroutinfactorydetail wROutInFactoryDetailo : wrOutInFactoryDetails) {
                wROutInFactoryDetailo.setApplyid(applyid);
                wROutInFactoryDetailo.setTypevalue2(wROutInFactoryDetailo.getTypevalue());
                iWroutinfactorydetailMapper.insert(wROutInFactoryDetailo);
            }
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult queryUserList(HttpServletRequest request) {
        List<OrganSelectResult> results = iWroutinapplyMapper.queryUserList();
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult querywslist(Long userid, HttpServletRequest request) {
        List<WslistQueryResult> results = iWroutinapplyMapper.querywslist(userid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult querywhlist(Long userid, Long wrstandardid, HttpServletRequest request) {
        List<WhlistQueryResult> results = iWroutinapplyMapper.querywhlist(userid, wrstandardid);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult<WrHoldLBResult> queryWRHoldLB(WrHoldLBParam param, HttpServletRequest request) {
        List<WrHoldLBResult> results = iWroutinapplyMapper.queryWRHoldLB(param);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult wrOutApply(WarehouseOutAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        String sm = iCommonService.getSysparmById(SysConstants.SYSPAMA_CODE_CANGDANWROUT);
        Wroutinapply vo = new Wroutinapply();
        if ("5".equals(sm)) {
            vo.setApplytype(4);
            vo.setApplystatus(5);
            vo.setApplystatus2(2);
            vo.setInrealqty(vo.getInqty());
            vo.setFirstauditid(systemmanager.getAutoid());
            vo.setFirstaudittime(new Date());
            vo.setSecondauditid(systemmanager.getAutoid());
            vo.setSecondaudittime(new Date());
        } else {
            vo.setApplystatus(1);
            vo.setApplytype(2);
        }

        vo.setCreatorid(systemmanager.getAutoid());
        vo.setCreatetime(new Date());
        vo.setApplytime(new Date());

        if (StringUtils.isNotBlank(param.getAppointmentdatestr())) {
            try {
                vo.setAppointmentdate(DateTimeUtils.parseDate(param.getAppointmentdatestr()));
            } catch (Exception e) {
                log.error("wrInApply 时间格式转换失败");
            }
        }

        Long applyid = SerialNumberUtils.getSerialNumber(SerialNumberUtils.prefix_wroutin);
        vo.setApplyid(applyid);
        Wrstandard wr = iWrstandardMapper.selectOne(new QueryWrapper<Wrstandard>().eq("wrstandardid", param.getWrstandardid()));
        vo.setWrstandardcode(wr.getWrstandardcode());
        vo.setDeliverygoodsid(wr.getDeliverygoodsid());
        Integer inqty = 0;
        List<WrHoldLBResult> wrHoldLBs = param.getResultList();
        if (CollectionUtils.isNotEmpty(wrHoldLBs)) {
            for (WrHoldLBResult wrHoldLBo : wrHoldLBs) {
                inqty += wrHoldLBo.getOutqty();
                Wroutindetail wd = new Wroutindetail();
                wd.setApplyid(applyid);
                wd.setLadingbillid(Long.valueOf(wrHoldLBo.getLadingbillid()));
                wd.setSubnum(wrHoldLBo.getSubnum());
                wd.setQty(Long.valueOf(wrHoldLBo.getQty()));
                wd.setOutqty(Long.valueOf(wrHoldLBo.getOutqty()));
                wd.setCreatorid(vo.getCreatorid());
                wd.setUpdatorid(vo.getCreatorid());
                if (wrHoldLBo.getWrfactortypeid() != null) {
                    wd.setWrfactortypeid(wrHoldLBo.getWrfactortypeid());
                } else {
                    Wrholdlb wrHoldLB = iWrholdlbMapper.selectOne(new QueryWrapper<Wrholdlb>()
                            .eq("ladingbillid", wrHoldLBo.getLadingbillid())
                            .eq("subnum", wrHoldLBo.getSubnum()));
                    wd.setWrfactortypeid(wrHoldLB.getWrfactortypeid());
                    wd.setQty(wrHoldLB.getQty());
                }
                //跳过初审阶段时，赋值实际出库量
                if ("5".equals(sm)) {
                    wd.setOutrealqty(Long.valueOf(wrHoldLBo.getOutqty()));
                    iWroutindetailMapper.insert(wd);
                } else {
                    iWroutindetailMapper.insert(wd);
                }
            }
        }
        vo.setInqty(Long.valueOf(inqty));
        if ("5".equals(sm)) {
            vo.setInrealqty(vo.getInqty());
        }

        iWroutinapplyMapper.insert(vo);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<WarehouseReceiptResult> receiptquery(WarehouseReceiptParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!SysConstants.SYS_TYPE_MANAGE.equals(systemmanager.getReletype())) {    //如果不是平台管理员
            param.setAreauserid(systemmanager.getAreauserid());
        }
        param.setWarehousecode(param.getWarehousecode() == null ? null : param.getWarehousecode().trim());
        param.setAreaname(param.getAreaname() == null ? null : param.getAreaname().trim());
        IPage<WarehouseReceiptResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseReceiptResult> userAccountVos = iWroutinapplyMapper.receiptquery(page, param);
        PageResult<WarehouseReceiptResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult dealreceipt(WarehouseReceiptAddParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getAutoid() != null) {
            Warehouseinfo wh = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("autoid", param.getAutoid()));
            String oldWarehousename = wh.getWarehousename();
            if (!param.getWarehousename().equals(wh.getWarehousename())) {
                Warehouseinfo current = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("warehousename", param.getWarehousename().trim()));
                if (Objects.isNull(current)) {
                    return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_03.getCode(), request.getHeader("Accept-Language"));
                }
            }
            wh.setAreauserid(param.getAreauserid());
            wh.setWarehousename(param.getWarehousename());
            wh.setWarehousetype(param.getWarehousetype());
            wh.setCountryid(param.getCountryid());
            wh.setProvinceid(param.getProvinceid());
            wh.setCityid(param.getCityid());
            wh.setDistrictid(param.getDistrictid());
            wh.setAddress(param.getAddress());
            // 审核拒绝的修改后状态变为待审核
            if (wh.getWarehousestatus() == 4 || wh.getWarehousestatus() == 2)
                wh.setWarehousestatus(3);
            wh.setHasvideo(param.getHasvideo());
            wh.setVideourl(param.getVideourl());
            wh.setContactname(param.getContactname());
            wh.setContactnum(param.getContactnum());
            iWarehouseinfoMapper.updateById(wh);
            if (!oldWarehousename.equals(param.getWarehousename())) {
                List<Dgfactoryitem> dGFactoryItemList = iDgfactoryitemMapper.selectList(new QueryWrapper<Dgfactoryitem>().eq("warehouseid", wh.getAutoid()));
                if (CollectionUtils.isNotEmpty(dGFactoryItemList)) {
                    for (Dgfactoryitem dgFactoryItem : dGFactoryItemList) {
                        dgFactoryItem.setDgfactoryitemvalue(wh.getWarehousename());
                        iDgfactoryitemMapper.updateById(dgFactoryItem);
                    }
                }
                sendWRFactorTypeNameUpdateReqMsg(wh, systemmanager);
            }
        } else {
            if (param.getWarehousecode().length() > 10) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_01.getCode(), request.getHeader("Accept-Language"));
            }
            Warehouseinfo wh = null;
            wh = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("warehousecode", param.getWarehousecode().trim()));
            if (Objects.nonNull(wh)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_02.getCode(), request.getHeader("Accept-Language"));
            }
            wh = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("warehousename", param.getWarehousename().trim()));
            if (Objects.nonNull(wh)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_03.getCode(), request.getHeader("Accept-Language"));
            }
            wh = new Warehouseinfo();
            wh.setWarehousecode(param.getWarehousecode().trim());
            wh.setWarehousename(param.getWarehousename().trim());
            wh.setWarehousetype(param.getWarehousetype());
            wh.setAreauserid(param.getAreauserid());
            // 仓库状态 - 1:正常 2:注销 3:待审核 4:审核拒绝
            wh.setWarehousestatus(3);
            wh.setCountryid(param.getCountryid());
            wh.setProvinceid(param.getProvinceid());
            wh.setCityid(param.getCityid());
            wh.setDistrictid(param.getDistrictid());
            wh.setAddress(param.getAddress());
            wh.setCreatetime(new Date());
            wh.setHasvideo(param.getHasvideo());
            wh.setVideourl(param.getVideourl());
            wh.setContactname(param.getContactname());
            wh.setContactnum(param.getContactnum());
            iWarehouseinfoMapper.insert(wh);

        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<WarehouseReceiptDetailResult> receiptDetail(Long warehouseid, Integer isaudit, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (!iCommonService.checkUserAccountRole(systemmanager, warehouseid)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.MESSAGE_ERROR_CODE_SYSTEM003.getCode(), request.getHeader("Accept-Language"));
        }

        Warehouseinfo current = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("autoid", warehouseid));
        WarehouseReceiptDetailResult result = new WarehouseReceiptDetailResult();
        BeanUtils.copyProperties(current, result);
        if (current.getAreauserid() != null) {
            Useraccount ognz = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", current.getAreauserid()));
            if (ognz == null) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_04.getCode(), request.getHeader("Accept-Language"));
            }
            result.setAreaname(ognz.getAccountname());
        }
        if (current.getDistrictid() != null) {
            Division area = iDivisionMapper.selectOne(new QueryWrapper<Division>().eq("autoid", current.getDistrictid()));
            result.setDetailaddress(area.getPathname() + " " + current.getAddress());
        } else {
            result.setDetailaddress(current.getAddress());
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), result);
    }

    @Override
    public AjaxResult receiptaudit(WarehouseReceiptAuditParam param, HttpServletRequest request) {
        Warehouseinfo warehouseInfo = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("autoid", param.getAutoid()));
        warehouseInfo.setWarehousestatus(param.getAuditflag());
        if (param.getMsg() != null) {
            warehouseInfo.setRemark(param.getMsg());
        }
        iWarehouseinfoMapper.updateById(warehouseInfo);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult receiptlogff(Long autoid, HttpServletRequest request) {
        if (iDeliverygoodsMapper.selectCount(new QueryWrapper<Deliverygoods>().eq("categoryid", autoid)) > 0) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.WAREHOUSE_ERROR_CODE_05.getCode(), request.getHeader("Accept-Language"));
        }
        Warehouseinfo warehoueInfo = iWarehouseinfoMapper.selectOne(new QueryWrapper<Warehouseinfo>().eq("autoid", autoid));
        warehoueInfo.setWarehousestatus(2);
        iWarehouseinfoMapper.updateById(warehoueInfo);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<WarehouseVarietyResult> varietquery(WarehouseVarietyParam param, HttpServletRequest request) {
        param.setIsvalid(1);
        IPage<WarehouseVarietyResult> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<WarehouseVarietyResult> userAccountVos = iWroutinapplyMapper.queryWRStandardSet(page, param);
        PageResult<WarehouseVarietyResult> pageResult = new PageResult<>();
        pageResult.setCode(Constants.Success_Code_Design);
        pageResult.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        pageResult.setPages(userAccountVos.getPages());
        pageResult.setCurrent(userAccountVos.getCurrent());
        pageResult.setTotal(userAccountVos.getTotal());
        pageResult.setPageSize(userAccountVos.getSize());
        pageResult.setData(userAccountVos.getRecords());
        return pageResult;
    }

    @Override
    public AjaxResult<WarehouseVarietyDetailResult> varietdetail(Long wrstandardid, HttpServletRequest request) {
        WarehouseVarietyDetailResult result = new WarehouseVarietyDetailResult();
        WarehouseVarietyParam param = new WarehouseVarietyParam();
        param.setWrstandardid(wrstandardid);
        List<WarehouseVarietyResult> resultList = iWroutinapplyMapper.queryWRStandardSet(param);
        BeanUtils.copyProperties(resultList.get(0), result);

        String sys = iCommonService.getSysparmById(Constants.SYSPARAM_ID_IMG);
        if (StringUtils.isNotBlank(sys)) {
            result.setIsimg(Integer.valueOf(sys));
        } else {
            result.setIsimg(0);
        }

        Object isShowEntry = redisServiceUtil.getCacheMapValue(Constants.REDIS_HEADER_SYSPARAM, "977");
        result.setIsShowEntry((Integer) isShowEntry);

        List<Dgfactoryitem> listDGFactoryItem = iWroutinapplyMapper.queryDGFactoryItemList(resultList.get(0).getWrstandardid(), resultList.get(0).getDeliverygoodsid());
        result.setDgFactoryItems(listDGFactoryItem);

        // 是否铁合金项目（现货商品用）
        String isShowTHJ = iCommonService.getSysparmById("994");
        if (isShowTHJ != null && isShowTHJ.equals("1")) {
            result.setIsShowTHJ(Integer.valueOf(isShowTHJ));
            //获取provideruserid机构名称
            if (resultList.get(0).getProvideruserid() != null) {
                List<Useraccount> userAccountList = iUseraccountMapper.queryUserAccount(resultList.get(0).getProvideruserid());
                if (CollectionUtils.isNotEmpty(userAccountList)) {
                    result.setProvidername(userAccountList.get(0).getAccountname());
                }
            }
            List<ThjSpotgoodsdeposit> thjspotgoodsdeposits = iThjSpotgoodsdepositMapper.selectList(new QueryWrapper<ThjSpotgoodsdeposit>().eq("wrstandardid", resultList.get(0).getWrstandardid()));
            result.setThjspotgoodsdeposits(thjspotgoodsdeposits);
        }

        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"),result);
    }

    private void sendWRFactorTypeNameUpdateReqMsg(Warehouseinfo wh, Systemmanager systemmanager) {
        WarehouseReceiptMI1.WRFactorTypeNameUpdateReq.Builder builder = WarehouseReceiptMI1.WRFactorTypeNameUpdateReq.newBuilder();
        WarehouseReceiptMI1.WRCommon.Builder common = WarehouseReceiptMI1.WRCommon.newBuilder();
        Long uuid = SerialNumberUtils.getNewSerialNumber(SerialNumberUtils.prefix_warehouse);
        if (wh.getAreauserid() != null) {
            common.setUserID(wh.getAreauserid());
        }
        common.setRelatedOrderID(uuid);
        common.setTradeID(wh.getAutoid());
        Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
        hd.setFunCode(FunCodeConstants.FunCode_Trade_WRFactorTypeNameUpdateReq);
        hd.setClientTime(System.currentTimeMillis());
        hd.setResponseTopic(SysConstants.RabbitWRRegisterRspKey);
        hd.setMarketID(Constants.SPEICAL_MARKET_WR);
        hd.setUUID(uuid.toString());
        hd.setUserID(systemmanager.getAutoid().intValue());
        builder.setHeader(hd);
        builder.setCommon(common);

        byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_WRFactorTypeNameUpdateReq);
        Calculator ca = SerialNumberUtils.createCalculator(uuid);
        rabbitTemplate.send(SysConstants.RabbitWRKey, new Message(body, new MessageProperties()));
        log.info("sendWRFactorTypeNameUpdateReqMsg:{}", builder.build());

        synchronized (ca) {
            try {
                ca.wait(10000);
                Object rsp_ = ca.obj;
                if (rsp_ != null) {
                    WarehouseReceiptMI1.WRFactorTypeNameUpdateRsp rsp = (WarehouseReceiptMI1.WRFactorTypeNameUpdateRsp) rsp_;
                    if (rsp.getRetCode() != 0) {
                        String errDesc = ProtoErrorCodes.resultMsg(rsp.getRetCode());
                        log.error("仓单品种修改更新历史数据失败，失败原因：" + errDesc);
                    }
                }
            } catch (InterruptedException e) {
                log.error("消息发送失败，失败原因：" + Arrays.toString(e.getStackTrace()));
            } finally {
                SerialNumberUtils.lockMap.remove(uuid);
            }
        }
    }

    private List<LineTreeNode> getChildren(List<Deliverygoods> dgList, Long categoryid) {
        List<LineTreeNode> tnlist = new ArrayList<>();
        for (Deliverygoods dg : dgList) {
            if (Objects.equals(dg.getCategoryid(), categoryid)) {
                LineTreeNode child = new LineTreeNode();
                child.setId(dg.getCategoryid() + "_" + dg.getDeliverygoodsid());
                child.setPid(String.valueOf(dg.getCategoryid()));
                child.setNodeType("2");
                child.setName(dg.getDeliverygoodsname());
                child.setObjs(dg);
                tnlist.add(child);
            }
        }
        return tnlist;
    }

}
