<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/3/14
 * Time: 17:47
 */

namespace App\Modules;

use App\Modules\Book\Services\BookConfigService;

class Util
{
    /**
     * 计算成本率
     * @param $amount 充值金额
     * @param $cost 成本
     * @return int|string
     */
    static function getPersentAmount($amount, $cost)
    {
        $percentResult = '0%';
        if (is_numeric($amount) && $amount > 0) {
            if (abs($cost) < 0.01) {
                $percentResult = '100%';
            } else {
                $percentResult = round(($amount / $cost) * 100, 2) . '%';
            }
        }
        return $percentResult;
    }

    static function getPersentAmountInteger($amount, $cost)
    {
        $percentResult = '0';
        if (is_numeric($amount) && $amount > 0) {
            if (abs($cost) < 0.01) {
                $percentResult = '1';
            } else {
                $percentResult = round(($amount / $cost), 4);
            }
        }
        return $percentResult;
    }

    /**
     * 加密site id
     */
    static function encodeDistributionChannelId($id)
    {
        $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
        return $hashids->encode($id);
    }

    /**
     * 根据图书id获取域名
     * @param string $bid
     * @return string
     */
    static function getDomainByBid($bid = '')
    {
        $domain = 'leyuee.com';
        //如果图书id为空,则返回默认的域名
        if (!empty($bid)) {
            $bookConfig = BookConfigService::getBookById($bid);
            if ($bookConfig) {
                $domain = $bookConfig->promotion_domain;
            }
        }
        return $domain;
    }

    static function getFormatDate($date, $created_at = '')
    {
        $count = strlen($date);
        if ($created_at) {
            $year = date('Y', strtotime($created_at));
        } else {
            $year = date('Y');
        }

        if (2 == $count) {
            $date = $year . '0' . $date[0] . '0' . $date[1];
        } elseif (3 == $count) {
            if (0 === strpos($date, '0')) {
                $date = $year . substr($date, 0, 2) . '0' . $date[2];
            } else {
                $date = $year . '0' . $date;
            }
        } elseif (4 == $count) {
            $date = $year . $date;
        }
        return $date;
    }

    static function getFullDate($year, $month, $day, $created_at = '')
    {
        if (strlen($year) != 4) {
            if ($created_at) {
                $year = date('Y', strtotime($created_at));
            } else {
                $year = date('Y');
            }
        }

        $day = (strlen($day) == 1) ? ('0' . $day) : $day;
        $month = (strlen($month) == 1) ? ('0' . $month) : $month;
        $date = $year . $month . $day;
        $date = date('Y/m/d', strtotime($date));
        return $date;
    }
}