<?php
/**
 * Function Description:${CARET}
 * Function Name: FxUserService
 * ${PARAM_DOC}
 *
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 *
 * @author 娄梦宁
 */

namespace admin\service\prod;

use common\models\BaseCategory;
use common\models\CmsCategory;
use common\models\CmsCategoryProd;
use common\models\ProdCategory;
use common\models\ProdMain;
use common\util\UploadPic;
use common\util\Util;
use Yii;
use yii\base\Exception;


class ProdService
{

    /*
     * 产品列表
     */
    public function getProdList($param)
    {
        $prod_category = new ProdCategory();
        $prod_main = new ProdMain();
        $prod_info = $prod_category->AdminGetList($param);
        $prod_list = $prod_info['list'];
        foreach ($prod_list as $key => $val) {
            $prod_list[$key]['price_name'] = $prod_main->getProdArr($val['pro_cate_id']);
            $s_time=$prod_list[$key]['close_sale_time'];
                if($s_time=='') $s_time = '24';
                if($s_time>0){
                    $s_day = 0;
                    $s_hour = $s_time;
                }else if($s_time==0){
                    $s_day = 1;
                    $s_hour = 24;
                }else{
                    $s_day = floor(abs($s_time)/24)+1;
                    $s_hour = abs(abs($s_time)-$s_day*24);
                }
            $prod_list[$key]['sale_day']=(string)$s_day;
            $prod_list[$key]['sale_hour']=(string)$s_hour;
        }
        $page_size = $param['page_size'];
        $total_count = $prod_info['count'];
        $total_pages = ceil($total_count / $page_size);
        $result = [
            'prod_list' => $prod_list,
            'page' => [
                'current_page' => (string)$param['current_page'],
                'total_pages' => (string)$total_pages,
                'page_size' => (string)$page_size,
                'total_count' => (string)$total_count,
            ]
        ];
        return Util::returnArrSu('', $result);
    }

    /*
     * 产品大类型基础数据.左侧菜单栏数据
     */
    public function getCmsCategory()
    {
        $cms_category = new CmsCategory();
        $base_category = new BaseCategory();
        $category = $cms_category->getCategoryArr();
        $baseCategory = $base_category->getTypeArr();
        $result = ['cms_category' => $category, 'base_category' => $baseCategory];
        return Util::returnArrSu('', $result);
    }

    /*
     * 产品推荐
     */
    public function RecomProd($pro_cate_id)
    {
        $prod_category = new ProdCategory();
        $result = $prod_category->Recommend($pro_cate_id);
        if ($result !== false) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('数据库错误');
    }

