package nccloud.pubimpl.ic.pub.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nc.bs.framework.common.NCLocator;
import nc.bs.ic.pub.util.ICBillVOQuery;
import nc.impl.pubapp.pattern.data.vo.VOQuery;
import nc.pubitf.uapbd.CurrencyRateUtilHelper;
import nc.vo.ic.general.define.ICBillBodyVO;
import nc.vo.ic.general.define.ICBillFlag;
import nc.vo.ic.general.define.ICBillHeadVO;
import nc.vo.ic.general.define.ICBillVO;
import nc.vo.ic.general.define.MetaNameConst;
import nc.vo.ic.general.util.ICLocationUtil;
import nc.vo.ic.m45.entity.PurchaseInVO;
import nc.vo.ic.org.OrgInfoQuery;
import nc.vo.ic.transtype.TransTypeExtendVO;
import nc.vo.pub.ISuperVO;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.scmpub.res.billtype.ICBillType;
import nc.vo.scmpub.util.BillBodySortUtils;
import nc.vo.ic.m45.utils.BillQuery;
import nccloud.dto.ic.pub.entity.BillVOWithExtendInfo;
import nccloud.dto.ic.pub.entity.ICBillstatusForWeb;
import nccloud.pubimpl.ic.pub.utils.ICBillExtendInfoHelper;
import nccloud.pubitf.ic.pub.service.IICBillVOQueryService;

/**
 * 库存单据查询实现类
 *
 * @author hujieh
 *
 */
public class ICBillVOQueryServiceImpl implements IICBillVOQueryService {

    @Override
    public ICBillVO[] query(ICBillType billtype, String[] hids) {
        ICBillVO[] vos = new ICBillVOQuery(billtype).query(hids);
        if(billtype.equals(ICBillType.PurchaseIn)){
            try {
                vos = new BillQuery<PurchaseInVO>(PurchaseInVO.class).queryGrandsons((PurchaseInVO[]) vos);
            } catch (Exception e) {
                ExceptionUtils.wrappException(e);
            }
        }
        return vos;
    }

    @SuppressWarnings("unchecked")
    @Override
    public ICBillHeadVO[] query(Class<?> T, String[] hids) {
        return (ICBillHeadVO[]) new VOQuery(T).query(hids);
    }

    @Override
    public BillVOWithExtendInfo queryBillExtByVO(ICBillVO vo) {
        BillVOWithExtendInfo info = new ICBillExtendInfoHelper()
                .getExtendInfoByBillVO(vo);
        return info;
    }

    @Override
    public BillVOWithExtendInfo queryBillExt(ICBillType billtype, String hid) {
        ICBillVO[] vos = new ICBillVOQuery(billtype).query(new String[] { hid });
        if(billtype.equals(ICBillType.PurchaseIn)){
            try {
                vos = new BillQuery<PurchaseInVO>(PurchaseInVO.class).queryGrandsons((PurchaseInVO[]) vos);
            } catch (Exception e) {
                ExceptionUtils.wrappException(e);
            }
        }
        if (billtype.equals(ICBillType.LocAdjust)) {
            vos = ICLocationUtil.loadLocationVOsFilterNeg(vos);
        } else {
            vos = ICLocationUtil.loadLocationVOs(vos);
        }
        if (vos != null && vos.length == 1) {
            BillBodySortUtils.sort(vos);
            // 本位币
            String cfinanceoid = new OrgInfoQuery().getFinanceOrgIDByCalBodyID(vos[0].getHead().getPk_org());
            String ccurrencyid = CurrencyRateUtilHelper.getInstance().getLocalCurrtypeByOrgID(cfinanceoid);
            Arrays.asList(vos[0].getBodys()).stream().forEach(body -> {body.setAttributeValue(MetaNameConst.CCURRENCYID, ccurrencyid);});
            BillVOWithExtendInfo info = new ICBillExtendInfoHelper()
                    .getExtendInfoByBillVO(vos[0]);
            return info;
        }

        return null;
    }

