<?php
declare (strict_types = 1);
namespace app\system\controller\v1;

use app\BaseController;
use app\model\api\User;
use app\model\api\GoodsCate;
use app\model\api\Coupon as CouponModel;
use app\model\api\Goods as GoodsModel;
use app\Request;
use library\services\UtilService;

// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | [ 商城管理 ]
// +----------------------------------------------------------------------
// | Date: 2020-09-06 21:53
// +----------------------------------------------------------------------

class Goods extends  BaseController{
    
    private $goodsDefaultParms = [
        ["title"=>"赋意","content"=>""],
        ["title"=>"盆","content"=>""],
        ["title"=>"配花","content"=>""],
        ["title"=>"配草","content"=>""],
        ["title"=>"插件","content"=>""],
        ["title"=>"IP","content"=>""],
        ["title"=>"时间","content"=>""],
        ["title"=>"花开","content"=>""],
    ];
    /**
     * 商品列表
     * @param Request $request
     * @return type
     */
    public function list(Request $request) {
        $pageSize = 50;
        $post =  UtilService::getMore([
                ['page',1],
                ['title',''],
                ['is_hot',''],
                ['is_hot_sell',''],
                ['is_ip',''],
                ['status',''],
                ['cate_id',''],
                ['uip',''],
                ['time',[]],
        ],$request);
        $where = [];
        
        if (!empty($post["title"])){
            $where[]=["g.title","like","%{$post['title']}%"];
        }
        if(in_array((string)$post["is_hot"],['1','0'])){
            $where[]=["g.is_hot","=",(int)$post["is_hot"]];
        }
        if(in_array((string)$post["is_hot_sell"],['1','0'])){
            $where[]=["g.is_hot_sell","=",(int)$post["is_hot_sell"]];
        }
        if(in_array((string)$post["is_ip"],['1','0'])){
            $where[]=["g.is_ip","=",(int)$post["is_ip"]];
        }
        if(in_array((string)$post["status"],['1','0'])){
            $where[]=["g.status","=",(int)$post["status"]];
        }
        if (!empty($post["cate_id"])){
            $where[]=["g.cate_id","=",$post['cate_id']];
        }
        if (!empty($post["uip"])){
            $where[]=["g.uip","=",$post['uip']];
        }
        //更新时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $where[]=["g.update_time","between","{$startTime},{$endTime}"];
        }
        $data = (new GoodsModel)
                ->field("g.*")
                ->alias("g")
                ->where($where)
                ->page((int)$post["page"], (int)$pageSize)
                ->order("g.update_time","desc")
                ->order("g.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new GoodsModel)->alias("g")->where($where)->count();
        $defaultParms=$this->goodsDefaultParms;
        $data = empty($data)?[]:$data;
        foreach($data as $k=>$v){
            $data[$k]["imgs"]        = empty($v["imgs"]) ? [] : explode(",",$v["imgs"]);
            $data[$k]["descs"]       = empty($v["descs"]) ? [] : explode(",",$v["descs"]);
            $data[$k]["time"]        = date("Y-m-d H:i:s",$v["time"]);
            $data[$k]["update_time"] = date("Y-m-d H:i:s",$v["update_time"]);
            $data[$k]["cate_id"]     = empty($v["cate_id"])?"":$v["cate_id"];
            $data[$k]["data"]        = empty($v["data"]) ? [] : unserialize($v["data"]);
        }
        return app('json')->success([
            'list'         => $data,
            'pageCount'    => $pageCount,
            'pageSize'     => $pageSize,
            'page'         => $post["page"],
            'defaultParms' => $defaultParms,
        ]);
    }

    
    /**
     * 添加编辑商品
     * @param Request $request
     * @return type
     */
    public function add(Request $request){
        $post = UtilService::getMore([
            ['id','0'],
            ['cate_id','','empty','请选择商品分类'],
            ['title','','empty','请填写商品标题'],
            ['describe',''],
            ['price','0','is_numeric','请输入正确的售价'],
            ['old_price','0','is_numeric','请输入正确的原价'],
            ['imgs',[],'empty','请上传商品主图'],
            ['descs',[],'empty','请上传商品详情图'],
            ['is_hot','0'],
            ['is_hot_sell','0'],
//            ['uip',''],
            ['is_ip','0'],
            ['ip_title',''],
            ['ip_price','0'],
            ['ip_income_per','0','is_numeric','请输入IP收益百分比'],
            ['status','0'],
            ['give_score','0','is_numeric','请输入正确的赠送积分'],
            ['data',[]],
        ],$request);
        if($post["is_ip"]==1 && (!is_numeric(trim($post["ip_price"])) || trim($post["ip_price"])<=0)){
            return app('json')->fail("'请输入买断售价");
        }
        if($post["is_ip"]==1){
            $post["ip_price"] = floatval(trim($post["ip_price"]));
        }else{
            $post["ip_price"] = 0;
        }
        
        
        $post["ip_income_per"] = empty($post["ip_income_per"])?0:(int)$post["ip_income_per"];
        $post["price"] = floatval($post["price"]);
        $post["old_price"] = floatval($post["old_price"]);
        $post["imgs"] = empty($post["imgs"]) ? "" : implode(",", $post["imgs"]);
        $post["descs"] = empty($post["descs"]) ? "" : implode(",", $post["descs"]);
        $post["is_hot"] = (int)$post["is_hot"]==1?1:0;
        $post["is_hot_sell"] = (int)$post["is_hot_sell"]==1?1:0;
        $post["is_ip"] = (int)$post["is_ip"]==1?1:0;
        $post["ip_price"] = floatval($post["ip_price"]);
        $post["status"] = (int)$post["status"]==1?1:0;
        $post["give_score"] = (int)$post["give_score"];
        $post["update_time"] = time();
        if($post["is_ip"]==1 && $post["ip_price"]<=0){
            return app('json')->fail("请输入正确的买断售价");
        }
        if($post["is_ip"]==1 && ($post["ip_income_per"]<0 || $post["ip_income_per"]>100)){
            return app('json')->fail("请输入正确的IP分成比例");
        }
        if(!empty($post["uip"])){
            $udata = (new User)->where("uip",$post["uip"])->find();
            if(empty($udata)){
                return app('json')->fail("用户不存在");
            }
            $post["uid"] = $udata["uid"];
            $post["uip"] = $udata["uip"];
        }
        $parmsAr = empty($post["data"]) ? [] : $post["data"];
        $post["data"]=[];
        foreach($parmsAr as $k=>$v){
            if(!empty($v["title"]) && !empty($v["content"])){
                $post["data"][]=[
                    "title"   => trim($v["title"]),
                    "content" => trim($v["content"]),
                ];
            }
        }
        $post["data"] = serialize($post["data"]);
        $id = $post["id"];
        unset($post["id"]);
        $r=0;
        if(empty($id) || $id=="0"){
            $post["time"] = time();
            $r = (new GoodsModel)->insert($post);
        }else{
            $r = (new GoodsModel)->where("id",$id)->update($post);
        }
        if($r){
            return app('json')->success("数据保存成功");
        }else{
            return app('json')->fail("数据保存失败");
        }
    }
    /**
     * 删除商品
     * @param Request $request
     */
    public function del(Request $request) {
        
    }
    /**
     * 优惠券列表
     * @param Request $request
     * @return type
     */
    public function coupon(Request $request) {
        $pageSize = 50;
        $post =  UtilService::getMore([
            ['page',1],
            ['status',''],
        ],$request);
        $where=[];
        if((string)$post["status"]!=""){
            $where[]=["status","=",(int)$post["status"] == 1 ? 1 : 0];
        }
        $data = (new CouponModel)
                ->where($where)
                ->page((int)$post["page"], (int)$pageSize)
                ->order("id","desc")
                ->order("seq","desc")
                ->select()
                ->toArray();
        $pageCount = (new CouponModel)->where($where)->count();
        $data = empty($data)?[]:$data;
        foreach($data as $k=>$v){
            $data[$k]["time"] = date("Y-m-d H:i:s",$v["time"]);
        }
        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post["page"]
        ]);
    }
    /**
     * 添加编辑优惠券
     * @param Request $request
     */
    public function couponAdd(Request $request){
        $post = UtilService::getMore([
            ['id','0'],
            ['title','','empty','请填写优惠券标题'],
            ['price','','is_numeric','请填写正确的优惠券面值'],
            ['limit_price','','is_numeric','请填写正确的满减标准'],
            ['day','','is_numeric','请填写正确的有效天数'],
            ['seq','0'],
            ['status','0']
        ],$request);
        $id = (int)$post["id"];
        unset($post["id"]);
        $post["price"] = floatval($post["price"]);
        $post["limit_price"] = floatval($post["limit_price"]);
        $post["day"] = intval($post["day"]);
        $post["seq"] = intval($post["seq"]);
        $post["status"] = intval($post["status"])==1?1:0;
        if($post["price"]<=0){
            return app('json')->fail("请输入正确的优惠券面值");
        }
        $r=0;
        if(empty($id)){
            $post["time"] = time();
            $r = (new CouponModel)->insert($post);
        }else{
            $r = (new CouponModel)->where("id",$id)->update($post);
        }
        if($r){
            return app('json')->success("数据保存成功");
        }else{
            return app('json')->fail("数据保存失败");
        }
    }
    /**
     * 删除优惠券
     * @param Request $request
     */
    public function couponDel(Request $request) {
        [$id] = UtilService::getMore([
            ['id',0,'empty','参数错误']
        ],$request,true);
        $bool =   (new CouponModel)->where("id",$id)->delete();
        return app('json')->success("删除成功");
    }
    
    
    /**
     * 商品分类列表
     * @param Request $request
     * @return type
     */
    public function cate(Request $request) {
        $pageSize = 50;
        $post =  UtilService::getMore([
                ['page',1],
                ['title',''],
        ],$request);
        $data = (new GoodsCate)
                ->when(1 == 1, function ($query) use ($request, $post) {
                    if (!empty($post["title"])){
                        $query->where("title",$post["title"]);
                    }
                })
                ->page((int)$post["page"], (int)$pageSize)
                ->order("sort","desc")
                ->order("id","desc")
                ->select()
                ->toArray();
        $pageCount = (new GoodsCate)
                ->when(1 == 1, function ($query) use ($request, $post) {
                    if (!empty($post["title"])){
                        $query->where("title",$post["title"]);
                    }
                })
                        ->count();
        $data = empty($data)?[]:$data;
        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post["page"]
        ]);
    }

    /**
     * 添加分类
     */
    public function cateAdd(Request $request){
        $post = UtilService::getMore([
            ['id','0'],
            ['title','','empty','请填写分类名称'],
            ['sort','0'],
            ['code',''],
            ['img','','empty','请上传分类图标'],
            ['is_show','0']
        ],$request);
        $id = $post["id"];
        unset($post["id"]);
        $r=0;
        if(empty($id) || $id=="0"){
            $r = (new GoodsCate)->insert($post);
        }else{
            $r = (new GoodsCate)->where("id",$id)->update($post);
        }
        
        if($r){
            return app('json')->success("数据保存成功");
        }else{
            return app('json')->fail("数据保存失败");
        }
    }

    /**
     * 分类删除
     * @param Request $request
     */
    public function cateDel(Request $request) {
        [$id] = UtilService::getMore([
            ['id',0,'empty','参数错误']
        ],$request,true);
        $bool =   (new GoodsCate)->where("id",$id)->delete();
        return app('json')->success("分类删除成功");
    }

}