<?php

namespace web\admin\rigger;

class cata {
    static function setwhere($db, $post) {
    }
    public static function json_init() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $ext = get('ext');
        $issub = (get('issub') == 'yes');
        $ismulti = (get('ismulti') == 'yes');
        $cbid = getint('cbid');
        if ($cbid == 0) {
            $code = get('code');
            $csql = new \ciy\sql('zc_cata');
            $csql->where('codeid', $code);
            $csql->where('cbid=0');
            $cbrow = $db->getone($csql);
            if (!is_array($cbrow))
                return errjson('代码库未找到code=' . $code);
            $cbid = $cbrow['id'];
            $cname = $cbrow['name'];
        } else {
            $csql = new \ciy\sql('zc_cata');
            $csql->where('id', $cbid);
            $csql->where('cbid=0');
            $cbrow = $db->getone($csql);
            if (!is_array($cbrow))
                return errjson('代码库未找到cbid=' . $cbid);
            $cname = $cbrow['name'];
            $code = $cbrow['codeid'];
        }
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid', $cbid);
        $csql->order('csort,id');
        $rows = $db->get($csql);
        $rows[] = array('id' => 0, 'name' => '', 'csort' => 10, 'isuse' => 1);
        $ret = array('list' => $rows);
        if ($post->getbool('field')) {
            $field = array();
            $fshow = '';
            $fshow = fieldadd($fshow, $field, -1, 'name', $cname);
            $fshow = fieldadd($fshow, $field, -1, 'codeid', '代码|');
            if (!empty($ext))
                $fshow = fieldadd($fshow, $field, -1, 'extdata', $ext);
            $fshow = fieldadd($fshow, $field, -1, 'isuse', '行为');
            $fshow = fieldadd($fshow, $field, -1, 'csort', '排序|');
            $fshow = fieldadd($fshow, $field, -1, 'clas', '样式');
            $fshow = fieldadd($fshow, $field, -1, '_btn', '操作');
            $field['clas']['thwidth'] = '7em';
            $field['codeid']['thwidth'] = '6em';
            $field['csort']['thwidth'] = '5em';
            $ret['field'] = $field;
        }
        if ($post->getbool('once')) {
            $ret['once'] = true;
            $input = array();
            $input[] = array(
                'type' => 'input',
                'form' => 'name',
                'name' => $cname,
                'prop' => ' style="width:8em;"'
            );
            $input[] = array(
                'type' => 'input',
                'form' => 'codeid',
                'name' => '代码',
                'prop' => ' style="width:8em;"'
            );
            if (!empty($ext)) {
                $input[] = array(
                    'type' => 'input',
                    'form' => 'extdata',
                    'name' => $ext,
                    'prop' => ' style="width:8em;"'
                );
            }
            $ret['searchinput'] = $input;
            $ret['cbid'] = $cbid;
            $ret['issub'] = $issub;
            $ret['ismulti'] = $ismulti;
            $ret['codename'] = $code;
        }
        return succjson($ret);
    }

    public static function json_update() {
        global $db;
        $rsuser = verifyfast();

        if (nopower($db, $rsuser['id'], 'p601pd'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $cbid = $post->getint('cbid');
        $codeid = $post->get('codeid');
        $name = $post->get('name');
        if ($name == '')
            return errjson('请填写名称');
        $upid = $post->getint('upid');
        $isuse = $post->getint('isuse');
        $csort = $post->getint('csort');
        $clas = $post->get('clas');
        $extdata = $post->get('extdata');
        $datarow = null;
        if ($id > 0) {
            $csql = new \ciy\sql('zc_cata');
            $csql->where('id', $id);
            $datarow = $db->getone($csql);
            if (!is_array($datarow))
                return errjson('数据不存在');
        }
        try {
            $db->begin();
            $csql = new \ciy\sql('zc_cata');
            $csql->where('cbid', $cbid)->where('codeid', $codeid);
            $csql->column('id');
            $chkid = toint($db->get1($csql));
            if ($chkid > 0 && (($id > 0 && $chkid != $id) || $id == 0))
                throw new \Exception('CIYIGN代码值重复');

            $updata = array();
            $updata['name'] = $name;
            $updata['codeid'] = $codeid;
            $updata['cbid'] = $cbid;
            $updata['upid'] = $upid;
            $updata['isuse'] = $isuse;
            $updata['csort'] = $csort;
            $updata['clas'] = $clas;
            $updata['extdata'] = $extdata;
            $csql = new \ciy\sql('zc_cata');
            if ($id > 0) {
                $csql->where('id', $id);
                if ($db->update($csql, $updata) === false)
                    throw new \Exception('更新失败:' . $db->error);
            } else {
                if ($db->insert($csql, $updata) === false)
                    throw new \Exception('更新失败:' . $db->error);
                $id = $db->insert_id();
            }
            $updata['id'] = $id;
            savelogdb($db, $rsuser['id'], 'zc_cata', $datarow, $updata);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $db->execute('update zc_online set usrchg=2');
        $ret['data'] = $updata;
        return succjson($ret);
    }

    public static function json_del() {
        global $db;
        $rsuser = verifyfast();
        if (nopower($db, $rsuser['id'], 'p601pd'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $ids = $post->get('ids');
        if (empty($ids))
            return errjson('请选择至少一条');
        $cbid = $post->getint('cbid');
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid=0');
        $csql->where('id', $cbid);
        $cbrow = $db->getone($csql);
        if (!is_array($cbrow))
            return errjson('代码库未找到cbid=' . $cbid);
        $exs = explode("\n", $cbrow['extdata']);
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid', $cbid);
        $csql->where('id in', $ids);
        $rows = $db->get($csql);
        $vids = array();
        try {
            $db->begin();
            foreach ($rows as $row) {
                $delid = $row['id'];
                $csql = new \ciy\sql('zc_cata');
                $csql->where('cbid', $row['cbid']);
                $csql->where('upid', $delid);
                $downcnt = toint($db->get1($csql));
                if ($downcnt > 0)
                    throw new \Exception('CIYIGN[' . $row['name'] . ']有' . $downcnt . '个子码，请先删除子码');
                foreach ($exs as $exn) {
                    if (empty($exn))
                        continue;
                    $tabf = explode(',', $exn);
                    if (count($tabf) == 1)
                        $tabf[1] = $cbrow['codeid'];
                    delcheck($db, $row['codeid'], $tabf[0], $tabf[1], $tabf[0] . '数据');
                }
                delme($db, $delid, 'zc_cata');
                savelogdb($db, $rsuser['id'], 'zc_cata', $row, null);
                $vids[] = $delid;
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $db->execute('update zc_online set usrchg=2');
        $ret['ids'] = $vids;
        return succjson($ret);
    }
    public static function json_multiadd() {
        global $db;
        $rsuser = verifyfast();

        if (nopower($db, $rsuser['id'], 'p601pd'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $format = $post->getint('multi_format');
        $cbid = $post->getint('cbid');
        $upid = $post->getint('upid');
        $code = $post->get('multi_code');
        if ($code == '')
            return errjson('请填写代码');
        $codes = explode("\n", str_replace('，', ',', $code));

        $cnt = 0;
        $deepids = array();
        $deepids[0] = $upid;
        $lastdeep = 0;
        try {
            $db->begin();
            if (count($codes) == 1 && strpos($code, ',') !== false && strpos($code, ':') !== false) {
                //订单状态,TINT,1:创建订单,10:支付成功,20:评价
                $codes = explode(',', $code);
                foreach ($codes as $c) {
                    $cs = explode(':', $c);
                    if (count($cs) < 2)
                        continue;
                    $codeid = $cs[0];
                    $name = $cs[1];
                    if (empty($name))
                        continue;
                    $deep = 0;
                    while (true) {
                        if (substr($name, 0, 2) != '--')
                            break;
                        $deep++;
                        $name = trim(substr($name, 2));
                    }
                    if (empty($name))
                        continue;
                    if ($lastdeep < $deep)
                        throw new \Exception('不能跳跃层级:' . $name);
                    $csql = new \ciy\sql('zc_cata');
                    $csql->where('cbid', $cbid)->where('codeid', $codeid);
                    $chkrow = $db->getone($csql);
                    $updata = array();
                    $updata['upid'] = $deepids[$deep];
                    $updata['name'] = $name;
                    $csql = new \ciy\sql('zc_cata');
                    if (is_array($chkrow)) {
                        $id = $chkrow['id'];
                        $csql->where('id', $id);
                        if ($db->update($csql, $updata) === false)
                            throw new \Exception('批量更新失败.' . $db->error);
                    } else {
                        $updata['isuse'] = 1;
                        $updata['cbid'] = $cbid;
                        $updata['codeid'] = $codeid;
                        $updata['csort'] = $codeid;
                        if ($db->insert($csql, $updata) === false)
                            throw new \Exception('批量新增失败.' . $db->error);
                        $id = $db->insert_id();
                    }
                    $updata['id'] = $id;
                    $deepids[$deep + 1] = $id;
                    $lastdeep = $deep + 1;
                    savelogdb($db, $rsuser['id'], 'zc_cata', $chkrow, $updata);
                    $cnt++;
                }
            } else {
                foreach ($codes as $c) {
                    $cs = explode(',', $c);
                    if (count($cs) < 2)
                        continue;
                    if ($format == 1) {
                        $name = $cs[0];
                        $codeid = $cs[1];
                    } else {
                        $name = $cs[1];
                        $codeid = $cs[0];
                    }
                    $deep = 0;
                    while (true) {
                        if (substr($name, 0, 2) != '--')
                            break;
                        $deep++;
                        $name = trim(substr($name, 2));
                    }
                    if (empty($name))
                        continue;
                    if ($lastdeep < $deep)
                        throw new \Exception('不能跳跃层级:' . $name);
                    $csql = new \ciy\sql('zc_cata');
                    $csql->where('cbid', $cbid)->where('codeid', $codeid);
                    $chkrow = $db->getone($csql);
                    $updata = array();
                    $updata['upid'] = $deepids[$deep];
                    $updata['name'] = $name;
                    $updata['extdata'] = @$cs[2] . '';
                    $csql = new \ciy\sql('zc_cata');
                    if (is_array($chkrow)) {
                        $id = $chkrow['id'];
                        $csql->where('id', $id);
                        if ($db->update($csql, $updata) === false)
                            throw new \Exception('批量更新失败.' . $db->error);
                    } else {
                        $updata['isuse'] = 1;
                        $updata['cbid'] = $cbid;
                        $updata['codeid'] = $codeid;
                        $updata['csort'] = $codeid;
                        if ($db->insert($csql, $updata) === false)
                            throw new \Exception('批量新增失败.' . $db->error);
                        $id = $db->insert_id();
                        $deepids[$deep + 1] = $id;
                        $lastdeep = $deep + 1;
                    }
                    $updata['id'] = $id;
                    savelogdb($db, $rsuser['id'], 'zc_cata', $chkrow, $updata);
                    $cnt++;
                }
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        if ($cnt > 0) {
            $db->execute('update zc_online set usrchg=2');
        }
        return succjson();
    }
}
