<?php

namespace Tag\Lib;

use Dever;

class Core
{
    # 更新数据
    public function data($id, $name, $data)
    {
        $source_table = Dever::input('source_table');

        $tag = Dever::param('tag', $data);

        if ($tag && $id > 0 && $source_table) {
            $tag = explode(',', $tag);
            foreach ($tag as $k => $v) {
                if (!$v || $v == 'null') {
                    unset($tag[$k]);
                    continue;
                }
                $info = Dever::db('tag/info')->one($v);
                if (!$info) {
                    if ($v) {
                        $insert['name'] = $v;
                        $tag_id = Dever::db('tag/info')->insert($insert);
                        $tag[$k] = $tag_id;
                    } else {
                        unset($tag[$k]);
                        continue;
                    }
                } else {
                    $tag_id = $v;
                }

                if ($tag_id > 0) {
                     $tag_data = array
                     (
                         'tag_id' => $tag_id,
                         'source_table' => $source_table,
                         'source_id' => $id,
                     );
                    $data_info = Dever::db('tag/data')->one($tag_data);

                    if (!$data_info) {
                        Dever::db('tag/data')->insert($tag_data);
                    }
                }
            }

            $tag = implode(',', $tag);
            Dever::db($source_table)->update(array('where_id' => $id, 'tag' => $tag));
        }

        Dever::load('content/lib/author')->data($id, $name, $data);
    }

    # 搜索
    public function search_api()
    {
        $keyword = Dever::input('keyword');

        $yes = Dever::input('yes');

        $where = array();

        if ($yes) {
            $yes = Dever::db('tag/info')->getAll(array('ids' => $yes));
        }
        if (!$keyword) {
            $where['limit'] = '0,50';
            $data = Dever::db('tag/info')->getAll($where);
        } else {
            $where['name'] = $keyword;
            $data = Dever::db('tag/info')->getAll($where);
        }

        $insert = array();
        if (!$data && $keyword) {
            $insert[0]['name'] = $keyword . '[新增]';
            $insert[0]['value'] = $keyword;
        }

        $result = array();
        if ($yes) {
            foreach ($yes as $k => $v) {
                if (isset($data[$k])) {
                    unset($data[$k]);
                }
                $yes[$k]['selected'] = 'selected';
            }
            $data = $insert + $yes + $data;

            $data = array_merge($data, array());
        } else {
            $data = $insert + $data;

            $data = array_merge($data, array());
        }

        if (!$data) {
            Dever::alert('暂无数据');
        }

        return $data;
    }
}