<?php

class Service_BilServeBill extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_BilServeBill|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_BilServeBill();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "bsb_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "bsb_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'bsb_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     *
     * @param unknown_type $condition
     * @param unknown_type $type
     * @param unknown_type $pageSize
     * @param unknown_type $page
     * @param unknown_type $order
     */
    public static function getJoinLeftByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getJoinLeftByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();

        return Common_Validator::formValidator($validateArr);
    }


    /**
     * @param array $params
     * @return array
     */
    public function getFields()
    {
        $row = array(

            'E0' => 'bsb_id',
            'E1' => 'sp_code',
            'E2' => 'bsb_code',
            'E3' => 'bsb_no',
            'E4' => 'bsb_amount',
            'E5' => 'currency_code',
            'E6' => 'currency_rate',
            'E7' => 'bsb_mode',
            'E8' => 'bsb_quantity',
            'E9' => 'bsb_payment_total',
            'E10' => 'bsb_charge_weight_total',
            'E11' => 'sm_code',
            'E12' => 'bsb_status',
            'E13' => 'bsb_writeoff_sign',
            'E14' => 'bsb_creator_id',
            'E15' => 'bsb_compare_bill_start',
            'E16' => 'bsb_compare_bill_date_srart',
            'E17' => 'bsb_compare_bill_end',
            'E18' => 'bsb_compare_bill_date_end',
            'E19' => 'bsb_verifier',
            'E20' => 'bsb_verifier_time',
            'E21' => 'bsb_note',
            'E22' => 'bsb_compare_bill_date_last',
            'E23' => 'bsb_start_time',
            'E24' => 'bsb_end_time',
            'E25' => 'bsb_transfer_days',
            'E26' => 'bsb_writeoff_sign_time',
            'E27' => 'bsb_add_time',
            'E28' => 'bsb_update_time',
            'E29' => 'id_code',
        );
        return $row;
    }


    public static function getBasicInfo($bsbId = '')
    {
        $result = array('state' => 0, 'message' => '', 'data' => array());
        try {
            $billRow = Service_BilServeBill::getByField($bsbId);
            if (empty($billRow)) {
                throw new Exception("帐单不存在");
            }

        } catch (Exception $e) {
            $result['state'] = 0;
            $result['message'] = $e->getMessage();
        }

        return $result;
    }

    /**
     * @desc 导出账单明细
     * @param $condition
     * @return array
     */
    public static function getBillData($billData)
    {
        $xlsData = array();        
        if ($billData) {
            switch (strtolower($billData['id_code'])) {
                //逻辑
                case 'standard':
                    //xls 表头
                    $keyMap = array(
                        'A' => '客户代码',
                        'B' => '单号',
                        'C' => '跟踪号',
                        'D' => '运输方式',
                        'E' => '费用发生时间',
                        'F' => '我司计费重量',
                        'G' => '服务商计费重量',
                        'H' => '重量差异',
                        'I' => '我司应付金额',
                        'J' => '服务商金额',
                        'K' => '金额差异',
                        'L' => '备注',
                    );
                    //Excel 表头
                    $xlsData[2] = $keyMap;
                    $totalDeliveredWeight = $totalChargeWeight = $totalDiffWeight = $totalMyAmount = $totalAcceptedAmount = $totalAmount = 0;
                    $type = array(
                        'bil_serve_bill_detail.customer_code',
                        'bil_serve_bill_detail.bsbd_hawb_code',
                        'bil_serve_bill_detail.bsbd_refer_hawb_code',
                        'bil_serve_bill_detail.bsbd_shipment_time',
                        'bil_serve_bill_detail.bsbd_delivered_weight',
                        'bil_serve_bill_detail.bsbd_charge_weight',
                        'bil_serve_bill_difference.bsd_accepted_amount',
                        'bil_serve_bill_difference.bsd_diff_type',
                        'bil_serve_bill_difference.bsd_value',
                        'bil_serve_bill_difference.bsd_amount',
                        'bil_serve_bill_difference.bsd_note',
                    );
                    $rows = Service_BilServeBillDetail::getAllByCondition(array('bsb_id'=> $billData['bsb_id']), $type, 0, 0, array('bil_serve_bill_detail.bsbd_id desc'));
                    //从第二行开始
                    $i = 3; 
                    foreach ($rows as $key => $iv) {
                        $k = $i++;
                        //我司应付金额
                        $myAmount = 0;
                        $condition = array(
                            'sp_code' => $billData['sp_code'],
                            'bb_refer_code' => $iv['bsbd_refer_hawb_code'],
                        );
                    //  $paymentRows = Table_BilPayment::getInstance()->getBusinessDetailFeeByCondition($condition, '*', 0);
                        $paymentRows = Table_BilPayment::getInstance()->getBusinessDetailFeeByCondition($condition, array('bp_id', 'bp_amount'), 0);
                        if (!empty($paymentRows)) {
                            foreach ($paymentRows as $pRow) {
                                $myAmount += $pRow['bp_amount'];
                            }
                        }
                        $xlsData[$k] = array(
                            'A' => $iv['customer_code'],
                            'B' => $iv['bsbd_hawb_code'],
                            'C' => $iv['bsbd_refer_hawb_code'],
                            'D' => $billData['sm_code'],
                            'E' => $iv['bsbd_shipment_time'],
                            'F' => $iv['bsbd_delivered_weight'],
                            'G' => $iv['bsbd_charge_weight'],
                            'H' => $iv['bsd_value'],
                            'I' => $myAmount,
                            'J' => $iv['bsd_accepted_amount'],
                            'K' => $iv['bsd_amount'],
                            'L' => $iv['bsd_note']
                        );
                        $totalDeliveredWeight += $iv['bsbd_delivered_weight'];
                        $totalChargeWeight += $iv['bsbd_charge_weight'];
                        $totalDiffWeight += $iv['bsd_value'];
                        $totalMyAmount += $myAmount;
                        $totalAcceptedAmount += $iv['bsd_accepted_amount'];
                        $totalAmount += $iv['bsd_amount'];
                    }
                    //合计
                    $xlsData[$i] = array(
                            'A' => '合计：',
                            'B' => '',
                            'C' => '',
                            'D' => '',
                            'E' => '',
                            'F' => $totalDeliveredWeight,
                            'G' => $totalChargeWeight,
                            'H' => $totalDiffWeight,
                            'I' => $totalMyAmount,
                            'J' => $totalAcceptedAmount,
                            'K' => $totalAmount,
                            'L' => ''
                    );
                    break;
                case 'random':
                case 'transpeed':
                    //xls 表头
                    $keyMap = array(
                        'A' => '服务商代码',
                        'B' => '账单编号',
                        'C' => '服务商账单号',
                        'D' => '运输方式',
                        'E' => '费用发生时间',
                        'F' => '我司计费重量',
                        'G' => '服务商计费重量',
                        'H' => '重量差异',
                        'I' => '我司应付金额',
                        'J' => '服务商金额',
                        'K' => '金额差异',
                        'L' => '备注',
                    );
                    //Excel 表头
                    $xlsData[2] = $keyMap;
                    $totalDeliveredWeight = $totalChargeWeight = $totalDiffWeight = $totalMyAmount = $totalAcceptedAmount = $totalAmount = 0;
                    $type = array('*', 'bil_serve_bill_detail.bsbd_id as bill_bsbd_id');
                    $rows = Service_BilServeBillDetail::getRandomByCondition(array('bsb_id'=> $billData['bsb_id']), $type, $pageSize, $page, array("bil_serve_bill_detail.bsbd_shipment_time"));
                    $i = 3;
                    foreach ($rows as $key => $val) {
                        $k = $i++;
                        $val['amount'] = Table_BilPayment::getInstance()->getByJoinInnerFeeIdTotal($val['bill_bsbd_id'], 'bsbd_id');
                        $val['bsbdf_amount'] = Table_BilServeBillDetailFee::getInstance()->getTotalAmountBy($val['bill_bsbd_id'], 'bsbd_id');
                        $bilDiffData = Service_BilServeBillDifference::getByField($val['bsbd_id'], 'bsbd_id', array('bsd_value', 'bsd_amount'));
                        $bilDiffData['bsd_amount'] = sprintf("%.3f", abs($val['amount'] - $val['bsbdf_amount'])) == $bilDiffData['bsd_amount'] ? $bilDiffData['bsd_amount'] : sprintf("%.3f", abs($val['amount'] - $val['bsbdf_amount']));
                        $xlsData[$k] = array(
                            'A' => $billData['sp_code'],
                            'B' => $billData['bsb_code'],
                            'C' => "\t".$billData['bsb_no'],
                            'D' => $billData['sm_code'],
                            'E' => $val['bsbd_shipment_time'],
                            'F' => $val['bsbd_delivered_weight'],
                            'G' => $val['bsbd_charge_weight'],
                            'H' => $bilDiffData['bsd_value'],
                            'I' => empty($val['amount']) ? 0.000 : $val['amount'],
                            'J' => empty($val['bsbdf_amount']) ? 0.000 : $val['bsbdf_amount'],
                            'K' => $bilDiffData['bsd_amount'],
                            'L' => $val['bsd_note']
                        );
                        $totalDeliveredWeight += $val['bsbd_delivered_weight'];
                        $totalChargeWeight += $val['bsbd_charge_weight'];
                        $totalDiffWeight += $bilDiffData['bsd_value'];
                        $totalMyAmount += $val['amount'];
                        $totalAcceptedAmount += $val['bsbdf_amount'];
                        $totalAmount += $bilDiffData['bsd_amount'];
                    }
                    //合计
                    $xlsData[$i] = array(
                            'A' => '合计：',
                            'B' => '',
                            'C' => '',
                            'D' => '',
                            'E' => '',
                            'F' => $totalDeliveredWeight,
                            'G' => $totalChargeWeight,
                            'H' => $totalDiffWeight,
                            'I' => $totalMyAmount,
                            'J' => $totalAcceptedAmount,
                            'K' => $totalAmount,
                            'L' => ''
                    );
                    break;
            }
        }else {
            return false;
        }
        return $xlsData;
    }
}