<?php
/**
 * 卡组相关
 */
defined('IN_WEB') or die('Include Error!');

class Card{
    public function getPro($param){
        $tb = otable::cardPro_Config();
        $sql = "SELECT * from {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[$v['type']] = json_decode($v['star_pro']);
        }

        return json_encode([
            'code'=>1,
            'data'=>$arr,
        ]);
    }

    public function actionPro($param){
        $data = json_decode($param['data']);
        $tb = otable::cardPro_Config();
        foreach ($data as $row){
            $temp = json_encode($row->data);
            $sql = "UPDATE {$tb} SET star_pro='{$temp}' WHERE type={$row->type}";
            $rs = oo::commonOprDb('common')->query($sql);
//            oo::commonOprCache('memcache')->delete(okeys::CardTypePro($row->type));
            oo::commonOprRedis('config')->delete(okeys::CardTypePro($row->type));
            oo::commonOprRedis('config')->delete(okeys::CardTypeProAll());
        }
        return $rs ? $rs : 0;
    }


    public function getReward($param){
        $tb = otable::cardreward_config();
        $sql = "SELECT * from {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[$v['cgid']] = [
              'coin_reward'=>$v['coin_reward'],
              'spin_reward'=>$v['spin_reward'],
            ];
        }

        return json_encode([
            'code'=>1,
            'data'=>$arr,
        ]);
    }

    public function actionReward($param){
        $data = json_decode($param['data']);
        $tb = otable::cardreward_config();
        foreach ($data as $row){
            $sql = "UPDATE {$tb} SET coin_reward='{$row->data->coin_reward}' , spin_reward='{$row->data->spin_reward}' WHERE cgid={$row->cgid}";
            $rs = oo::commonOprDb('common')->query($sql);
        }
        return $rs ? $rs : 0;
    }
  
  	public function getProcess($param){
        $tb = otable::cardgroupreward_config();
        $sql = "SELECT * from {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[$v['progress']] = [
                'coin_reward'=>$v['coin_reward'],
                'spin_reward'=>$v['spin_reward'],
            ];
        }

        return json_encode([
            'code'=>1,
            'data'=>$arr,
        ]);
    }
  
    public function actionProcess($param){
        $data = json_decode($param['data']);
        $tb = otable::cardgroupreward_config();
        $sql = "DELETE FROM {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->query($sql);
        foreach ($data as $row){
            $sql = "INSERT INTO {$tb} (levelId, progress, coin_reward , spin_reward) VALUES (1, {$row->process}, {$row->data->coin_reward} , {$row->data->spin_reward})";
            $rs = oo::commonOprDb('common')->query($sql);
        }
//        oo::commonOprCache('memcache')->delete(okeys::CardGroupProgressConfig());
        oo::commonOprRedis('config')->delete(okeys::CardGroupProgressConfig());
        return $rs ? $rs : 0;
    }

    public function getGroup($param)
    {
        $type = $param['type'];
        $tb = otable::cardgroup_config();
        $sql = "SELECT * from {$tb} WHERE cg_type={$type}";
        $rs = oo::commonOprDb('common')->getAll($sql, 1);
        return json_encode([
            'code' => 1,
            'data' => $rs,
        ]);
    }

    public function getGroupAll()
    {
        $tb = otable::cardgroup_config();
        $sql = "SELECT * from {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->getAll($sql, 1);
        return json_encode([
            'code' => 1,
            'data' => $rs,
        ]);
    }
	
  	public function actionGroup($param){
        if(!empty($param['uniqidKey'])){
            $param  = oo::commonOprRedis('statistics')->hGetAll($param['uniqidKey']);
            oo::commonOprRedis('statistics')->delete($param['uniqidKey']);
        }
        $data = json_decode($param['data']);
        $tb = otable::cardgroup_config();
        $sql = "SELECT `cgid` from {$tb} WHERE 1";
        $ret = oo::commonOprDb('common')->getAll($sql,1);
        $cgids = array_column($ret, 'cgid');

        foreach ($data as $row) {
            if (in_array($row->cgid, $cgids)) {
                $sql = funs::db_updateSQL($tb, $row->data, "cgid={$row->cgid}");
            } else {
                $sql=funs::db_insertSQL($tb,$row->data);
            }
            $rs = oo::commonOprDb('common')->query($sql);
        }
        oo::commonOprRedis('config')->delete(okeys::CardGroupConfig());
        return $rs ? $rs : 0;
    }

  	public function getExclusiveGroup($param){
        $tb = otable::specialCardgroup_config();
        $sql = "SELECT * from {$tb} WHERE 1";
        $rs = oo::commonOprDb('common')->getAll($sql,1);
        return json_encode([
            'code'=>1,
            'data'=>$rs,
        ]);
    }

    public function actionExclusiveGroup($param){
        $data = json_decode($param['data'],true);
        $tb = otable::specialCardgroup_config();
        foreach ($data as $row){
            $temp = $row['data'];
            $set = '';
            foreach ($temp as $key=>$value){
                $set .= "$key='{$value}',";
            }
            $set = trim($set,",");
            $sql = "UPDATE {$tb} SET {$set} WHERE cgid={$row['cgid']}";
            $rs = oo::commonOprDb('common')->query($sql);
        }
//        oo::commonOprCache('memcache')->delete(okeys::SpecialCardGroupConfig());
        oo::commonOprRedis('config')->delete(okeys::SpecialCardGroupConfig());

        return $rs ? $rs : 0;
    }


    public function getCard($param)
    {
        $cgid = $param['cgid'];
        $tb = otable::cardinfo_config();
        $tb2 = otable::cardreward_config2();
        if ($cgid == 9999) {
            $sql = "SELECT t.*, t2.reward from {$tb} t Left Join {$tb2} t2 On t2.ctype=2 and t.ciid = t2.c_cg_id";
        } else {
            $sql = "SELECT t.*, t2.reward from {$tb} t Left Join {$tb2} t2 On t2.ctype=2 and t.ciid = t2.c_cg_id WHERE  t.cgid={$cgid}";
        }
        $rs = oo::commonOprDb('common')->getAll($sql, 1);
        return json_encode([
            'code' => 1,
            'data' => $rs,
        ]);
    }
  
  	public function actionCard($param){
        $cgid = $param['cgid'];
        if(!empty($param['uniqidKey'])){
            $param  = oo::commonOprRedis('statistics')->hGetAll($param['uniqidKey']);
            oo::commonOprRedis('statistics')->delete($param['uniqidKey']);
        }
        oo::commonOprRedis('statistics')->delete($param['uniqidKey']);
        $data = json_decode($param['data']);
        $tb = otable::cardinfo_config();

        $sql = "SELECT `ciid` FROM {$tb} WHERE cgid={$cgid}";
        $ret = oo::commonOprDb('common')->getAll($sql,MYSQLI_ASSOC);
        $ciids = array_column($ret, 'ciid');
        foreach (array_column($data, 'ciid') as $ciid) {
            if (!in_array($ciid, $ciids)) {
                return json_encode(['ret' => 1, 'msg' => "导入表中的卡片ID不存在此卡组中，ID：{$ciid}"]);
            }
        }

        foreach ((array)$data as $row){
            $ci_name    = str_replace("'", "\'", $row->data->ci_name);
            $ci_name_fr = str_replace("'", "\'", $row->data->ci_name_fr);
            $ci_name_de = str_replace("'", "\'", $row->data->ci_name_de);
            $ci_name_es = str_replace("'", "\'", $row->data->ci_name_es);
            $ci_name_pt = str_replace("'", "\'", $row->data->ci_name_pt);
            $ci_name_tw = str_replace("'", "\'", $row->data->ci_name_tw);
            $ci_name_zh = str_replace("'", "\'", $row->data->ci_name_zh);
            $ci_name_th = str_replace("'", "\'", $row->data->ci_name_th);
            $ci_name_vn = str_replace("'", "\'", $row->data->ci_name_vn);
            $ci_name_no = str_replace("'", "\'", $row->data->ci_name_no);
            $ci_name_id = str_replace("'", "\'", $row->data->ci_name_id);
            $ci_name_rou = str_replace("'", "\'", $row->data->ci_name_rou);
            $ci_name_my = str_replace("'", "\'", $row->data->ci_name_my);
            $ci_name_it = str_replace("'", "\'", $row->data->ci_name_it);

            $sql = "UPDATE {$tb} SET ci_name='{$ci_name}',ci_name_fr='{$ci_name_fr}',ci_name_de='{$ci_name_de}',ci_name_es='{$ci_name_es}',ci_name_pt='{$ci_name_pt}',ci_name_th='{$ci_name_th}',ci_name_tw='{$ci_name_tw}',ci_name_zh='{$ci_name_zh}',ci_name_vn='{$ci_name_vn}',ci_name_no='{$ci_name_no}',ci_name_id='{$ci_name_id}',ci_name_rou='{$ci_name_rou}',ci_name_my='{$ci_name_my}',ci_name_it='{$ci_name_it}',cgposition='{$row->data->cgposition}',ci_star_rank='{$row->data->ci_star_rank}',ci_lockRank='{$row->data->ci_lockRank}',ci_picture='{$row->data->ci_picture}',grade='{$row->data->grade}',weights='{$row->data->weights}' WHERE ciid={$row->ciid}";
            $rs = oo::commonOprDb('common')->query($sql);
            if (!$rs) {
                return json_encode(['ret' => 1, 'msg' => "数据更新失败，ID：{{$row->ciid}}"]);
            }
        }

        $this->updateCardCache();
        return json_encode(['ret' => 0, 'msg' => '']);
    }

    private function updateCardCache()
    {
        $tb = otable::cardinfo_config();
        $sql = "SELECT * FROM {$tb}";
        $ret = oo::commonOprDb('config')->getAll($sql, 1);
        if (!empty($ret)) {
            $cacheKey = okeys::CardConfig();
            oo::commonOprRedis('config')->delete($cacheKey);
            foreach ($ret as $k => $v) {
                $arr[$v['ciid']] = $v;
                $cache[$v['ciid']] = json_encode($v);
            }
            oo::commonOprRedis('config')->hMset($cacheKey, $cache);
        }
    }
  	
  	public function getExclusiveCard($param){
        if(!isset($param['cgid'])){
            return 0;
        }
        $cgid=$param['cgid'];

        $tb = otable::specialCardInfoConfig();
        $sql = "SELECT * from {$tb} WHERE cgid={$cgid}";
        $rs = oo::commonOprDb('common')->getAll($sql,1);
        return json_encode([
            'code'=>1,
            'data'=>$rs,
        ]);
    }
  
  	public function actionExclusiveCard($param){
        $data = json_decode($param['data']);
        $tb = otable::specialCardInfoConfig();
        foreach ($data as $row){
            $ci_name    = str_replace("'", "\'", $row->data->ci_name);
            $ci_name_fr = str_replace("'", "\'", $row->data->ci_name_fr);
            $ci_name_de = str_replace("'", "\'", $row->data->ci_name_de);
            $ci_name_es = str_replace("'", "\'", $row->data->ci_name_es);
            $ci_name_pt = str_replace("'", "\'", $row->data->ci_name_pt);
            $ci_name_tw = str_replace("'", "\'", $row->data->ci_name_tw);
            $ci_name_zh = str_replace("'", "\'", $row->data->ci_name_zh);
            $ci_name_th = str_replace("'", "\'", $row->data->ci_name_th);
            $ci_name_vn = str_replace("'", "\'", $row->data->ci_name_vn);
            $ci_name_no = str_replace("'", "\'", $row->data->ci_name_no);
            $ci_name_id = str_replace("'", "\'", $row->data->ci_name_id);
            $ci_name_rou = str_replace("'", "\'", $row->data->ci_name_rou);
            $ci_name_my = str_replace("'", "\'", $row->data->ci_name_my);
            $ci_name_it = str_replace("'", "\'", $row->data->ci_name_it);
            $sql = "UPDATE {$tb} SET ci_name='{$ci_name}',ci_name_fr='{$ci_name_fr}',ci_name_de='{$ci_name_de}',ci_name_es='{$ci_name_es}',ci_name_pt='{$ci_name_pt}',ci_name_th='{$ci_name_th}',ci_name_tw='{$ci_name_tw}',ci_name_zh='{$ci_name_zh}',ci_name_vn='{$ci_name_vn}',ci_name_no='{$ci_name_no}',ci_name_id='{$ci_name_id}',ci_name_rou='{$ci_name_rou}',ci_name_my='{$ci_name_my}',ci_name_it='{$ci_name_it}',cgid='{$row->data->cgid}',cgposition='{$row->data->cgposition}',ci_star_rank='{$row->data->ci_star_rank}',ci_lockRank='{$row->data->ci_lockRank}' WHERE ciid={$row->ciid}";
            $rs = oo::commonOprDb('common')->query($sql);
        }
//        oo::commonOprCache('memcache')->delete(okeys::SpecialCardConfig());
        oo::commonOprRedis('config')->delete(okeys::SpecialCardConfig());
        return $rs ? $rs : 0;
    }
  
  	public function saveCardPic($param){
        $ciid = $param['ciid'];
        $picture = $param['picture'];
        $tb = otable::cardinfo_config();
        $sql = "UPDATE {$tb} SET ci_picture='{$picture}' WHERE ciid={$ciid}";
        $rs = oo::commonOprDb('common')->query($sql);
        return $rs ? $rs : 0;
    }

    public function makeCardJson($param)
    {
        $incrementIds = json_decode($param['incrementIds'], true);

        $groupCard = [];
        $cardInfoTable = [];
        $basicGroup = [];
        $exclusiveGroup = [];
        $incrementGroup = [];
        $incrementCard = [];

        $ret = json_decode($this->getCard(["cgid" => 9999]), true)['data'] ?? [];
        foreach ($ret as $row) {
            $temp = [
                'name' =>
                    [
                        $row['ci_name_zh']
                        , $row['ci_name']
                        , $row['ci_name_tw']
                        , $row['ci_name_fr']
                        , $row['ci_name_de']
                        , $row['ci_name_es']
                        , $row['ci_name_pt']
                        , $row['ci_name_th']
                        , $row['ci_name_id']
                        , $row['ci_name_vn']
                        , $row['ci_name_no']
                        , $row['ci_name_rou']
                        , $row['ci_name_my']
                        , $row['ci_name_it']
                        , $row['ci_name_pl']
                    ],
                'star' => $row['ci_star_rank'],
                'level' => $row['ci_lockRank'],
                'id' => $row['ciid'],
                'group' => $row['cgid'],
                'index' => $row['cgposition'],
                'image' => $row['ci_picture'],
                'grade' => max($row['grade'], 1),
                'reward' => json_decode($row['reward'] ?? '[]', true),
            ];
            if ($temp['reward']) {
                $showPrize = [];
                foreach ($temp['reward'] as $item) {
                    $showPrize[] = [
                        "propsId" => $item['propsId'],
                        "num" => $item['num'],
                        "jokerCardExpireTime" => 0,
                        "cards" => null,
                        "chestProps" => null,
                        "skinResourceId" => $item["skin"],
                        "skin" => $item["skin"],
                    ];
                }
                $temp['reward'] = $showPrize;
            }

            $cardInfoTable[$row['ciid']] = $temp;
            $groupCard[$row['cgid']][] = $row['ciid'];

            if (in_array($row['cgid'], $incrementIds)) {
                $incrementCard[$row['ciid']] = $temp;
            }
        }

        $tb = otable::cardgroup_limit_theme_config();
        $ret = oo::commonOprDb('common')->getAll("SELECT `id`,`cgids` from {$tb} WHERE 1", 1);

        $themeMap = [];
        foreach ($ret as $row) {
            $themeMap[$row['id']] = json_decode($row['cgids'], true);
        }

        $tb = otable::cardgroup_config();
        $ret = oo::commonOprDb('common')->getAll("SELECT * from {$tb} WHERE 1", 1);
        foreach ($ret as $row) {
            $oneGroupInfo = [
                'name' => [
                    $row['cg_name_zh']
                    , $row['cg_name']
                    , $row['cg_name_tw']
                    , $row['cg_name_fr']
                    , $row['cg_name_de']
                    , $row['cg_name_es']
                    , $row['cg_name_pt']
                    , $row['cg_name_th']
                    , $row['cg_name_id']
                    , $row['cg_name_vn']
                    , $row['cg_name_no']
                    , $row['cg_name_rou']
                    , $row['cg_name_my']
                    , $row['cg_name_it']
                    , $row['cg_name_pl']
                ],
                'reward' => ['spins' => $row['cg_spin_reward'], 'coin' => $row['cg_coin_reward'], 'coins' => $row['cg_coin_reward'], 'petFeed' => $row['cg_petFeed_reward'], 'petExp' => $row['cg_petExp_reward']],
                'level' => $row['cg_lock_rank'],
                'id' => $row['cgid'],
                'type' => $row['cg_type'],
                'group' => $row['cgid'],
                'list' => $groupCard[$row['cgid']],
                "titleImgId" => $row['cg_title_img_id'],
                "theme_id" => self::matchThemeId($row['cgid'], $themeMap),
            ];

            $basicGroup[] = $oneGroupInfo;
            if (in_array($oneGroupInfo['id'], $incrementIds)) {
                $incrementGroup[] = $oneGroupInfo;
            }
        }

        $tb = otable::specialCardgroup_config();
        $ret = oo::commonOprDb('common')->getAll("SELECT * from {$tb} WHERE 1", 1);
        foreach ($ret as $row) {
            $exclusiveGroup[] = [
                'name' => [
                    $row['cg_name_zh']
                    , $row['cg_name']
                    , $row['cg_name_tw']
                    , $row['cg_name_fr']
                    , $row['cg_name_de']
                    , $row['cg_name_es']
                    , $row['cg_name_pt']
                    , $row['cg_name_th']
                    , $row['cg_name_id']
                    , $row['cg_name_vn']
                    , $row['cg_name_no']
                    , $row['cg_name_rou']
                    , $row['cg_name_my']
                    , $row['cg_name_it']
                ],
                'reward' => ['spins' => $row['cg_spin_reward'], 'coin' => $row['cg_coin_reward'], 'coins' => $row['cg_coin_reward'], 'petFeed' => $row['cg_petFeed_reward'], 'petExp' => $row['cg_petExp_reward']],
                'level' => $row['cg_lock_rank'],
                'id' => $row['cgid'] + 100000,
                'group' => $row['cgid'],
                'list' => $groupCard[$row['cgid'] + 100000],
                "titleImgId" => $row['cg_title_img_id']
            ];
        }

        $tb = otable::cardgroupreward_config();
        $ret = oo::commonOprDb('common')->getAll("SELECT * from {$tb} WHERE 1", 1);
        $cardGroupTaskBasic = [];
        foreach ($ret as $key => $row) {
            $cardGroupTaskBasic[] = [
                'id' => $key + 1,
                'target' => $row['progress'],
                'reward' => [
                    'spins' => $row['spin_reward'],
                    'coin' => $row['coin_reward'],
                    'coins' => $row['coin_reward']
                ]
            ];
        }

        return json_encode(['code' => 1, 'data' => [
            'cardGroupTable' => [
                'basic' => $basicGroup,
                'exclusive' => $exclusiveGroup,
            ],
            'cardInfoTable' => $cardInfoTable,
            'cardGroupTask' => [
                'basic' => $cardGroupTaskBasic,
                'exclusive' => []
            ],
            'incrementData' => [
                'cardGroupInfo'=>$incrementGroup,
                'cardInfo'=>$incrementCard,
            ],
        ]], JSON_NUMERIC_CHECK);
    }

    public function pushIncrementCardJson($params)
    {
        if (empty($params['filename'])) {
            return;
        }

        $data = [
            "cmd" => 16409,
            "uid" => 0,
            "data" => [
                "action" => "add",
                "cardJsonFile" => $params['filename']
            ],
        ];

        funs::SendNsqMsg(ocmd::TopicCardPushAll, [], $data);
    }

    // 卡组ID匹配主题ID
    public function matchThemeId($cgid, $themeMap): int
    {
        foreach ($themeMap as $themeId => $cgids) {
            if (in_array($cgid, $cgids)) {
                return $themeId;
            }
        }
        return 0;
    }

    /**
     * 修改用户卡片
     * @param $param
     * @return int
     * Created by: Owen
     * Created on: 2021/1/5 16:15
     */
    public function actionAddUserCard($param){
        $uid     = $param['uid'];
        $cardArr = json_decode($param['card'],true);
        $userCardInfo = oo::commonOprModel('card')->getUserCardInfo($uid);
        $userCardData = $userCardInfo['ciid'];
        $userCardType = array_keys($userCardData);
        $actionStar   = 0;
        foreach ($cardArr as $ciid=>$num){
            if($num > 0){
                if(!in_array($ciid,$userCardType)){
                    $cardInfo = oo::commonOprModel('card')->getCardInfoByCiid($ciid);
                    $actionStar += intval($cardInfo['ci_star_rank']);
                }
                $userCardData[$ciid] += intval($num);
            }else{
                if(in_array($ciid,$userCardType)){
                    $userCardData[$ciid] = max(0,intval($userCardData[$ciid]) - abs($num));
                    if($userCardData[$ciid] == 0){
                        unset($userCardData[$ciid]);
                        $cardInfo = oo::commonOprModel('card')->getCardInfoByCiid($ciid);
                        $actionStar -= intval($cardInfo['ci_star_rank']);
                    }
                }
            }
        }
        if($actionStar != 0){
            oo::commonOprModel('member')->optProperty($uid,['star'=>abs($actionStar)],$actionStar > 0 ? "+" : "-",32,'后台修改卡片:'.$param['card']);
        }
        return oo::commonOprModel('card')->updateUserCardInfo($uid,[ 'ciid' => $userCardData ]) ? 1 : 0;
    }
}
