<?php
namespace DAO\Goods;
/**
 * 运费
 * User: liuyuzhen
 * Date: 2018/6/28
 * Time: 19:26
 * Description:
 */
class TransportModel extends \DAO\AbstractModel{
    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_transport';

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';

    public function init()
    {

    }

    public function find($where,$field = \Our\NameConst::allField){
        $this->setDb($this->dbName);
        $result = $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
        return $result;
    }

    /**
     * 计算某个具单元的运费
     * @param 配送地区 $area_id
     * @param 购买数量 $num
     * @param 运费模板内容 $extend
     * @return number 总运费
     */
    public function calcUnit($areaId, $num, $extend){
        if (!empty($extend) && is_array($extend)){
            foreach ($extend as $v) {
                if (strpos($v['area_id'],",".$areaId.",") !== false){
                    if ($num <= $v['snum']){
                        //在首件数量范围内
                        $calcTotal = $v['sprice'];
                    }else{
                        //超出首件数量范围，需要计算续件
                        $calcTotal = sprintf('%.2f',($v['sprice'] + ceil(($num-$v['snum'])/$v['xnum'])*$v['xprice']));
                    }
                }
                if ($v['is_default']==1){
                    if ($num <= $v['snum']){
                        //在首件数量范围内
                        $calcDefaultTotal = $v['sprice'];
                    }else{
                        //超出首件数量范围，需要计算续件
                        $calcDefaultTotal = sprintf('%.2f',($v['sprice'] + ceil(($num-$v['snum'])/$v['xnum'])*$v['xprice']));
                    }
                }
            }
            //如果运费模板中没有指定该地区，取默认运费
            if (!isset($calcTotal) && isset($calcDefaultTotal)){
                $calcTotal = $calcDefaultTotal;
            }
        }
        return intval($calcTotal*\Our\ApiConst::hundred);
    }


    private static $_instance = null;
    /**
     * 获取类实例
     */
    public static function getInstance($dbName = \Our\DbNameConst::salveDBConnectName) {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($dbName);
        }
        return self::$_instance;
    }
}