<?php

class StarExchangeModel extends CI_Model
{
    private $configTable;
    private $propsConfig;

    public function __construct()
    {
        parent::__construct();
        $this->configTable = otable::StarExchangeV2();
        $this->propsConfig = oo::commonOprModel('config')->getPropsConfigFromLocal('func');
    }

    /**
     * 获取配置列表
     * @return array
     */
    public function configList(): array
    {
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$this->configTable}");

        $data = [];
        $starList = [];
        $superStarList = [];
        foreach ($ret as $key => $row) {
            $row['prize_json'] = json_decode($row['prize_json'], true);
            $row['skin'] = $row['prize_json'][0]['skin'] ?? 0;
            $row['clear_refresh'] = json_decode($row['clear_refresh'], true);

            if ($row['type'] == 1) {
                //星星兑换宝箱
                $starList[] = $row;

            } elseif ($row['type'] == 2) {
                //超级星星兑换宝箱
                $superStarList[] = $row;
            }
        }

        //皮肤宝箱列表
        $skinList = [];
        foreach ($this->propsConfig as $oneProp) {
            if ($oneProp['id'] == 19) {
                $skinList = $oneProp['skinList'];
            }
        }

        $data['starList'] = $starList;
        $data['superStarList'] = $superStarList;
        $data['skinList'] = $skinList;

        return $data;
    }

    /**
     * 更新配置信息
     */
    public function updateConfig(array $data)
    {
        foreach ($data as $id => $row) {
            $row['clear_refresh'] = json_encode($row['clear_refresh'], JSON_NUMERIC_CHECK);
            $row['prize_json'] = json_encode([["propsId" => 19, "num" => 1, "rtype" => 1, "skin" => $row['skin']]], JSON_NUMERIC_CHECK);
            unset($row['id'], $row['skin']);
            $set = "";
            foreach ($row as $key => $value) {
                $set .= "`{$key}`='{$value}',";
            }
            $set = trim($set, ',');
            $sql = "UPDATE {$this->configTable} SET {$set} WHERE id={$id}";
            oo::commonOprDb('games')->query($sql);
        }

        oo::commonOprRedis('games')->delete(okeys::StarExchangeConfigV2());
    }

}