<?php namespace Manage\Api\Page;
use Dever;
use Manage\Lib\Page;
# 数据获取
class Data extends Page
{
    private $recycler = false;
    private $selection = false;
    private $expand = false;
    public function __construct($load = '')
    {
        parent::__construct('list', $load);
    }
    public function list()
    {
        if (!$this->getFunc('list', '列表', 1)) {
            Dever::error('无访问权限');
        }
        $data['title'] = '';
        $data['button'] = $this->button();
        $data['recycler'] = $this->recycler;
        $data = array_merge($data, $this->out());
        $data['total'] = Dever::page('total');
        $data['height'] = $this->config['height'] ?? '100%';
        $data['type'] = $this->config['type'] ?? 'table';
        $data['desc'] = $this->config['desc'] ?? '';
        $data['layout'] = $this->config['layout'] ?? array();
        $data['exportButton'] = $this->export();
        $data['show'] = array
        (
            'selection' => $this->selection,
            'expand' => $this->expand,
            'index' => $this->config['index'] ?? false,
        );
        $this->column($data);
        return $data;
    }
    public function out()
    {
        $where = $this->config['where'] ?? array();
        $set = $this->config['set'] ?? array();
        $data['field'] = $data['head'] = array();
        $data['search'] = $this->search($where);
        if (isset($this->config['data'])) {
            $result = Dever::call($this->config['data'], array($where, $set));
            $data = array_merge($data, $result);
        } else {
            $data['field'] = $this->setting('field', $data['head'], true, 'show');
            $data['body'] = $this->data($where, $set);
        }
        $method = Dever::input('method');
        if ($method && strstr($method, '.')) {
            $result = Dever::call($method, array($data));
            unset($data);
            $data['field'] = $result['head'];
            $data['body'] = $result['body'];
        }
        $data['stat'] = array();
        if (isset($this->config['stat'])) {
            $data['stat'] = Dever::call($this->config['stat'], array($where));
        }
        return $data;
    }

    private function data($where, $set = array())
    {
        $set['num'] = Dever::input('pgnum', '', '', 10);
        $order_col = Dever::input('order_col');
        if ($order_col) {
            $order_value = Dever::input('order_value');
            if ($order_value) {
                $set['order'] = $order_col . ' ' . $order_value . ', id desc';
            }
        }
        if (isset($this->config['tree'])) {
            return $this->db->tree($where, $this->config['tree'], array($this, 'handleData'));
        }
        $data = $this->db->select($where, $set);
        $result = array();
        if ($data) {
            foreach ($data as $k => $v) {
                $result[$k] = $this->handleData($k, $v);
            }
        }
        return $result;
    }

    public function handleData($k, $v)
    {
        $button = $this->button('data_button', $v);
        if ($button) {
            $result['button'] = $button;
        }
        # 是否保留html代码,1是保留,2是不保留
        $html = Dever::input('html', '', '', 1);
        if (isset($v['id'])) {
            $result['id'] = $v['id'];
        }
        $result['cdate'] = $v['cdate'];
        foreach ($this->field as $value) {
            $key = $value['key'];
            if (isset($v[$key])) {
                $result[$key] = $this->getValue($key, $v[$key], $v, $value);
            } elseif (strpos($key, '/')) {
                $other = $this->getOther($key, $value['where'], $v);
                if ($other) {
                    $otherName = array();
                    foreach ($other as $k1 => $v1) {
                        if (isset($v1['name'])) {
                            $otherName[] = $v1['name'];
                        }
                    }
                    if ($otherName) {
                        $result[$key] = implode('、', $otherName);
                    } else {
                        $result[$key] = $other;
                    }
                }
            }
            if ($html == 2) {
                $result[$key] = strip_tags($result[$key]);
            }
        }
        if (isset($this->config['expand']) && $this->config['expand']) {
            $result['expand'] = Dever::call($this->config['expand'], array($v));
            $this->expand = true;
        }
        return $result;
    }

    private function export()
    {
        $result = false;
        if (isset($this->config['export'])) {
            $result = array();
            foreach ($this->config['export'] as $k => $v) {
                $func = $this->getFunc($k, $v, 300);
                if ($func) {
                    $result[$k] = $v;
                }
            }
        }
        return $result;
    }

    private function search(&$where)
    {
        $search = Dever::input('search');
        $set = Dever::input('set');
        $list_search = $result = array();
        $result['form'] = $result['field'] = $result['option'] = array();
        $this->setting('search', $list_search, false, 'text');
        if ($list_search) {
            foreach ($list_search as $v) {
                if ($v['type'] != 'hidden') {
                    $result['form'][] = $v;
                    $result['field'][$v['key']] = $v['value'];
                    if ($v['type'] == 'sku') {
                        $result['field'][$v['key'] . '_spec'] = [];
                    }
                    if (isset($v['option'])) {
                        $result['option'][$v['key']] = $v['option'];
                    }
                }
                $this->where($search, $v, $where);
                $this->where($set, $v, $where);
            }
        }
        return $result;
    }