    @Override
    public BillVOWithExtendInfo[] queryBillDev(ICBillType billtype, String[] hids) {
        ICBillVO[] vos = new ICBillVOQuery(billtype).query(hids);
        if(billtype.equals(ICBillType.PurchaseIn)){
            try {
                vos = new BillQuery<PurchaseInVO>(PurchaseInVO.class).queryGrandsons((PurchaseInVO[]) vos);
            } catch (Exception e) {
                ExceptionUtils.wrappException(e);
            }
        }
        if (billtype.equals(ICBillType.LocAdjust)) {
            vos = ICLocationUtil.loadLocationVOsFilterNeg(vos);
        } else {
            vos = ICLocationUtil.loadLocationVOs(vos);
        }
        List<BillVOWithExtendInfo> resultList=new ArrayList<>();
        if (vos != null && vos.length >0) {
            BillBodySortUtils.sort(vos);

            for(ICBillVO vo:vos){
                // 本位币
                String cfinanceoid = new OrgInfoQuery().getFinanceOrgIDByCalBodyID(vo.getHead().getPk_org());
                String ccurrencyid = CurrencyRateUtilHelper.getInstance().getLocalCurrtypeByOrgID(cfinanceoid);
                Arrays.asList(vo.getBodys()).stream().forEach(body -> {body.setAttributeValue(MetaNameConst.CCURRENCYID, ccurrencyid);});
                BillVOWithExtendInfo info = new ICBillExtendInfoHelper()
                        .getExtendInfoByBillVO(vo);
                resultList.add(info);
            }
        }
        return resultList.toArray(new BillVOWithExtendInfo[resultList.size()]);
    }
    @Override
    public TransTypeExtendVO qryTransTypeExtendVOByPK(String pk) {
        TransTypeExtendVO[] retvo = (TransTypeExtendVO[]) new VOQuery(
                TransTypeExtendVO.class).queryWithWhereKeyWord(
                " where CTRANTYPEID= '" + pk + "'", "");
        return retvo[0];
    }

    @Override
    public ICBillHeadVO[] queryHeadWithInfo(ICBillType billtype,
                                            ISuperVO[] headvos) {
        ICBillVO[] billvos = queryBillByHead(billtype, headvos);
        if (billvos == null || billvos.length == 0) {
            return null;
        }
        return filterHeadVO(billvos);
    }

    private ICBillHeadVO[] filterHeadVO(ICBillVO[] billvos) {
        List<ICBillHeadVO> headvos = new ArrayList<ICBillHeadVO>();
        for (ICBillVO billvo : billvos) {
            ICBillHeadVO head = billvo.getHead();
            // 处理中和待签字的单据都是自由态
            if (head.getFbillflag() == ICBillFlag.getFreeFlag()) {
                boolean isProcessing = false;
                ICBillBodyVO[] bodys = billvo.getBodys();
                // 存在一行表体没有实收或实发的单据认为是处理中
                // 数量为0认为是有数量
                for (ICBillBodyVO body : bodys) {
                    if (null == body.getNnum()) {
                        isProcessing = true;
                        break;
                    }
                }
                // 不是处理中的单据认为是待签字
                if (!isProcessing) {
                    head.setAttributeValue(ICBillstatusForWeb.ICBILLSTATUS,
                            ICBillstatusForWeb.TOSIGN);
                } else {
                    head.setAttributeValue(ICBillstatusForWeb.ICBILLSTATUS,
                            ICBillstatusForWeb.TOPROCESS);
                }
            } else {
                head.setAttributeValue(ICBillstatusForWeb.ICBILLSTATUS,
                        ICBillstatusForWeb.SIGNED);
            }
            headvos.add(head);
        }
        return headvos.toArray(new ICBillHeadVO[0]);
    }

    private ICBillVO[] queryBillByHead(ICBillType billtype, ISuperVO[] headvos) {
        Set<String> ids = new HashSet<String>();
        for (ISuperVO headvo : headvos) {
            ids.add((String) headvo
                    .getAttributeValue(MetaNameConst.CGENERALHID));
        }
        ICBillVO[] billvos = NCLocator.getInstance()
                .lookup(IICBillVOQueryService.class)
                .query(billtype, ids.toArray(new String[0]));
        return billvos;
    }

    // @Override
    // public TransTypeExtendVO qryTransTypeExtendVOByPK(String pk) {
    // TransTypeExtendVO[] retvo = (TransTypeExtendVO[]) new VOQuery(
    // TransTypeExtendVO.class).queryWithWhereKeyWord(" where pk_group ="
    // + "'" + InvocationInfoProxy.getInstance().getGroupId() + "'"
    // + " and transtypecode  = " + "'" + pk + "'", null);
    // return retvo[0];
    // }
}
