<?php

/**
 * Created by PhpStorm.
 * User: william
 * Date: 2020/12/12
 * Time: 14:05
 * 目前海关暂时不允许从电商账册直接做5034退港出区,需要从电商张转到保税账里面才可以
 */
class Service_ShipBatch_ShipPreProcess{
    private $sbArr;
    private $sbRow; //只做一个，多个调用多次，出区单多个情况下合并件数和净重，毛重无法拆分
    private $products;
    private $orderList;
    private $exportList;
    private $tuigangHzList; //退港核注清单
    private $priDataList;//获取预录入数据
    private $splitNumber = 50;
    private $tuigang;
    private $error=[];
    private $waring=[];
    private $packweight;
    private $param;
    private $netweightTotal; //所有拆分的子单的净重之和
    private $netRows; //净重明细
    private $defaultValue;
    private $company;

    public $bg_pri_entry_data; //预录入数据表
    public $bg_pri_entry_data_detail; //预录入数据表表体(废弃用$bg_pri_entry_data_detail_body_head)
    public $bg_pri_entry_data_detail_body_head; //预录入数据表体对应的报关单/核注单头
    public $bg_pri_entry_data_detail_body_detail; //预录入数据表体对应的报关单/核注单表体
    public $bg_pri_entry_data_detail_body_detail_split; //待分拆的表体

    private $bilInfo = array(
        'ex_bill_no' => '',//转出的电商账册
        'im_bill_no' => '',//转入的保税账册
    );

    private $tax_method = '3';

    public function __construct($sbArr) {
        $this->setSb($sbArr);
    }
    public function getBgCompany($value){
        $c = Service_BgCompany::getByField($value,'company_code');
        $this->company = $c;
        $this->bilInfo['ex_bill_no'] = $c['bwl_no'];
    }
    /**
     * @todo 设置一些默认数字
     */
    public function setDefaultValue(){
        $defaultArr = array(
            'traf_name'=>'',
            'traf_mode'=>'Y'
        );
        if($this->param['type']!=''){
            $formType = \Service_FormType::getByField($this->param['type'],'form_type');
            if($formType['default_value']!=''){
                $rowdefault = json_decode($formType['default_value'],true);

                if(!empty($rowdefault)){
                    $defaultArr = array_merge($defaultArr,$rowdefault);
                }
            }
        }else{
            $this->error[] = "必须选择业务类型";
        }
        $this->defaultValue = $defaultArr;
    }
    /**
     * @todo 设置参数
     */
    public function setParam($param){
        $this->param = $param;
    }
    /**
     * @todo 获取件数和总量和净重
     */
    public function getPackWeight(){
        $pack = 0;
        $gross_weight_total = 0;
        if (!empty($this->sbArr)) {
            foreach ($this->sbArr as $k => $sbCode) {
                $gross_weight = Service_ShipBatchDetail::sumGrossWeight($sbCode);
                $gross_weight_total+=$gross_weight;
                $shipattr = Service_ShipBatchAttribute::getByField($sbCode,'sb_code');
                $pack+=$shipattr['pack_no'];
            }
        }
        $pw = array(
            'pack'=>$pack,
            'gross_weight'=>$gross_weight_total,
        );
        $this->packweight = $pw;
        return $pw;
    }
    public function setSb($sbArr) {
        foreach ($sbArr as $k=>$sbCode){
            $sbRow = Service_ShipBatch::getByField($sbCode,'sb_code');
            $sbAttRow = Service_ShipBatchAttribute::getByField($sbCode,'sb_code');
            $this->sbRow = array_merge($sbRow,$sbAttRow);
        }
        $this->sbArr = $sbArr;
    }
    public function setOrderList($orderList){
        $this->orderList = $orderList;
    }
    public function getOrderList(){
        return $this->orderList;
    }
    /**
     * @todo 区内调拨获取调拨账册信息
     */
    public function getBillInfo() {
        return $this->bilInfo;
    }
    /**
     * @todo 获取订单号
     */
    public function getSbOrders() {
        $orderList = array();
        if (!empty($this->sbArr)) {
            foreach ($this->sbArr as $k => $sbCode) {
                $shipbatch = Service_ShipBatch::getByField($sbCode, 'sb_code');
                if (!empty($shipbatch)) {
                    $sbCondition = array(
                        'sb_code' => $sbCode
                    );
                    $sbRows = Service_ShipBatchDetail::getByCondition($sbCondition, '*');
                    if (!empty($sbRows)) {
                        foreach ($sbRows as $ks => $row) {
                            $obCondition = array(
                                "ob_no" => $row['ob_no']
                            );
                            $outDetails = Service_OutboundBagDetail::getByCondition($obCondition, "*");
                            foreach ($outDetails as $ko => $odRow) {
                                $orderList[] = $odRow['order_code'];
                            }
                        }
                    }
                }
            }
        }
        $this->orderList = $orderList;
        return $orderList;
    }
    /**
     * Note:获取转入的数据
     * User: Yao
     * Date: 2020/12/18
     * Time: 14:12
     * @throws Exception
     */
    public function getExportImByOrderList(){
        try {
            $this->getProducts(); //获取商品统计
            $this->getProductsDel(); //将商品信息在物流账册有库存的情况下剥离出去
            $this->getExportImDetail(); //获取核注详情
        } catch (Exception $e) {
            throw $e;
        }
    }
    /**
     * Note:获取转出的数据
     * User: Yao
     * Date: 2020/12/18
     * Time: 14:12
     * @throws Exception
     */
    public function getExportExByOrderList(){
        try {
            $this->getProducts(); //获取商品统计
            $this->getProductsDel(); //将商品信息在物流账册有库存的情况下剥离出去
            $this->getExportExDetail(); //获取核注详情
        } catch (Exception $e) {
            throw $e;
        }
    }
    /**
     * @todo 获取转入数据
     */
    public function getExportIm() {
        try {
            $this->getSbOrders(); //获取出货单订单
            $this->getProducts(); //获取商品统计
            $this->getProductsDel(); //将商品信息在物流账册有库存的情况下剥离出去
            $this->getExportImDetail(); //获取核注详情
        } catch (Exception $e) {
           throw $e;
        }
    }

