<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * 活动皮肤配置
 */
class ActSkin extends MY_Controller
{
    /**
     * 活动皮肤额外配置
     */
    public function themeExtraConf()
    {
        $type = $this->input->post()['type'];
        $skin = $this->input->post()['skin'];

        $tb = otable::ActSkinExtraConfig();
        $sql = "select `key`,`val`,`msg` from {$tb} where `type`='{$type}' and `skin`='{$skin}'";
        $confList = oo::commonOprDb('slavedb')->getAll($sql);

        $data['type'] = $type;
        $data['skin'] = $skin;
        $data['list'] = [];

        if ($confList) {
            foreach ($confList as $item) {
                $data['list'][] = [
                    "key" => $item['key'],
                    "val" => $item['val'],
                    "msg" => $item['msg'],
                ];
            }
        }

        return $this->response(0, '操作成功', $data);
    }

    /**
     * 活动皮肤额外配置更新
     */
    public function themeExtraConfUpdate()
    {
        $data = $this->input->post();

        $type = $data['type'];
        $skin = $data['skin'];

        $tb = otable::ActSkinExtraConfig();
        $sql = "select `key` from {$tb} where `type`='{$type}' and `skin`='{$skin}'";
        $confList = oo::commonOprDb('slavedb')->getAll($sql);
        $existKeys = array_column($confList, 'key');

        $uniqKeys = [];
        $updateKeys = [];
        foreach ($data['extraConf'] as $item) {
            if (in_array($item['key'], $uniqKeys) || empty($item['key'])) {
                continue;
            }
            if (in_array($item['key'], $existKeys)) {
                // update
                $sql = funs::db_updateSQL($tb, $item, "`type`='{$type}' and `skin`='{$skin}' and `key`='{$item['key']}'");
                $updateKeys[] = $item['key'];
            } else {
                $item['type'] = $type;
                $item['skin'] = $skin;
                $sql = funs::db_insertSQL($tb, $item);
            }

            oo::commonOprDb('games')->query($sql);
        }

        $delKeys = array_diff($existKeys, $updateKeys);
        foreach ($delKeys as $delKey) {
            $sql = "delete from {$tb} where `type`='{$type}' and `skin`='{$skin}' and `key`='{$delKey}'";
            oo::commonOprDb('games')->query($sql);
        }

        $this->buildStaticJson();

        return $this->response(0, '操作成功');
    }

    private function buildStaticJson()
    {
        $tb = otable::ActSkinExtraConfig();
        $sql = "select * from {$tb} where true";
        $confList = oo::commonOprDb('slavedb')->getAll($sql);

        $json = [];
        foreach ($confList as $item) {
            $json[$item['type']][$item['skin']][$item['key']] = $item['val'];
        }

        $filename = 'ActSkinExtraConfig' . time() . '.json';

        oo::commonOprModel("json")->SaveJson($json, $filename);
        oo::commonOprModel("json")->setStaticConfig("ActSkinExtraConfig", $filename);
    }
}