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

use app\BaseController;
use app\model\api\User as UserModel;
use app\model\api\Activity as ActivityModel;
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 Activity extends  BaseController{
    private $activityDefaultParms = [
        ["title"=>"联系电话","type"=>"input","required"=>1,"content"=>"","parms"=>[]],
        ["title"=>"联系人","type"=>"input","required"=>1,"content"=>"","parms"=>[]],
    ];
    private $activityFromType=[
        ["title"=>"文本输入框","type"=>"input"],
        ["title"=>"下拉选择框","type"=>"select"],
        ["title"=>"文本域","type"=>"textarea"],
    ];
    /**
     * 活动列表
     * @param Request $request
     * @return type
     */
    public function list(Request $request) {
        $pageSize = 50;
        $post =  UtilService::getMore([
                ['page',1],
                ['title',''],
                ['is_main',''],
                ['status',''],
                ['is_show',''],
                ['time',[]],
        ],$request);
        $where = [];
        //添加时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $where[]=["c.add_time","between","{$startTime},{$endTime}"];
        }
        if (!empty($post["title"])){
            $where[]=["c.title","like","%{$post['title']}%"];
        }
        if (!empty($post["is_main"]) && (int)$post["is_main"]==1){
            $where[]=["c.is_main","=",1];
        }
        if(in_array((string)$post["status"],['1','0'])){
            //活动已经结束
            if((string)$post["status"]=="0"){
                $where[]=["c.time","<=",time()];
            }
            //报名中
            if((string)$post["status"]=="1"){
                $where[]=["c.time",">",time()];
            }
        }
        if(in_array((string)$post["is_show"],['1','0'])){
            $where[]=["c.is_show","=",(int)$post["is_show"]];
        }
        $data = (new ActivityModel)
                ->field("c.*,IFNULL(o.order_count,0) as order_count")
                ->alias("c")
                ->leftJoin("(select count(*) as order_count,activity_id  from table_activity_order where status > 0 group by activity_id) as o","o.activity_id = c.id")
                ->where($where)
                ->page((int)$post["page"], (int)$pageSize)
                ->order("c.is_main","desc")
                ->order("c.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new ActivityModel)->alias("c")->where($where)->count();
        $data = empty($data)?[]:$data;
        $defaultParms=$this->activityDefaultParms;
        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]["labels"]   = empty($v["labels"]) ? [] : explode(",",$v["labels"]);
            $data[$k]["time"]     = date("Y-m-d H:i:s",$v["time"]);
            $data[$k]["add_time"] = date("Y-m-d H:i:s",$v["add_time"]);
            $data[$k]["status"]   = $v["time"] > time() ? 1 : 0;
            $data[$k]["data"]        = empty($v["data"]) ? [] : unserialize($v["data"]);
        }
        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post["page"],
            'defaultParms' => $defaultParms,
            'activityFromType'=>$this->activityFromType,
        ]);
    }

    
    /**
     * 添加编辑活动
     * @param Request $request
     * @return type
     */
    public function add(Request $request){
        $post = UtilService::getMore([
            ['id','0'],
            ['title','','empty','请填写活动标题'],
            ['mono',''],
            ['deposits_price','0','is_numeric','请输入正确的活动定金'],
            ['time','','empty','请选择活动时间'],
            ['time_str',''],
            ['address',''],
            ['imgs',[],'empty','请上传活动主图'],
            ['descs',[],'empty','请上传活动详情图'],
            ['labels',[]],
            ['is_show','0'],
            ['is_main','0'],
            ['data',[],'empty','请添加报名参数'],
        ],$request);
        $post["deposits_price"] = floatval($post["deposits_price"]);
        $post["time"] = strtotime($post["time"]);
        $post["imgs"] = empty($post["imgs"]) ? "" : implode(",", $post["imgs"]);
        $post["descs"] = empty($post["descs"]) ? "" : implode(",", $post["descs"]);
        $post["labels"] = empty($post["labels"]) ? "" : implode(",", $post["labels"]);
        $post["is_show"] = (int)$post["is_show"];
        $post["is_main"] = (int)$post["is_main"];
        if($post["is_main"]==1){
            (new ActivityModel)->where("is_main",1)->update(["is_main"=>0]);
        }
        //参数添加
        $parmsAr = empty($post["data"]) ? [] : $post["data"];
        $post["data"]=[];
        $activityFromType = $this->activityFromType;
        foreach($parmsAr as $k=>$v){
            if(!empty($v["title"]) && !empty($v["type"])){
                $check = false;
                foreach($activityFromType as $k2=>$v2){
                    if($v2["type"]==$v["type"]){
                        $check = true;
                        break;
                    }
                }
                if(!$check){
                    return app('json')->fail("请选择正确的参数类型");
                }
                if($v["type"]=="select" && (empty($v["parms"]) || !is_array($v["parms"]))){
                    return app('json')->fail("请添加下拉选择框的选项值");
                }
                if($v["type"]!="select"){
                    $v["parms"] = [];
                }
                $post["data"][]=[
                    "title"   => trim($v["title"]),
                    "content" => trim($v["content"]),
                    "type"    => trim($v["type"]),
                    "required"=> (int)$v["required"]==1?1:0,
                    "parms"   => $v["parms"],
                ];
            }
        }
        $post["data"] = serialize($post["data"]);
        
        
        $id = $post["id"];
        unset($post["id"]);
        $r=0;
        if(empty($id) || $id=="0"){
            $post["add_time"] = time();
            $r = (new ActivityModel)->insert($post);
        }else{
            $r = (new ActivityModel)->where("id",$id)->update($post);
        }
        if($r){
            return app('json')->success("数据保存成功");
        }else{
            return app('json')->fail("数据保存失败");
        }
    }

    
}