    private function where($value, $v, &$where)
    {
        if ($value) {
            if ($value = Dever::isset($value, $v['key'])) {
                if (isset($v['search'])) {
                    if (is_callable($v['search'])) {
                        $value = $v['search']($v['key'], $v['type'], $value);
                    } elseif (isset($v['search']['table'])) {
                        $v['search']['where'] = Dever::json_decode(str_replace('{value}', $value, Dever::json_encode($v['search']['where'])));
                        $search = Dever::db($v['search']['table'])->select($v['search']['where'], $v['search']['set'] ?? array());
                        $value = array();
                        if ($search) {
                            foreach ($search as $v1) {
                                $value[] = $v1[$v['search']['field']];
                            }
                        }
                        $value = implode(',', $value);
                        $v['type'] = 'in';
                    }
                }
                if ($v['type'] == 'group') {
                    $where[$v['key']] = array('group', $value);
                } elseif ($v['type'] == 'selects') {
                    $where[$v['key']] = array('group', $value);
                } elseif ($v['type'] == 'like') {
                    $where[$v['key']] = array('like', $value);
                } elseif ($v['type'] == 'in') {
                    $where[$v['key']] = array('in', $value);
                } elseif ($v['type'] == 'date') {
                    if (strstr($v['date_type'], 'range')) {
                        $where[$v['key']] = array('>=', \Dever\Helper\Date::mktime($value[0]));
                        $where[$v['key'] . '#'] = array('<=', \Dever\Helper\Date::mktime($value[1]));
                    } else {
                        $where[$v['key']] = $value;
                    }
                } else {
                    $where[$v['key']] = $value;
                }
            }
        }
    }

    private function button($key = 'button', $data = array())
    {
        $result = array();
        if (!isset($this->config[$key])) {
            $num = 0;
            if (isset($this->db->config['manage']['update']['field'])) {
                $num = count($this->db->config['manage']['update']['field']);
            } elseif (isset($this->db->config['struct']) && $this->db->config['struct']) {
                $num = count($this->db->config['struct']);
            }
            $fast = 'fast';
            if ($num > 8) {
                $fast = '';
            }
            if ($key == 'button') {
                $this->config[$key] = array('新增' => $fast . 'add');
            } else {
                $this->config[$key] = array('编辑' => $fast . 'edit', '删除' => 'recycle');
            }
        }
        $sort = 1;
        foreach ($this->config[$key] as $k => $v) {
            $d = '';
            $p = '';
            $i = '';
            if (is_array($v)) {
                if (isset($v[3]) && $data) {
                    $d = $v[3];
                    parse_str($d, $t);
                    $state = true;
                    foreach ($t as $k1 => $v1) {
                        if (!isset($data[$k1]) || (isset($data[$k1]) && $data[$k1] != $v1)) {
                            $state = false;
                        }
                    }
                    if (!$state) {
                        continue;
                    }
                }
                if (isset($v[2])) {
                    $i = $v[2];
                }
                if (isset($v[1])) {
                    $p = $v[1];
                }
                $v = $v[0];
            }
            if (strstr($v, 'add')) {
                $icon = 'Plus';
                $button = 'primary';
            } elseif (strstr($v, 'edit')) {
                $icon = 'Edit';
                $button = 'primary';
            } elseif (strstr($v, 'view')) {
                $icon = 'View';
                $button = '';
            } elseif ($v == 'delete') {
                if ($key == 'button') {
                    if (isset($this->config['layout'])) {
                        continue;
                    }
                    $this->selection = true;
                }
                $icon = 'Delete';
                $button = 'danger';
            } elseif ($v == 'recycle') {
                if ($key == 'button') {
                    if (isset($this->config['layout'])) {
                        continue;
                    }
                    $this->selection = true;
                }
                $icon = 'Delete';
                $button = 'danger';
            } elseif ($v == 'oper') {
                if ($key == 'button') {
                    if (isset($this->config['layout'])) {
                        continue;
                    }
                    $this->selection = true;
                }
                $icon = 'Notification';
                $button = 'warning';
            } elseif ($v == 'api') {
                if ($key == 'button') {
                    if (isset($this->config['layout'])) {
                        continue;
                    }
                    $this->selection = true;
                }
                $p = Dever::url($p);
                $icon = 'Notification';
                $button = 'warning';
            } elseif ($v == 'link') {
                $icon = 'Link';
                $button = 'success';
            } elseif ($v == 'route') {
                $icon = 'Link';
                $button = 'success';
            } elseif ($v == 'recover') {
                $icon = 'CirclePlus';
                $button = 'info';
            } else {
                continue;
            }
            # 权限验证
            $sort++;
            $func = $this->getFunc($v, $k, $sort, $p);
            if (!$func) {
                continue;
            }
            if ($i) {
                $icon = $i;
            }
            $result[] = array
            (
                'name' => $k,
                'type' => $v,
                'param' => $p,
                'icon' => $icon,
                'button' => $button,
                'func' => $func,
            );
            if (!$this->recycler && $v == 'recycle') {
                $this->recycler = true;
            }
        }
        return $result;
    }
}