    /**
     * Function Description:新增产品
     * Function Name: AddProd
     * @param $param
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function AddProd($param)
    {
        $checkParam = $this->checkParam($param);
        if (!$checkParam) {
            return Util::returnArrEr('参数错误');
        }
        $prod_category = new ProdCategory();
        $prod_main = new ProdMain();
        $cms_category = new CmsCategory();
        $transaction = Yii::$app->db->beginTransaction();
        //产品主表信息插入
        $istProdCategory = $prod_category->addProd($param);
        //获取刚插入数据库的产品id
        $param['prod_cate_id'] = $prod_category->pro_cate_id;
        //绑定产品栏目表
        $istCmsCategory = $cms_category->addCmsProd($param);
        if ($istProdCategory && $istCmsCategory) {
            //插入子产品表
            $istProdMain = $prod_main->addProdMain($param);
            if ($istProdMain) {
                //修改首页展示价格为子产品最低价
                $prod_category->changeShowPrice($param['prod_cate_id']);
                $transaction->commit();
                return Util::returnArrSu('');
            }
        }
        $transaction->rollBack();
        return Util::returnArrEr('新增产品失败');
    }

    /**
     * Function Description:修改产品信息
     * Function Name: UptProd
     * @param $param
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function UptProd($param)
    {
        $checkParam = $this->checkParam($param);
        if (!$checkParam) {
            return Util::returnArrEr('参数错误');
        }
        $prod_category = new ProdCategory();
        $prod_main = new ProdMain();
        $cms_category_prod = new CmsCategoryProd();
        $transaction = Yii::$app->db->beginTransaction();
        //主表数据更新
        $uptProd = $prod_category->uptAdminProd($param);
        if ($uptProd === false) {
            $transaction->rollBack();
            return Util::returnArrEr('修改失败');
        }
        //修改子产品表
        $pro_main_id_arr = $prod_main->getIdArr($param['pro_cate_id']);
        $arrCheck = [];
        foreach ($param['price_type'] as $val) {
            $arrCheck[] = $val['prod_id'];
            $uptProdMain = $prod_main->uptCmsProd($val, $param['pro_cate_id']);
            if ($uptProdMain === false) {
                $transaction->rollBack();
                return Util::returnArrEr('修改失败');
            }
        }
        foreach ($pro_main_id_arr as $key => $val) {
            if (!in_array($key, $arrCheck)) {
                $delCount = $prod_main->delCount($key);
                if ($delCount === false) {
                    $transaction->rollBack();
                    return Util::returnArrEr('修改失败');
                }
            }
        }

        //修改产品与栏目绑定关系
        $uptCmsAdmin = $cms_category_prod->uptCmsAdmin($param);
        if ($uptCmsAdmin === false) {
            return Util::returnArrEr('修改失败');
        }
        $prod_category->changeShowPrice($param['pro_cate_id']);
        $transaction->commit();
        return Util::returnArrSu('');
    }

    /*
     * 产品图片上传
     */
    public function uploadImg($file)
    {
        $time = time() . rand(1000, 9999);
        $upDir = ROOT_PATH . '/web/admin/images/prodImg/' . $time . '.jpg';
        $config = Util::getSiteConfig();
        $url = $config['host_name'] . '/web/admin/images/prodImg/' . $time . '.jpg';
        $img_url = UploadPic::_UPLOADPIC($file, 100000, $upDir);
        if ($img_url['flag'] == true) {
            if (file_exists($upDir) == false) {
                return Util::returnArrEr("$upDir");
            }
            UploadPic::cutPic($upDir, $img_url['data']['url'] . '.min.jpg');//生成小图 从中间剪切
            if (file_exists($img_url['data']['url'] . '.min.jpg') == false) {
                return Util::returnArrEr('上传失败[10001]');
            }
            return Util::returnArrSu('', ['url' => $url]);
        }
        $msg = empty($img_url['msg']) ? '上传失败[10003]' : $img_url['msg'];
        return Util::returnArrEr($msg);
    }

    /*
     * 自定义佣金按pro_cate_id
     */
    public function DefineCommission($pro_cate_id, $commission)
    {
        $transaction = Yii::$app->db->beginTransaction();
        $prod_category = new ProdCategory();
        $result=$prod_category->DefineCommission($pro_cate_id, $commission);
        if($result===false) {
            $transaction->rollBack();
            return Util::returnArrEr('自定义佣金失败，请联系相关技术人员');
        }

        $prod_main = new ProdMain();
        $param = ["prod_cate_id"=>$pro_cate_id,"commission"=>$commission];
        $result = $prod_main->setProdCommissionByCateId($param);
        if($result===false) {
            $transaction->rollBack();
            return Util::returnArrEr('自定义佣金失败，请联系相关技术人员');
        }
        $transaction->commit();
        return Util::returnArrSu('自定义佣金成功，pro_cate_id修改');
    }
    /*
     * 自定义佣金 按prod_id
     */
    public function DefineCommissionByProdId($param){
        $prod_commission_arr = json_decode($param['prod_commission_arr'],true);  //[{prod_id:x,commission:x}];

        $prod_main = new ProdMain();
        $transaction = Yii::$app->db->beginTransaction();
        foreach($prod_commission_arr as $k=>$v){
            $param = ["prod_id"=>$v['prod_id'],"commission"=>$v['commission']];
            $result=$prod_main->setProdCommissionByProdId($param);
            if($result===false){
                $transaction->rollBack();
                return Util::returnArrEr();
            }
        }
        $transaction->commit();
        return Util::returnArrSu();

    }

    /**
     * Function Description:新增产品
     * Function Name: checkParam
     * @param $param
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function checkParam($param)
    {
        if (Util::checkPattern('intVal', $param['category_id']) == false) {
            return false;
        } elseif ($param['pro_cate_name'] == '') {
            return false;
        }
        return true;
    }
}