<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 * 装扮商城接口
 */
class Attire extends Api
{
    protected $noNeedLogin = ['getAttireList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->attireModel = new \app\common\model\Attire();
        $this->attirebackModel = new \app\common\model\AttireBack();
    }

    /**
     * 获取装扮列表
     */
    public function getAttireList() {
        $type = $this->request->request("type"); // 装扮类型:1=座驾,2=头饰,3=聊天气泡,4=消息尾灯
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        // 获取基本信息
        $where = [];
        $where["type"] = $type;
        $where["is_show"] = 1;
        $attireList = $this->attireModel->where($where)->limit($pageStart,$pageNum)->select();
        if($attireList) {
            foreach($attireList as $k => $v) {

            }
        }
        $this->success("获取成功!",$attireList);
    }

    /**
     * 购买并加入我的背包
     */
    public function attireAddToMyBack() {
        $attire_id = $this->request->request("attire_id"); //装扮ID
        if (!$attire_id) {
            $this->error(__('Invalid parameters'));
        }
        if ($this->auth->power->attire == 1) {
            $this->error('您已被禁止购买装扮');
        }
        // 判断用户钻石余额是否充足
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->where(["id"=>$this->auth->id])->find();
        if(!$userInfo) {
            $this->error("用户信息获取失败!");
        }
        // 获取购买装扮需要的价格
        $attireInfo = $this->attireModel->where(["id"=>$attire_id])->find();
        if(!$attireInfo) {
            $this->error("装扮信息获取失败!");
        }
        if($userInfo["jewel"] < $attireInfo["price"]) {
            $this->error("您的余额不足,请先充值!");
        }
        // 进行购买逻辑
        Db::startTrans();
        try{
            $userjewellogModel = new \app\common\model\UserJewelLog();
            // 扣除用户钻石余额
            $where = [];
            $where["id"] = $this->auth->id;
            $res1 = $userModel->where($where)->setDec("jewel",$attireInfo["price"]);
            // 添加当前用户钻石流水记录
            $res2 = $userjewellogModel->addUserJewelLog($this->auth->id, $attireInfo["price"], "-", $userInfo["jewel"], "购买装扮扣除" . $attireInfo["price"] . "钻石!", 6);
            // 添加装扮购买记录
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["attire_id"] = $attire_id;
            $data["price"] = $attireInfo["price"];
            $data["attire_name"] = $attireInfo["title"];
            $data["createtime"] = time();
            $attirebylogModel = new \app\common\model\AttireBuyLog();
            $res3 = $attirebylogModel->insertGetId($data);
            // 加入我的背包
//            $where = [];
//            $where["user_id"] = $this->auth->id;
//            $where["attire_id"] = $attire_id;
//            $attirebackInfo = $this->attirebackModel->where($where)->find();
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["attire_id"] = $attire_id;
            $data["attire_name"] = $attireInfo["title"];
            $data["price"] = $attireInfo["price"];
            $data["file_image"] = $attireInfo["file_image"];
            $data["android_image"] = $attireInfo["android_image"];
            $data["gif_image"] = $attireInfo["gif_image"];
            $data["limit_day"] = $attireInfo["limit_day"];
            $data["type"] = $attireInfo["type"];
            $data["createtime"] = time();
//            if($attirebackInfo) { // 背包中已有商品
//                if($attirebackInfo["is_use"] == 1) { // 商品正在使用中
//                    if($attirebackInfo["duetime"] >= time()) { // 使用中未到期
//                        $duetime = $attireInfo["limit_day"]*86400;
//                        $res4 = $this->attirebackModel->setInc("duetime",$duetime);
//                    } else { // 使用中已到期
//                        $res4 = $this->attirebackModel->insert($data);
//                    }
//                } else { // 商品未使用
//                    $res4 = $this->attirebackModel->insert($data);
//                }
//            } else { // 背包中没有此商品
//                $res4 = $this->attirebackModel->insert($data);
//            }
            $res4 = $this->attirebackModel->insert($data);

            if($res1 && $res2 && $res3 && $res4) {
                Db::commit();
                $this->success("购买成功!");
            } else {
                $this->error("购买失败,请稍后重试!");
            }

        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取我的背包装饰列表
     */
    public function getBackAttireList() {
        try {
            $page = $this->request->request('page',1); // 分页
            $pageNum = $this->request->request('pageNum',10); // 分页
            $type = $this->request->request("type"); // 装扮类型:1=座驾,2=头饰,3=聊天气泡,4=消息尾灯
            // 分页搜索构建
            $pageStart = ($page-1)*$pageNum;
            global $where;
            $where = [];$whereOr=[];
            $where["user_id"] = $this->auth->id;
            $type && $where["type"] = $type;

            $whereOr["is_use"] = "0";
            $whereOr["duetime"] = ["gt",time()];
            $list = $this->attirebackModel
                ->field("id,type,file_image,gif_image,attire_name as title,limit_day,duetime,is_use,is_using")
                ->where(function ($query) {
                    global $where;
                    $query->where($where);
                })
                ->where(function ($query) {
                    $query->whereOr(["is_use"=>0,"duetime"=>["gt",time()]]);
                })
                ->limit($pageStart,$pageNum)
                ->select();

            if(!$list) {
                $this->success("背包空空如也!");
            }

            foreach($list as $k => $v) {
                // 有效期/剩余天数
                if($v["is_use"] == 1 && $v["duetime"]>time()) { // 正在使用,未过期
                    $dtime = "剩余".ceil(($v["duetime"]-time())/86400)."天";
                }
                if($v["is_use"] == 0) {
                    $dtime = "有效期".$v["limit_day"]."天";
                }
                $list[$k]["dtime"] = $dtime;
            }
            $this->success("获取成功!",$list);
        } catch (Exception $e) {echo '<pre>';var_dump($e->getMessage());exit;
            $this->error($e->getMessage());
        }
    }
    /**
     * 使用并装上装饰
     */
    public function toUseAttire() {
        $id = $this->request->request("id"); //背包中商品ID
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        // 获取装饰信息
        $where = [];
        $where["id"] = $id;
        $attirebackInfo = $this->attirebackModel->where($where)->find();
        $data = [];
        $data["is_use"] = 1;
        $data["is_using"] = 1;
        $data["duetime"] = time()+$attirebackInfo["limit_day"]*86400;
        $res = $this->attirebackModel->update($data,$where);
        if($res) {
            $this->success("设置成功!");
        } else {
            $this->success("网络错误,请稍后重试!");
        }
    }

    /**
     * 装上
     */
    public function toUsingAttire() {
        $id = $this->request->request("id"); //背包中商品ID
        $use_type = $this->request->request("use_type",1); //使用方式:1=装上,2=卸下
        if (!$id || !in_array($use_type,[1,2])) {
            $this->error(__('Invalid parameters'));
        }
        // 获取装饰信息
        $where = [];
        $where["id"] = $id;
        $attirebackInfo = $this->attirebackModel->where($where)->find();
        if($use_type == 2) {
            $attirebackInfo->is_using = 0;
            $attirebackInfo->save();
            $this->success("设置成功!");
        }
        if($attirebackInfo["is_use"] != 1) {
            $data = [];
            $data["is_use"] = 1;
            $data["is_using"] = 1;
            $data["duetime"] = time()+$attirebackInfo["limit_day"]*86400;
            $res = $this->attirebackModel->update($data,$where);
            if(!$res) $this->error("使用失败!");
        }
        Db::startTrans();
        try{
            // 先取消掉所有的
            $res1 = $this->attirebackModel->update(["is_using"=>0],["user_id"=>$this->auth->id,"type"=>$attirebackInfo["type"]]);
            // 再设置当前
            $res2 = $this->attirebackModel->update(["is_using"=>1],["id"=>$id]);
            if($res1 && $res2) {
                Db::commit();
                $this->success("设置成功!");
            } else {
                $this->success("网络错误,请稍后重试!");
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

}