<?php

namespace Agent\Lib;

use Dever;

# 批量设置商品
class Reward_set
{
	public function __construct()
    {
        Dever::load('manage/auth.init');
    }

    # 获取商品列表
    public function goods_api()
    {
        $id = Dever::input('reward_give_id', 1);
        return Dever::load('agent/lib/set')->getData($id);
    }

    # 设置商品
    public function home_api()
    {
        $data = array();
        $data['link'] = Dever::decode(Dever::input('refer'));
        $data['reward_give_id'] = Dever::input('id', 1);
        Dever::setInput('reward_give_id', $data['reward_give_id']);
        $data['host'] = Dever::url('lib/reward_set.home?id=' . $data['reward_give_id'], 'agent');
        $data['url'] = Dever::url('lib/reward_set.goods?reward_give_id=' . $data['reward_give_id'], 'agent');
        $data['submit'] = Dever::url('lib/reward_set.action_commit?json=1', 'agent');

        return Dever::render('setRewardGoods', $data);
    }

    # 设置
    public function action_commit_api()
    {
        $goods = Dever::input('goods');
        if (!$goods) {
            Dever::alert('请传入商品');
        }
        $goods = Dever::json_decode($goods);
        $reward_give_id = Dever::input('reward_give_id');

        $where['option_reward_give_id'] = $reward_give_id;
        $where['set_state'] = 2;
        Dever::db('setting/role_reward_goods')->updates($where);

        foreach ($goods as $k => $v) {
            $type = 1;
            $type_id = $k;
            $sku_id = -1;
            if (strstr($k, '_')) {
                $temp = explode('_', $k);
                $type_id = $temp[0];
                $type = $temp[1];
            } elseif (strstr($k, '-')) {
                $temp = explode('-', $k);
                $type_id = $temp[0];
                $sku_id = $temp[1];
            }
            
            if ($v['total'] <= 0) {
            	continue;
            }
            $w = array();
            $w['type'] = $type;
            $w['type_id'] = $type_id;
            $w['reward_give_id'] = $reward_give_id;
            $w['sku_id'] = $sku_id;
            $info = Dever::db('setting/role_reward_goods')->one($w);
            if ($v['del'] == 2) {
                if ($info) {
                    Dever::db('setting/role_reward_goods')->update(array('where_id' => $info['id'], 'state' => 2));
                }
            } else {
            	$w['num'] = $v['total'];
                
                if (!$info) {
                    Dever::db('setting/role_reward_goods')->insert($w);
                } else {
                    $w['where_id'] = $info['id'];
                    $w['state'] = 1;
                    Dever::db('setting/role_reward_goods')->update($w);
                }
            }
        }

        return 'reload';
    }
}