    /**
     * @todo 获取转出核注数据
     */
    public function getExportEx() {
        $result = array(
            'state'=>0,
            'message'=>'',
            'error'=>[],
            'data'=>[],
        );
        try {
            $this->setDefaultValue(); //设置一些必要的数据
            $this->getSbOrders(); //获取出货单订单
            //print_r($this->orderList);
            $this->getProducts(); //获取商品统计
            //print_r($this->products);
            $this->getbgpri_entry_data_detail_body_detail_split();
            //echo "split";
            //print_r($this->bg_pri_entry_data_detail_body_detail_split);
            //相同的备案序号合并申报
            $this->getbgpri_entry_data_detail_body_detail_split_merge();
            $this->getPackWeight();
            $this->getbg_pri_entry_data_detail_body_detail();
            //echo "body";
            //print_r($this->bg_pri_entry_data_detail_body_detail);

            //获取getbg_pri_entry_data_detail_body_head--预录入数据表体对应的报关单/核注单头
            $this->getbg_pri_entry_data_detail_body_head();

            //获取bg_pri_entry_data_detail---预录入数据核注单&报关单关联信息(废弃用获取getbg_pri_entry_data_detail_body_head)

            //bg_pri_entry_data--预录入数据
            $this->getbg_pri_entry_data();

            if(!empty($this->error)){
                $result['error'] = $this->error;
                $result['message'] = "获取数据有错误";
            }else{
                $result['state'] = 1;
                //返回数据
                $data = array(
                    'bg_pri_entry_data'=>$this->bg_pri_entry_data,
                    'bg_pri_entry_data_detail_body_head'=>$this->bg_pri_entry_data_detail_body_head,
                    'bg_pri_entry_data_detail_body_detail'=>$this->bg_pri_entry_data_detail_body_detail
                );
                $result['data'] = $data;
            }
        } catch (Exception $e) {
            $result['message'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * @todo 获取退港核注清单
     */
    public function getTuigangHz(){
        try{
            $this->getSbOrders(); //获取出货单订单
            $this->getProducts(); //获取商品统计
            $this->geTuigangDetail(); //获取核注详情(会拆分)
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }
    /**
     * @todo 获取导出的数据
     */
    public function getExportList() {
        return $this->exportList;
    }
    public function getDataBykey($key){
        return $this->$key;
    }
    /**
     * @todo 获取产品的账册信息(转出方账册信息)
     */
    public function getBillNO($product_id, $op_quantity) {
        //var_dump($product_id);
        //exit;
        $product = Service_Product::getByField($product_id);
        $billBookProudct = Service_BillBookProduct::getBillRecord($product_id);
        //var_dump($billBookProudct);
        $account_no = $this->bilInfo['ex_bill_no'];
        $recordeNo = '';
        $result = array(
            'state' => 0,
            'message' => '',
            'error' => array(),
            'data' => array(),
            'product' => [], //带出商品以便有错误时候能显示
        );

        if (empty($billBookProudct)) {
            $error[] = $product['product_sku'] . '转出方账册信息不存在'.$this->bilInfo['ex_bill_no'];
        }
        //查询法定数量
        $hum = Service_HsUomMap::getByField($product_id, 'product_id');
        if (empty($hum)) {
            $error[] = $product['product_sku'] . '法定数量信息不存在';
        }
        $declare_value = $product['product_declared_value'];
        $currency = Service_Currency::getByField($product['currency_code'], 'currency_code');
        if ($declare_value <= 0) {
            $error[] = '商品申报价值小于0';
        }
        if ($product['currency_code']) {
            $currency = Service_Currency::getByField($product['currency_code'], 'currency_code');
            if ($currency['currency_hs_code'] != '') {
                $product['currency_hs_code'] = $currency['currency_hs_code'];
            }
        }
        $result['product'] = $product;
        $data = []; //返回核扣的数据
        /*print_r($billBookProudct);
        exit;*/

        if ($billBookProudct) {
            $billBookId = array();
            foreach ($billBookProudct as $bill) {
                $billBookId[] = $bill['bill_book_id'];
            }
            //$gt = $op_quantity -1;
            $gt = 0.1; //大于0的账册从小到达排序,然后
            $billBooks = Service_BillBook::getByCondition(array(
                'id_array' => $billBookId,
                'warehous_account_no' => $account_no,
                'state'=>'0',
                'can_use_quantity_gt' => $gt
            ), '*', '0', '0', array('can_use_quantity asc '));
            if (empty($billBooks)) {
                $error[] = $product['product_sku'] . '账册信息不存在'.$account_no;
            }
            $hekouNumber = $op_quantity; //总剩余核扣账册库存，初始化等于数量
            //var_dump($billBooks);
            foreach ($billBooks as $kb => $rb) {
                //$info = array();
                $billBook = Service_BillBook::getByIdForUpdate($rb['id'], 'id', '*');
                //var_dump($billBook);exit;
                $info = $billBook;
                $info['product_id'] = $product_id; //初始化为传的参数，bill_book的product_id存在一品多个商品关联情况不准确
                $info['product_sku'] = $product['product_sku'];
                $info['tax_method'] = $this->tax_method;
                $info['hum'] = $hum;
                if($hekouNumber == 0){
                    break;
                }
                if ($billBook['can_use_quantity'] >= $hekouNumber) {
                    $info['qty'] = $hekouNumber;
                    $info['qty1'] = sprintf("%.5f",$hekouNumber * $hum['hum_quantity_law']);
                    $info['qty2'] = sprintf("%.5f",$hekouNumber * $hum['hum_quantity_second']);
                    $info['zc_declareprice'] = $billBook['decalar_price'];
                    $info['zc_decalar_currency'] = $billBook['decalar_currency'];
                    $hekouNumber = $hekouNumber - $info['qty'];
                    $data[] = $info;
                    break; //库存够了跳出循环
                } else {
                    // $op_quantity = $op_quantity - $billBook['can_use_quantity'];
                    $info['qty'] = $billBook['can_use_quantity']; //库存不够把这个备案序号的库存全出完
                    $info['tax_method'] = $this->tax_method;
                    $info['qty1'] = sprintf("%.5f",$info['qty'] * $hum['hum_quantity_law']);
                    $info['qty2'] = sprintf("%.5f",$info['qty'] * $hum['hum_quantity_second']);
                    $info['zc_declareprice'] = $billBook['decalar_price'];
                    $info['zc_decalar_currency'] = $billBook['decalar_currency'];
                    $hekouNumber = $hekouNumber - $info['qty'];
                    $data[] = $info;
                }
            }
            if ($hekouNumber != 0) {
                $error[] = $product['product_sku'] . "账册库存不够核扣";
            }
        }
        if (!empty($error)) {
            $result['message'] = "库存获取有问题";
            $result['error'] = $error;
        } else {
            $result['data'] = $data;
            $result['message'] = "获取数据成功";
            $result['state'] = 1;
        }
        /*echo "result";
        print_r($result);*/
        return $result;
    }

    /**
     * @todo 根据转出方信息获取转入方信息
     * @row 是转入方信息的数组
     */
    public function getImBillNO($row) {
        $result = array(
            'state' => 0,
            'message' => '',
            'error' => array(),
            'data' => array(),
            'product' => [],
        );
        if (isset($row['product'])) {
            $result['product'] = $row['product'];
        }
        //print_r($row);
        //($row);
        $error = []; //错误信息
        if ($row['state'] == 1) {
            $account_no = $this->bilInfo['im_bill_no'];
            //转出校验成功,开始做转入
            $product = $row['product'];
            /*print_r($product);
            exit;*/
            $product_id = $product['product_id'];

            if ($product_id > 0) {
                $billBookProudct = Service_BillBookProduct::getBillRecord($product_id);
                $bookFlag = false; //转入到转出的账册，转出账册是否有库存标志，如果有就转入到该账册里面，避免产生过多的备案序号
                if ($billBookProudct) {
                    $billBookId = array();
                    foreach ($billBookProudct as $bill) {
                        $billBookId[] = $bill['bill_book_id'];
                    }
                    $billBook = Service_BillBook::getByCondition(array(
                        'id_array' => $billBookId,
                        'warehous_account_no' => $account_no,
                        'state'=>'0',
                        //'can_use_quantity_gt'=>0
                    ), '*', '1', '1', array('stock_quantity desc')); //取最大库存
                    if (!empty($billBook)) {
                        $bookFlag = true; //存在转入放的账册库存
                    }
                }
                $dataIms = array(); //转入方数据
                //获取转入方的账册数据和校验
                if ($bookFlag) {
                    //转入方有账册
                    $billBook = $billBook[0];
                    $data = $row['data']; //转出方数据

                    foreach ($data as $kd => $vd) {
                        if ($vd['hs_code'] != $billBook['hs_code']) {
                            $error[] = "转出方商品:" . $vd['product_sku'] . "商品海关编码:" . $vd['hs_code'] . "和转入方海关编码" . $billBook['hs_code'] . "不一致";
                        }
                        if ($vd['country_code'] != $billBook['country_code']) {
                            $error[] = "转出方商品:" . $vd['product_sku'] . "商品海关编码:" . $vd['hs_code'] . "和转入方海关编码" . $billBook['hs_code'] . "不一致";
                        }
                        $dataIm = $billBook;
                        $dataIm['recorde_no_info'] = $billBook['recorde_no']; //转入方有账册都转入到这个账册序号下,变个键值,避免转出方的键值
                        $dataIm['qty'] = $vd['qty'];
                        $dataIm['qty1'] = sprintf("%.5f",$vd['qty'] * $vd['hum']['hum_quantity_law']);
                        $dataIm['qty2'] = sprintf("%.5f",$vd['qty'] * $vd['hum']['hum_quantity_second']);

                        $dataIm['zc_declareprice'] = $vd['zc_declareprice'];
                        $dataIm['zc_decalar_currency'] = $vd['zc_decalar_currency'];

                        $dataIms[] = $dataIm;
                    }
                } else {
                    //转入方没数据
                    $data = $row['data']; //转出方数据
                    foreach ($data as $kd => $vd) {
                        $dataIm = $vd;
                        $dataIm['recorde_no_info'] = ""; //转入方没有账册不填
                        $goods_code = $product['goods_id'];
                        $dataIm['goods_code'] = $goods_code; //没有账册,用商品的料号
                        $dataIm['qty'] = $vd['qty'];
                        $dataIm['qty1'] = sprintf("%.5f",$vd['qty'] * $vd['hum']['hum_quantity_law']);
                        $dataIm['qty2'] = sprintf("%.5f",$vd['qty'] * $vd['hum']['hum_quantity_second']);

                        $dataIm['zc_declareprice'] = $vd['zc_declareprice'];
                        $dataIm['zc_decalar_currency'] = $vd['zc_decalar_currency'];

                        $dataIms[] = $dataIm;
                        //var_dump($dataIms);
                        //exit;
                    }
                }
            } else {
                $error[] = "产品id错误" . $product_id;
            }
            if (!empty($error)) {
                $result['error'] = $error;
            } else {
                $result['state'] = 1; //没有问题
                $result['data'] = $dataIms;
            }
        } else {
            $result['message'] = "转入方数据有问题";
            $result['error'] = $row['error'];
        }
        /*echo "biiiii";
        print_r($result);*/
        //exit;
        return $result;
    }
    /**
     * @todo 获取退港账册信息
     */
    public function getTuigangNo($product_id,$op_quantity){
        $product = Service_Product::getByField($product_id);

        $billBookProudct = Service_BillBookProduct::getBillRecord($product_id);
        //$account_no = $this->bilInfo['ex_bill_no'];
        $account_no = $this->bilInfo['im_bill_no'];

        //var_dump($account_no);
        $recordeNo = '';
        $result = array(
            'state'=>0,
            'message'=>'',
            'error' =>array(),
            'data'=>array(),
            'product'=>[], //带出商品以便有错误时候能显示
        );
        if(empty($billBookProudct)){
            $error[] = $product['product_sku'].'转入方账册信息不存在';
        }
        //查询法定数量
        $hum = Service_HsUomMap::getByField($product_id,'product_id');
        if(empty($hum)){
            $error[] = $product['product_sku'].'法定数量信息不存在';
        }
        $declare_value = $product['product_declared_value'];
        $currency = Service_Currency::getByField($product['currency_code'],'currency_code');
        if($declare_value<=0){
            $error[] = '商品申报价值小于0';
        }
        if($product['currency_code']){
            $currency = Service_Currency::getByField($product['currency_code'],'currency_code');
            if($currency['currency_hs_code']!=''){
                $product['currency_hs_code'] = $currency['currency_hs_code'];
            }
        }
        $result['product'] = $product;
        $data=[]; //返回核扣的数据
        //print_r($billBookProudct);
        //exit;

        if ($billBookProudct) {
            $billBookId = array();
            foreach ($billBookProudct as $bill) {
                $billBookId[] = $bill['bill_book_id'];
            }
            //$gt = $op_quantity -1;
            $gt = $op_quantity; //大于0的账册从小到达排序,然后
            $billBooks = Service_BillBook::getByCondition(array(
                'id_array' => $billBookId,
                'warehous_account_no'=>$account_no,
                'can_use_quantity_gt'=>$gt
            ), '*', '1', '1', array('stock_quantity asc'));
            if (empty($billBooks)) {
                $error[] = $product['product_sku'].'账册信息不存在->'.$account_no;
            }else{
                $hekouNumber = $op_quantity; //总剩余核扣账册库存，初始化等于数量
                $rb = $billBooks[0];
                $billBook = Service_BillBook::getByIdForUpdate($rb['id'],'id','*');
                //var_dump($billBook);exit;
                $info = $billBook;
                $info['product_id'] = $product_id; //初始化为传的参数，bill_book的product_id存在一品多个商品关联情况不准确
                $info['product_sku'] = $product['product_sku'];
                $info['tax_method'] = $this->tax_method;
                $info['hum'] = $hum;
                if ($billBook['can_use_quantity'] >= $op_quantity) {
                    $info['qty'] = $op_quantity;
                    $hekouNumber = $hekouNumber - $info['qty'];
                    $info['qty1'] = $op_quantity*$hum['hum_quantity_law'];
                    $info['qty2'] = $op_quantity*$hum['hum_quantity_second'];
                    $data[] = $info;
                }else{
                    $error[] = $product['product_sku']."账册库存不够核扣";
                }
            }
        }else{
            $error[] = $product['product_sku'].'无匹配的账册信息';
        }
        if(!empty($error)){
            $result['message'] =  "库存获取有问题";
            $result['error'] = $error;
        }else{
            $result['data'] = $data;
            $result['message'] = "获取数据成功";
            $result['state'] = 1;
        }
        /*echo "result";
        print_r($result);*/
        return $result;
    }
    /**
     * @todo 获取商品信息
     */
    public function getProducts() {
        $codeList = $this->orderList;
        $codeList = array_unique($codeList); //去除重复项

        $condition = [
            'order_code_arr' => $codeList
        ];
        //print_r($condition);
        $orderTotal = [];
        $exportList = [];
        $gdsSeqNo = 1;
        $total = 0;
        $result = array(
            'state' => '0',
            'message' => '',
            'data' => [],
            'error' => [],
        );
        if (empty($codeList)) {
            $result['message'] = "订单为空";
            return $result;
        }
        $orders = Service_Orders::getByCondition($condition, "*");

        foreach ($orders as $k => $order) {
            //获取商品信息
            $conditionp = array(
                'order_code' => $order['order_code']
            );
            $orderProducts = Service_OrderProduct::getByCondition($conditionp, '*');
            foreach ($orderProducts as $kop => $oop) {
                //$exportList[$cdetail['item_record_no']] = $content;
                $content = array(
                    'product_id' => $oop['product_id'],
                    'qty' => $oop['op_quantity'],
                );
                if (!isset($exportList[$oop['product_id']])) {
                    $exportList[$oop['product_id']] = $content;
                } else {
                    $exportList[$oop['product_id']]['qty'] = $exportList[$oop['product_id']]['qty'] + $oop['op_quantity'];
                }
            }
        }
        ksort($exportList);
        $this->products = $exportList;
        //获取转出账册信息
    }


    /**
     * @todo 获取申报信息
     */
    protected function getExportImDetail() {
        $exportList = array();
        $gdsSeqNo = 1;
        if(empty($this->products)){
            $this->exportList = $exportList;
            return;
        }
        foreach ($this->products as $k => $product) {
            //print_r($product);
            //exit;
            $row = $this->getBillNO($product['product_id'], $product['qty']);
            $imRow = $this->getImBillNO($row);
            $product = array();
            if (isset($imRow['product'])) {
                $product = $imRow['product'];
            }
            $product_declare = $product['product_declared_value'];
            $currency_hs_code = $product['currency_hs_code'];
            //$currency_code =

            /*print_r($imRow);
            exit;*/
            if ($imRow['state'] == 1) {
                $cdetails = $imRow['data'];
                foreach ($cdetails as $kc => $cdetail) {
                    //print_r($cdetail);
                    $putrec_seqno = "";
                    if (isset($cdetail['recorde_no_info']) && $cdetail['recorde_no_info'] != '') {
                        $putrec_seqno = $cdetail['recorde_no_info'];
                    }
                    //$price = $product['']
                    $content = array(
                        'gds_seqno' => $gdsSeqNo,
                        'putrec_seqno' => $putrec_seqno,//备案序号
                        'gds_mtno' => $cdetail['goods_code'],//商品料号
                        'gdecd' => $cdetail['hs_code'],//商品编码(必填)
                        'gds_nm' => $cdetail['product_title'],
                        'gds_spcf_model_desc' => $cdetail['specification'],//规格型号
                        'dcl_unitcd' => $cdetail['decalare_unit'],//申报单位
                        'lawf_unitcd' => $cdetail['legal_unit'],//法定单位
                        'secd_lawf_unitcd' => $cdetail['second_legal_unit'],//法定第二单位
                        'natcd' => $cdetail['country_code'],//国别
                        'dcl_uprc_amt' => $cdetail['zc_declareprice'], //$product_declare,//申报单价，取底账单价(转入方单价和和币制取转出方的一致)
                        'dcl_total_amt' => $cdetail['zc_declareprice'] * $cdetail['qty'],//申报总价，取底账单价*数量
                        'dcl_currcd' => $cdetail['zc_decalar_currency'], //$currency_hs_code,取底账币种
                        'dcl_qty' => $cdetail['qty'],//申报数量
                        'lawf_qty' => $cdetail['qty1'],//法定数量
                        'secd_lawf_qty' => $cdetail['qty2'],//第二法定数量
                        'decalar_currency'=>$cdetail['zc_decalar_currency'],//申报币种（取转出方的数据）
                        'use_cd' => '',//用途
                        //重量比例因子
                        //第一比例因子
                        //第二比例因子
                        //毛重	净重
                        //用途
                        'lvyrlf_modecd' => '3',//征免方式
                        'ucns_verno' => '',//单耗版本号
                        'entry_gds_seqno' => $gdsSeqNo,//报关单商品序号
                        //申请表序号
                        'rmk' => '',//备注
                        'destination_natcd' => '142',//最终目的国
                        // 'net_wt' => $productInfo['product_weight'],
                    );
                    $exportList[] = array('data' => $content, 'state' => 1);
                    $gdsSeqNo++;
                }
            } else {
                $exportList[] = array('data' => [], 'state' => 0, 'error' => $imRow['error'], 'product' => $product);
            }

        }
        //print_r($this->exportList);
        $this->exportList = $exportList;
    }

    /**
     * @todo 获取转出申报信息
     */
    protected function getExportExDetail() {
        $exportList = array();
        $gdsSeqNo = 1;
        if(empty($this->products)){
            $this->exportList = $exportList;
            return;
        }
        foreach ($this->products as $k => $p) {
            //print_r($product);
            //exit;
            $imRow = $this->getBillNO($p['product_id'], $p['qty']); //获取转出数据
            /*print_r($imRow);
            exit;*/
            $product = array();
            if (isset($imRow['product'])) {
                $product = $imRow['product'];
            }
            $product_declare = $product['product_declared_value'];
            $currency_hs_code = $product['currency_hs_code'];
            //$currency_code =

           /* print_r($imRow);
            exit;*/
            if ($imRow['state'] == 1) {
                $cdetails = $imRow['data'];
                foreach ($cdetails as $kc => $cdetail) {
                    //print_r($cdetail);
                    $putrec_seqno = "";
                    if (isset($cdetail['recorde_no']) && $cdetail['recorde_no'] != '') {
                        $putrec_seqno = $cdetail['recorde_no'];
                    }
                    //$price = $product['']
                    $content = array(
                        'gds_seqno' => $gdsSeqNo,
                        'putrec_seqno' => $putrec_seqno,//备案序号
                        'gds_mtno' => $cdetail['goods_code'],//商品料号
                        'gdecd' => $cdetail['hs_code'],//商品编码(必填)
                        'gds_nm' => $cdetail['product_title'],
                        'gds_spcf_model_desc' => $cdetail['specification'],//规格型号
                        'dcl_unitcd' => $cdetail['decalare_unit'],//申报单位
                        'lawf_unitcd' => $cdetail['legal_unit'],//法定单位
                        'secd_lawf_unitcd' => $cdetail['second_legal_unit'],//法定第二单位
                        'natcd' => $cdetail['country_code'],//国别
                        'dcl_uprc_amt' =>$cdetail['decalar_price'], //$product_declare,//申报单价，取底账单价
                        'dcl_total_amt' => $cdetail['decalar_price'] * $cdetail['qty'],//申报总价,取底账单价*数量
                        'dcl_currcd' => $cdetail['decalar_currency'], //$currency_hs_code, 取底账币种
                        'dcl_qty' => $cdetail['qty'],//申报数量
                        'lawf_qty' => $cdetail['qty1'],//法定数量
                        'secd_lawf_qty' => $cdetail['qty2'],//第二法定数量
                        'use_cd' => '',//用途
                        //重量比例因子
                        //第一比例因子
                        //第二比例因子
                        //毛重	净重
                        //用途
                        'lvyrlf_modecd' => '3',//征免方式
                        'ucns_verno' => '',//单耗版本号
                        'entry_gds_seqno' => $gdsSeqNo,//报关单商品序号
                        //申请表序号
                        'rmk' => '',//备注
                        'destination_natcd' => '142',//最终目的国
                        // 'net_wt' => $productInfo['product_weight'],
                    );
                    $exportList[] = array('data' => $content, 'state' => 1);
                    $gdsSeqNo++;
                }
            } else {
                $exportList[] = array('data' => [], 'state' => 0, 'error' => $imRow['error'], 'product' => $product);
            }
        }
        //print_r($this->exportList);
        $this->exportList = $exportList;
    }

    /**
     * @todo 先把商品全获取到然后再分成50项目
     */
    private function getbgpri_entry_data_detail_body_detail_split(){

        foreach($this->products as $k=>$p){
            $exportList = array();
            $gdsSeqNo=1;

            $imRow = $this->getBillNO($p['product_id'],$p['qty']); //获取转出数据
            $product = array();
            if(isset($imRow['product'])){
                $product = $imRow['product'];
            }
            $product_declare = $product['product_declared_value'];
            $currency_hs_code = $product['currency_hs_code'];

            $trade_area_code = "";
            if($this->param['trade_area_code']!=''){
                $trade_area_code = $this->param['trade_area_code'];
            }
            $trade_country = ""; //运抵国
            if($this->param['trade_country']!=''){
                $trade_country = $this->param['trade_country'];
            }


            if($imRow['state']==1){
                $cdetails = $imRow['data'];
                foreach($cdetails as $kc=>$cdetail){
                    //print_r($cdetail);
                    $putrec_seqno = "";
                    if(isset($cdetail['recorde_no']) && $cdetail['recorde_no']!=''){
                        $putrec_seqno = $cdetail['recorde_no'];
                    }
                    //$price = $product['']
                    //单价转成澳元
                    //$decalar_price = Service_Currency::converByHscode($cdetail['decalar_currency'],601,$cdetail['decalar_price']);//都转成澳元
                    $decalar_price = $cdetail['decalar_price'];
                    $totalprice = sprintf("%.4f",$cdetail['decalar_price'] * $cdetail['qty']);
                    $content = array(
                        //'gds_seqno'=>$gdsSeqNo,
                        'putrec_seqno' => $putrec_seqno,//备案序号
                        'gds_mtno' => $cdetail['goods_code'],//商品料号
                        'gdecd' => $cdetail['hs_code'],//商品编码(必填)
                        'gds_nm' => $cdetail['product_title'],
                        'gds_spcf_model_desc' => $cdetail['specification'],//规格型号
                        'dcl_unitcd' => $cdetail['decalare_unit'],//申报单位
                        'lawf_unitcd' => $cdetail['legal_unit'],//法定单位
                        'secd_lawf_unitcd' => $cdetail['second_legal_unit'],//法定第二单位
                        'natcd' => $cdetail['country_code'],//国别
                        'dcl_uprc_amt' => $decalar_price,//sprintf("%.4f",$cdetail['decalar_price']),//申报单价
                        'dcl_total_amt' => $totalprice,//申报总价
                        'dcl_currcd' => $cdetail['decalar_currency'],//, //$currency_hs_code, 取底账数据,固定601
                        'dcl_qty' => $cdetail['qty'],//申报数量
                        'lawf_qty' => $cdetail['qty1'],//法定数量
                        'secd_lawf_qty' => $cdetail['qty2'],//第二法定数量
                        'use_cd'=>'',//用途
                        //重量比例因子
                        //第一比例因子
                        //第二比例因子
                        //毛重	净重
                        //用途
                        'lvyrlf_modecd' => $this->param['duty_mode'],//征免方式
                        'ucns_verno'=>'',//单耗版本号
                        //'entry_gds_seqno'=>$gdsSeqNo,//报关单商品序号
                        //申请表序号
                        'rmk'=>'',//备注
                        'origin_country'=>'142',
                        'destination_natcd' => $trade_country,//最终目的国，取运抵国
                        //'gross_weight'
                        'net_wt' => $product['product_net_weight'],
                        'product_id'=>$product['product_id'],
                        'goods_id'=>$product['goods_id']
                    );
                    $bg_pri_entry_data_detail_body_detail_split[] = array('data'=>$content,'state'=>1);
                    //为了测试多增加几条记录
                    /*$bg_pri_entry_data_detail_body_detail_split[] = array('data'=>$content,'state'=>1);
                    $bg_pri_entry_data_detail_body_detail_split[] = array('data'=>$content,'state'=>1);
                    $bg_pri_entry_data_detail_body_detail_split[] = array('data'=>$content,'state'=>1);*/
                    $gdsSeqNo++;
                }
            }else{
                $bg_pri_entry_data_detail_body_detail_split[] = array('data'=>[],'state'=>0,'error'=>$imRow['error'],'product'=>$product);
                $this->error = $imRow['error'];
            }
            //$bg_pri_entry_data_detail_body_detail_split[] = $exportList;
        }
        $this->bg_pri_entry_data_detail_body_detail_split = $bg_pri_entry_data_detail_body_detail_split;
    }
    /**
     * @todo 根据备案序号将备案序号合并在拆分
     */
    private function getbgpri_entry_data_detail_body_detail_split_merge(){
        //将商品按备案序号取相同的合并起来
        $mergeDetail = [];
        foreach ($this->bg_pri_entry_data_detail_body_detail_split as $k=>$vv){
            $data = $vv['data'];
            $putrec_seqno = $data['putrec_seqno']; //备案序号
            if($putrec_seqno==''){
                $this->error[] = "料件号:".$data['goods_id']."无备案序号";
            }else{
                $goodsInfo = Service_Product::getByField($data['goods_id'],'goods_id');
                if(isset($mergeDetail[$putrec_seqno])){
                    //查询料号商品
                    $declare_total = sprintf("%.4f",$goodsInfo['product_declared_value']*$data['dcl_qty']);
                    $uomap = Service_HsUomMap::getByField($goodsInfo['product_id'],'product_id');

                    $qty1 = $uomap['hum_quantity_law']*$data['dcl_qty'];
                    $qty1 = sprintf("%.4f",$qty1);
                    $mergeDetail[$putrec_seqno]['data']['lawf_qty'] = $mergeDetail[$putrec_seqno]['data']['lawf_qty']+$qty1;
                    if($vv['secd_lawf_unitcd']!=""){
                        $qty2 = $uomap['hum_quantity_second']*$data['dcl_qty'];
                        $qty2 = sprintf("%.4f",$qty2);
                        $mergeDetail[$putrec_seqno]['data']['secd_lawf_qty'] = $mergeDetail[$putrec_seqno]['data']['secd_lawf_qty'] + $qty2;
                    }
                    $mergeDetail[$putrec_seqno]['data']['decl_total'] = $mergeDetail[$putrec_seqno]['data']['decl_total'] + $declare_total;
                    $mergeDetail[$putrec_seqno]['data']['dcl_qty'] =  $mergeDetail[$putrec_seqno]['data']['dcl_qty'] + $data['dcl_qty'];
                    $mergeDetail[$putrec_seqno]['data']['dcl_total_amt'] = $mergeDetail[$putrec_seqno]['data']['dcl_total_amt'] + $declare_total;
                    //hum_quantity_law
                    //$mergeDetail[$putrec_seqno]['lawf_qty'] =
                    //$mergeDetail
                }else{
                    $mergeDetail[$putrec_seqno] = $vv;
                    //以下数据重新计算，因为害怕一个商品多个料号存在料号备案信息不一致导致法一，法二，申报价格不一致的情况，只取第一个查到的
                    //$goodsInfo = Service_Product::getByField($data['goods_id'],'goods_id');
                    $declare_total = sprintf("%.4f",$goodsInfo['product_declared_value']*$data['dcl_qty']);
                    $uomap = Service_HsUomMap::getByField($goodsInfo['product_id'],'product_id');

                    $qty1 = $uomap['hum_quantity_law']*$data['dcl_qty'];
                    $qty1 = sprintf("%.4f",$qty1);
                    $mergeDetail[$putrec_seqno]['data']['lawf_qty'] = $qty1;
                    //申报单价取商品的
                    $mergeDetail[$putrec_seqno]['data']['dcl_uprc_amt'] = $goodsInfo['product_declared_value'];
                    $mergeDetail[$putrec_seqno]['data']['dcl_total_amt'] = $declare_total;

                    if($vv['secd_lawf_unitcd']!=""){
                        $qty2 = $uomap['hum_quantity_second']*$data['dcl_qty'];
                        $qty2 = sprintf("%.4f",$qty2);
                        $mergeDetail[$putrec_seqno]['data']['secd_lawf_qty'] = $qty2;
                    }
                    $mergeDetail[$putrec_seqno]['data']['decl_total'] = $declare_total;
                    $mergeDetail[$putrec_seqno]['data']['product_id'] = $goodsInfo['product_id'];
                    $mergeDetail[$putrec_seqno]['data']['net_wt'] = $goodsInfo['product_net_weight'];
                }
            }
        }
        $this->bg_pri_entry_data_detail_body_detail_split = $mergeDetail;
    }



    /**
     * @todo 获取bg_pri_entry_data 预录入数据表
     */
    private function getbg_pri_entry_data(){
        $pro = "ZHQG";
        //return Common_GetNumbers::getCode('ASN', '', $this->_pro);
        //$ref_no = Common_GetNumbers::getOnlyCode('QG',$pro); //出货总单
        $bg_pri_entry_data = array(
            'ref_no'=>$this->sbRow['sb_code'],
            'declare_port'=>$this->param['declare_port'],
            'ie_port'=>$this->param['ie_port'],
            'pt_code'=>$this->param['type'],
            'ie_flag'=>'E',
            'pack_number'=>$this->bg_pri_entry_data['pack_number'],//这时候还不知道等表体获取之后在处理
            'net_weight'=>$this->netweightTotal,
            'gross_weight'=>$this->sbRow['gross_wt'],
            'add_time'=>date("Y-m-d H:i:s",time()),
            'company_code'=>$this->company['company_code'],
            //'op_id'=>'',
        );
        $this->bg_pri_entry_data = $bg_pri_entry_data;
    }
    /**
     * @todo 获取bg_pri_entry_data_detail预录入数据表表体
     */
    private function getbg_pri_entry_data_detail(){
        //总件数校验是否少于报关单数，若不够无法拆分。
        if($this->sbRow['pack_no']<=count($this->bg_pri_entry_data_detail_body_detail)){
            $this->error[] = "出货总单总件数".$this->sbRow['pack_no']."小于报关单数,无法拆分";
        }else{
            $num = count($this->bg_pri_entry_data_detail_body_detail); //报关单数
            //拆分数据
            $netWeightTotal = [];
            foreach ($this->bg_pri_entry_data_detail_body_detail as $k=>$v){
                if($k==0){
                    //$pack_number
                    $pack_number = $this->sbRow['pack_no']-floor($this->sbRow['pack_no']/$num)*($num-1);
                }else{
                    $pack_number = floor($this->sbRow['pack_no']/$num);
                }
                $detailArr = array(
                    'bpd_ref_no'=>$this->sbRow['sb_code'],
                    'bpdd_pack_number'=>$pack_number,
                );
                $netwt = 0;
                foreach ($v as $kv=>$vv){
                    $netwt+=$vv['net_wt_total'];
                }
                $detailArr['net_weight'] = $netwt;

                //毛重和净重的差值
                $gapweight = $this->sbRow['gross_wt']-$this->netweightTotal;
                //将差值按净重比率分配到各个子单里面在加上净重算成子单的毛重
                $detailArr['gross_weight'] = $gapweight*($netwt/$this->netweightTotal)+$netwt;
                $detailArr['add_time'] = date("Y-m-d H:i:s",time());
                $this->bg_pri_entry_data_detail = $detailArr;
            }
        }
    }
    /**
     * @todo 获取bg_pri_entry_data_detail_body_head预录入数据表体对应的报关单
     */
    private function getbg_pri_entry_data_detail_body_head(){
        //总件数校验是否少于报关单数，若不够无法拆分。
        $num = count($this->bg_pri_entry_data_detail_body_detail); //报关单数
        if($this->sbRow['pack_no']<$num){
            $this->error[] = "出货总单总件数".$this->sbRow['pack_no']."小于报关单数:{$num},无法拆分";
        }else{
            //拆分数据
            $netWeightTotal = [];
            $packTotal = 0;
            foreach ($this->bg_pri_entry_data_detail_body_detail as $k=>$v){
                if($k==0){
                    //$pack_number
                    $pack_number = $this->sbRow['pack_no']-floor($this->sbRow['pack_no']/$num)*($num-1);
                }else{
                    $pack_number = floor($this->sbRow['pack_no']/$num);
                }

                $trade_mode = ''; //监管方式
                $trans_mode = ''; //成交方式
                $trade_area_code = '';//贸易国
                $trade_country = ""; //运抵国
                $duty_mode ='';//征免性质--表头的
                if ($this->defaultValue['hz_trade_mode']!='') {
                    $trade_mode = $this->defaultValue['hz_trade_mode'];
                }
                if($this->defaultValue['trade_area_code']!=''){
                    $trade_area_code = $this->defaultValue['trade_area_code'];
                }
                if($this->defaultValue['duty_mode']!=''){
                    $duty_mode = $this->defaultValue['duty_mode'];
                }
                if($this->param['trade_country']!=""){
                    $trade_country = $this->param['trade_country'];
                }
                //这个是表体的duty_model
                $duty_mode_body = $this->defaultValue['duty_mode'];
                if($this->param['duty_mode']!=""){
                    $duty_mode_body = $this->param['duty_mode'];
                }

                if($this->sbRow['trans_mode']){
                    $trans_mode = $this->sbRow['trans_mode'];
                }
                if($this->param['trans_mode']!=""){
                    $trans_mode = $this->param['trans_mode'];
                }

                $trade_area_code = "142";
                if($this->param['trade_area_code']!=''){
                    $trade_area_code = $this->param['trade_area_code'];
                }

                $destination_port = "";
                if($this->param['destination_port']!=''){
                    $destination_port = $this->param['destination_port'];
                }

                $enty_port_code = "";
                if($this->param['enty_port_code']!=''){
                    $enty_port_code = $this->param['enty_port_code'];
                }





                $bodyHeadArr = array(
                    'bpd_ref_no'=>$this->sbRow['sb_code'].'-'.($k+1),
                    'pt_code'=>$this->param['type'],
                    'ie_flag'=>'E',
                    'declare_port'=>$this->param['declare_port'],
                    'ie_port'=>$this->param['ie_port'],
                    'enty_port_code'=>$this->param['enty_port_code'],
                    'ems_no'=>$this->bilInfo['ex_bill_no'],
                    'ems_cop_no'=>'',
                    'platenumber'=>$this->sbRow['sb_truck_no'],
                    'traf_name'=>'',
                    'traf_mode'=>$this->defaultValue['traf_mode'],
                    'voyage_no'=>'',
                    'bill_no'=>'',
                    'wrap_type'=>$this->param['wrap_type'],
                    'net_wt'=>$this->netRows[$k],
                    'gross_wt'=>$v['gross_wt'],
                    'pack_no'=>$pack_number,
                    'duty_mode'=>$duty_mode,
                    'trade_mode'=>$trade_mode,
                    'trans_mode'=>$trans_mode,
                    'trade_country'=>$trade_country,
                    'trade_area_code'=>$trade_area_code,
                    'destination_port'=>$destination_port,
                    'enty_port_code'=>$enty_port_code,
                    'num'=>$num,
                    'trade_co'=>$this->company['trade_co'],
                    'trade_name'=>$this->company['trade_name'],
                    'agent_code'=>$this->company['declare_customs_code'],
                    'agent_name'=>$this->company['declare_company_name'],
                    'owner_code'=>$this->company['trade_co'], //暂时和境内收发货人一致
                    'owner_name'=>$this->company['trade_name'],//
                    'rlt_entry_rvsngd_etps_sccd'=>$this->company['rvsngd_etps_sccd'],//关联报关单消费使用单位拟社会统一信用代码',
                    'rlt_entry_rcvgd_etpsno'=>$this->company['rcvgd_etps_no'],//关联报关单消费使用单位编码',
                    'rlt_entry_rcvgd_etps_nm'=>$this->company['rcvgd_etps_nm'],// 关联报关单消费使用单位名称',
                    'rlt_entry_bizop_etps_sccd'=>$this->company['rvsngd_etps_sccd'],//'关联报关单经营企业社会信用代码',
                    'rlt_entry_bizop_etpsno'=>$this->company['rcvgd_etps_no'],//'关联报关单境内收发货人',
                    'rlt_entry_bizop_etps_nm'=>$this->company['rcvgd_etps_nm'],//关联报关单境内收发货人名称
                );
                $netwt = 0;
                foreach ($v as $kv=>$vv){
                    $netwt+=$vv['net_wt_total'];
                }
                $bodyHeadArr['net_wt'] = $netwt;
                //毛重和净重的差值
                $gapweight = $this->sbRow['gross_wt']-$this->netweightTotal;
                //将差值按净重比率分配到各个子单里面在加上净重算成子单的毛重
                $bodyHeadArr['gross_wt'] = sprintf("%.4f",$gapweight*($netwt/$this->netweightTotal)+$netwt);
                $bodyHeadArr['add_time'] = date("Y-m-d H:i:s",time());
                $this->bg_pri_entry_data_detail_body_head[$k]= $bodyHeadArr;
                $packTotal+=$pack_number;
                //$this->bg_pri_entry_data_detail = $detailArr;
            }
            $this->bg_pri_entry_data['pack_number'] = $pack_number;
        }
    }
    /**
     * @todo 获取bg_pri_entry_data_detail_body_detail预录入数据表体对应的报关单
     */
    private function getbg_pri_entry_data_detail_body_detail(){
        $pri_entry_data_detail = [];

        $splitnum =  $this->splitNumber;
        $num =0;
        $chunkSplitArr = array_chunk($this->bg_pri_entry_data_detail_body_detail_split,$this->splitNumber);
        $netRow = [];

        //这个是表体的duty_model
        $duty_mode_body = $this->defaultValue['duty_mode'];
        if($this->param['duty_mode']!=""){
            $duty_mode_body = $this->param['duty_mode'];
        }
        //境内货源地
        $district_code = "";
        if($this->defaultValue['district_code']!=''){
            $district_code = $this->defaultValue['district_code'];
        }

        foreach ($chunkSplitArr as $k=>$v){
            $no = 1;
            $netwt = 0;
            foreach ($v as $kv=>$vv){
                $data = $vv['data'];
                $splitArr = array(
                    'product_id'=>$data['product_id'],
                    'goods_id'=>$data['goods_id'],
                    //'bpd_ref_no'=>$this->sbRow['sb_code']
                    'g_no'=>$no,//商品序号
                    'contr_item'=>$data['putrec_seqno'], //备案序号
                    'code_ts'=>$data['gdecd'], //商品编号
                    'decl_price'=>$data['dcl_uprc_amt'], //
                    'duty_mode'=>$duty_mode_body,
                    'gmodel'=>$data['gds_spcf_model_desc'],
                    'gname'=>$data['gds_nm'],
                    'origin_country'=>$data['origin_country'],
                    'destination_country'=>$data['destination_natcd'],
                    'trade_curr'=>$data['dcl_currcd'],
                    'decl_total'=>$data['dcl_total_amt'],
                    'gqty'=>$data['dcl_qty'],
                    'first_qty'=>$data['lawf_qty'],
                    'second_qty'=>$data['secd_lawf_qty'],
                    'gunit'=>$data['dcl_unitcd'],
                    'first_unit'=>$data['lawf_unitcd'],
                    'second_unit'=>$data['secd_lawf_unitcd'],
                    'net_wt'=>$data['net_wt'],
                    'net_wt_total'=>sprintf("%.4f",$data['net_wt']*$data['dcl_qty']),
                    'district_code'=>$district_code,
                );
                $netwt+=$splitArr['net_wt_total'];
                $this->bg_pri_entry_data_detail_body_detail[$num][] = $splitArr;
                $no++;
            }
            $this->netweightTotal = $this->netweightTotal+$netwt;
            $this->netRows[$k] = sprintf("%.4f",$netwt);
            $num++;
        }
        //print_r($this->bg_pri_entry_data_detail_body_detail);

        //$this->pri_entry_data_detail = $pri_entry_data_detail;
    }

    /**
     * @todo 获取预录入数据
     */
    public function getPreData(){
        $pridata = array(
            ''
        );
    }
}