<?php

namespace web\admin\rigger;

class cataindex {
    public static function json_init() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid=0');
        $csql->order('csort,id');
        $rows = $db->get($csql);
        $ret = array('list' => $rows);
        if ($post->getbool('field')) {
            $field = array();
            $fshow = '';
            $fshow = fieldadd($fshow, $field, -1, '_btn', '操作');
            $fshow = fieldadd($fshow, $field, -1, 'id', '|库索引|');
            $fshow = fieldadd($fshow, $field, -1, 'name', '库名称');
            $fshow = fieldadd($fshow, $field, -1, 'codeid', '库代码');
            $fshow = fieldadd($fshow, $field, -1, 'csort', '排序|');
            $fshow = fieldadd($fshow, $field, -1, 'extdata', '引用表');
            $field['name']['thwidth'] = '20em';
            $field['extdata']['thwidth'] = '20em';
            $ret['field'] = $field;
            $ret['fshow'] = $fshow;
        }
        if ($post->getbool('once')) {
            $ret['once'] = true;
            $input = array();
            $input[] = array(
                'type' => 'input',
                'form' => 'name',
                'name' => '库名称',
                'prop' => ' style="width:10em;"'
            );
            $input[] = array(
                'type' => 'input',
                'form' => 'codeid',
                'name' => '库代码',
                'prop' => ' style="width:10em;"'
            );
            $input[] = array(
                'type' => 'input',
                'form' => 'extdata',
                'name' => '引用表',
                'prop' => ' style="width:10em;"'
            );
            $ret['searchinput'] = $input;
        }
        return succjson($ret);
    }

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

        if (nopower($db, $rsuser['id'], 'p601pi'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $id = $post->getint('id');
        $codeid = $post->get('codeid');
        if (empty($codeid))
            return errjson('请填写值');
        $name = $post->get('name');
        if (empty($name))
            return errjson('请填写名称');
        $upid = $post->getint('upid');
        $csort = $post->getint('csort');
        $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=0')->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['upid'] = $upid;
            $updata['csort'] = $csort;
            $updata['codeid'] = $codeid;
            $updata['name'] = $name;
            $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 {
                $updata['isuse'] = 1;
                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());
        }
        $ret['data'] = $updata;
        return succjson($ret);
    }

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

        if (nopower($db, $rsuser['id'], 'p601pi'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $ids = $post->get('ids');
        if (empty($ids))
            return errjson('请选择至少一条');
        $csql = new \ciy\sql('zc_cata');

        $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('upid', $delid);
                $csql->where('cbid=0');
                $downcnt = $db->get1($csql);
                if ($downcnt > 0)
                    throw new \Exception("该库有{$downcnt}个子库，请先删除子库");
                delcheck($db, $delid, 'zc_cata', 'cbid', '代码');
                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());
        }
        $ret['ids'] = $vids;
        return succjson($ret);
    }
    public static function json_fore_addnew() {
        global $db;
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid=0');
        $csql->order('id desc');
        $csql->column('id');
        $ret['cateid'] = $db->get1($csql) + 1;
        $csql = new \ciy\sql('zc_cata');
        $csql->where('cbid>0');
        $csql->order('id desc');
        $csql->column('id');
        $valid = $db->get1($csql);
        $ret['valid'] = toint($valid / 50) * 50 + 50;
        return succjson($ret);
    }

    public static function json_addnew() {
        global $db;
        $rsuser = verifyfast();
        if (nopower($db, $rsuser['id'], 'p601pi'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $upid = $post->getint('upid');
        $cateid = $post->getint('cateid');
        $valid = $post->getint('valid');
        $data = $post->get('data');
        if (empty($data))
            return errjson('请填写信息');
        $multi = explode("\n", str_replace('，', ',', $data));
        $catename = '';
        $catecode = '';
        $csql = new \ciy\sql('zc_cata');
        $csql->where('id', $cateid);
        if (is_array($db->getone($csql)))
            return errjson('库ID被占用');
        $vals = array();
        foreach ($multi as $m) {
            $m = trim($m);
            if (empty($m))
                continue;
            $ms = explode(',', $m);
            if (count($ms) != 2)
                return errjson($m . ' 信息格式错误');
            if (empty($catename)) {
                $catename = trim($ms[0]);
                $catecode = trim($ms[1]);
                if (empty($catename) || empty($catecode))
                    return errjson('请填写分类名称和分类代码');
            } else {
                $vname = trim($ms[0]);
                $vid = trim($ms[1]);
                if (!empty($vname) && !empty($vid))
                    $vals[$vid] = $vname;
            }
        }
        $csql = new \ciy\sql('zc_cata');
        $csql->where('codeid', $catecode);
        $csql->where('cbid=0');
        if (is_array($db->getone($csql)))
            return errjson('库代码重复');
        if (count($vals) < 2)
            return errjson('请至少填写2个有效值');
        try {
            $db->begin();
            $updata = array();
            $updata['id'] = $cateid;
            $updata['upid'] = $upid;
            $updata['cbid'] = 0;
            $updata['csort'] = 10;
            $updata['isuse'] = 1;
            $updata['codeid'] = $catecode;
            $updata['name'] = $catename;
            $csql = new \ciy\sql('zc_cata');
            if ($db->insert($csql, $updata) === false)
                throw new \Exception('新增库失败:' . $db->error);
            foreach ($vals as $vid => $vname) {
                $updatav = array();
                $updatav['id'] = $valid++;
                $updatav['upid'] = 0;
                $updatav['cbid'] = $cateid;
                $updatav['csort'] = 10;
                $updatav['isuse'] = 1;
                $updatav['codeid'] = $vid;
                $updatav['name'] = $vname;
                $csql = new \ciy\sql('zc_cata');
                if ($db->insert($csql, $updatav) === false)
                    throw new \Exception('新增值失败:' . $db->error);
            }
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        $ret['data'] = $updata;
        return succjson($ret);
    }
}
