<?php
namespace app\admin\controller;

use app\common\util\QrcodeUtil;
use think\Db;
use think\Exception;

class DinnerGroup extends Auth
{

    public function index(){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['title','like','%'.$title.'%'];
            }
            $enable = input('enable','','trim');
            if($enable != ''){
                $map[] = ['enable','=',$enable];
            }

            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('dinner_group')->where($map)->limit($start,$length)->order($order)->select();


            //数据返回
            $totalCount = Db::name('dinner_group')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            return $this->fetch();
        }
    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        if(request()->isPost()){
            $res = model('DinnerGroup')->updates();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('DinnerGroup')->getError());
            }
        }else{
            if($id){
                $info = Db::name('dinner_group')->where('id',$id)->find();

                $this->assign('info',$info);
            }

            $cur = get_week_days(0);
            $curnext = get_week_days(1);
            $weeks = [
                ["id"=>0,"name"=>"本周({$cur[0]} ~ {$cur[1]})"],
                ["id"=>1,"name"=>"下周({$curnext[0]} ~ {$curnext[1]})"]
            ];
            $this->assign('weeks',$weeks);

            return $this->fetch();
        }
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $res = Db::name('dinner_group')->where('id',$id)->setField('del',1);
        if($res){

            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 改变字段值
     * @param int $fv
     * @param string $fn
     * @param int $fv
     */
    public function changeField($id=0,$fn='',$fv=0){
        if(!$fn||!$id){
            $this->error('参数错误');
        }
        $res = Db::name('dinner_group')->where('id',$id)->setField($fn,$fv);
        if($res){
            $name = '套餐:';
            $content = '';
            if($fn == 'enable'){
                $content = $name.'禁用';
                if($fv == 1){
                    $content = $name.'启用';
                }
            }

            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    public function setting($id=0,$day=''){
        $info = Db::name('dinner_group')->where('id',$id)->find();
        if(!$info){
            $this->error('套餐不存在');
        }
        $day = $day?$day:$info['start'];
        $this->assign('day',$day);

        $weeks = [];
        $stime = $info['start'];
        while (true){
            if($stime > $info['end']){
                break;
            }
            $weeks[] = [
                'day' => $stime,
                'week' => get_week_txt($stime),
            ];
            $stime = date('Y-m-d',strtotime($stime) + 24*60*60);
        }
        $this->assign('weeks',$weeks);

        $typeList = model('DinnerType')->getList($this->orgId);
        foreach ($typeList as $k=>$v){
            $limit = Db::name('dinner_group_type')
                ->where('group_id',$id)
                ->where('day',$day)
                ->where('dinner_type_id',$v['id'])
                ->value('limit');
            $typeList[$k]['limit'] = $limit?$limit:0;

            $items = Db::name('dinner_group_item')
                ->alias('a')
                ->join('dinner b','a.dinner_id = b.id')
                ->where('a.group_id',$id)
                ->where('a.day',$day)
                ->where('b.dinner_type_id',$v['id'])
                ->field('a.id,a.money,a.dinner_id,b.name,b.money as oldmoney,b.imgs,a.required,a.max')
                ->order('b.sort asc, a.id desc')
                ->select();
            foreach ($items as $kk=>$vv){
                if($vv['money'] == 0 && $vv['oldmoney'] > 0){
                    $items[$kk]['money'] = $vv['oldmoney'];
                }
                $imgs = $vv['imgs']?explode(',',$vv['imgs']):[];
                $items[$kk]['img'] = $imgs?$imgs[0]:'';
            }
            $typeList[$k]['items'] = $items?$items:[];

            // 组合
            $combination = Db::name('dinner_group_combination')
                ->where('group_id',$info['id'])
                ->where('dinner_type_id',$v['id'])
                ->where('day',$day)
                ->select();
            foreach ($combination as $kk=>$vv){
                $items = explode(',',$vv['items']);
                $names = Db::name('dinner')
                    ->alias('a')
                    ->join('dinner_group_item b','a.id = b.dinner_id')
                    ->where('b.id','in',$items)
                    ->column('name');
                $combination[$kk]['names'] = $names?implode(',',$names):'';
            }
            $typeList[$k]['combination'] = $combination?$combination:[];

            // 互斥组合
            $combination2 = Db::name('dinner_group_combination2')
                ->where('group_id',$info['id'])
                ->where('dinner_type_id',$v['id'])
                ->where('day',$day)
                ->select();
            foreach ($combination2 as $kk=>$vv){
                $items = explode(',',$vv['items']);
                $names = Db::name('dinner')
                    ->alias('a')
                    ->join('dinner_group_item b','a.id = b.dinner_id')
                    ->where('b.id','in',$items)
                    ->column('name');
                $combination2[$kk]['names'] = $names?implode(',',$names):'';
            }
            $typeList[$k]['combination2'] = $combination2?$combination2:[];
        }
//        halt($typeList);
        $this->assign('typeList',$typeList);

        $this->assign('info',$info);
        return $this->fetch();
    }

    // 选择种类限制
    public function limits(){
        $groupId = input('id/d',0);
        $day = input('day','','trim');
        $typeId = input('typeId/d',0);
        $info = Db::name('dinner_group_type')
            ->where('group_id',$groupId)
            ->where('day',$day)
            ->where('dinner_type_id',$typeId)
            ->find();
        if(request()->isPost()){
            $limit = input('limit/d',0);
            if($limit < 0){
                $this->error('限制数不能小于0');
            }
            if($info){
                if($info['limit'] == $limit){
                    $ret = true;
                }else{
                    $ret = Db::name('dinner_group_type')->where('id',$info['id'])->update(['limit'=>$limit]);
                }
            }else{
                $ret = Db::name('dinner_group_type')->insert([
                    'group_id' => $groupId,
                    'day' => $day,
                    'dinner_type_id' => $typeId,
                    'limit' => $limit
                ]);
            }
            if($ret){

                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->assign('id',$groupId);
            $this->assign('day',$day);
            $this->assign('typeId',$typeId);
            $limit = $info?$info['limit']:0;
            $this->assign('limit',$limit);
            return $this->fetch();
        }
    }

    public function items($id=0,$typeId=0,$day=''){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $title = input('title','','trim');
            if($title){
                $map[] = ['name','like','%'.$title.'%'];
            }

            $dids = Db::name('dinner_group_item')->where('group_id',$id)->where('day',$day)->column('dinner_id');
            if($dids){
                $map[] = ['id','not in',$dids];
            }

            $map[] = ['cate','=',1];
            $map[] = ['dinner_type_id','=',$typeId];
            $map[] = ['enable','=',1];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = Db::name('dinner')->where($map)->limit($start,$length)->order($order)->select();
            foreach ($lists as $k=>$v){
                $img = $v['imgs']?explode(',',$v['imgs']):[];
                $lists[$k]['img'] = $img?$img[0]:'';
            }

            //数据返回
            $totalCount = Db::name('dinner')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $this->assign('id',$id);
            $this->assign('day',$day);
            $this->assign('typeId',$typeId);
            return $this->fetch();
        }
    }

    public function itemsave(){
        $groupId = input('groupId/d',0);
        $day = input('day','','trim');
        $id = input('id/d',0);
        if($groupId<=0 || !$day || $id < 0){
            $this->error('参数错误');
        }
        $dinner = Db::name('dinner')->where('id',$id)->find();
        if(!$dinner){
            $this->error('菜品不存在');
        }
        $info = Db::name('dinner_group_item')->where('dinner_id',$id)->where('day',$day)->find();
        if($info){
            $this->error('已添加,无重复');
        }
        $data = [
            'group_id' => $groupId,
            'day' => $day,
            'dinner_id' => $id,
            'required' => 0,
            'money' => $dinner['money']
        ];
        $ret = Db::name('dinner_group_item')->insert($data);
        if($ret){

            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }

    public function itemdel(){
        $id = input('id/d',0);
        if($id < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_item')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        Db::startTrans();
        try{
            $ret = Db::name('dinner_group_item')->delete($id);
            if(!$ret){
                \exception('操作失败2');
            }

            // 消除组合里的商品
            $map[]=['','exp',Db::raw("FIND_IN_SET({$id},items)")];
            $lists = Db::name('dinner_group_combination')->where($map)->select();
            $lists = $lists?$lists:[];
            foreach ($lists as $k=>$v){
                $items = explode(',',$v['items']);
                $items = array_diff($items,[$id]);
                sort($items);

                if(count($items) <= 1){
                    $ret = Db::name('dinner_group_combination')->delete($v['id']);
                }else{
                    $ret = Db::name('dinner_group_combination')
                        ->where('id',$v['id'])
                        ->update(['items'=>implode(',',$items)]);

                }
                if(!$ret){
                    \exception('操作失败1');
                }
            }

            // 消除互斥组合里的商品
            $map2[]=['','exp',Db::raw("FIND_IN_SET({$id},items)")];
            $lists = Db::name('dinner_group_combination2')->where($map2)->select();
            $lists = $lists?$lists:[];
            foreach ($lists as $k=>$v){
                $items = explode(',',$v['items']);
                $items = array_diff($items,[$id]);
                sort($items);

                if(count($items) <= 1){
                    $ret = Db::name('dinner_group_combination2')->delete($v['id']);
                }else{
                    $ret = Db::name('dinner_group_combination2')
                        ->where('id',$v['id'])
                        ->update(['items'=>implode(',',$items)]);

                }
                if(!$ret){
                    \exception('操作失败1');
                }
            }


            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('操作失败'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    public function itemcombination(){
        $id = input('id/d',0);
        if($id < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_combination')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        $ret = Db::name('dinner_group_combination')->delete($id);
        if($ret){

            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }

    public function itemrequired(){
        $id = input('id/d',0);
        if($id < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_item')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        $ret = Db::name('dinner_group_item')->where('id',$id)->update(['required' => $info['required']==1?0:1]);
        if($ret){

            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }

    public function itemmax(){
        $id = input('id/d',0);
        $val = input('val/d',0);
        if($id < 0 || $val < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_item')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        $ret = Db::name('dinner_group_item')->where('id',$id)->update(['max' => $val]);
        if($ret){
            $info['val'] = $val;

            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }

    public function itemmoney(){
        $id = input('id/d',0);
        $val = input('val/f',0);
        if($id < 0 || $val < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_item')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        $ret = Db::name('dinner_group_item')->where('id',$id)->update(['money' => $val]);
        if($ret){
            $info['money'] = $val;

            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }

    public function combination(){
        if(request()->isPost()){
            $data = [
                'title' => input('title','','trim'),
                'group_id' => input('group_id/d',0),
                'day' => input('day','','trim'),
                'dinner_type_id' => input('dinner_type_id/d',0),
                'items' => input('items','','trim')
            ];
            if(!$data['title']){
                $this->error('请输入名称');
            }
            if(!$data['items'] && !format_str($data['items'])){
                $this->error('请选择菜品');
            }
            $items = explode(',',format_str($data['items']));
            sort($items);
            if(count($items) <= 1){
                $this->error('组合至少要选两种菜品');
            }
            $data['items'] = implode(',',$items);

            $ret = Db::name('dinner_group_combination')
                ->where('group_id',$data['group_id'])
                ->where('day',$data['day'])
                ->where('dinner_type_id',$data['dinner_type_id'])
                ->column('items');
            $ret = $ret?$ret:[];
            $aitems = [];
            foreach ($ret as $k=>$v){
                $aitems = array_merge($aitems,explode(',',$v));
            }
            if(array_intersect($items,$aitems)){
                $this->error('选择的部分商品已在其他组合中');
            }

            $ret = Db::name('dinner_group_combination')->insert($data);
            if(!$ret){
                $this->error('操作失败');
            }

            $this->success('操作成功');
        }else{
            $groupId = input('groupId/d',0);
            $typeId = input('typeId/d',0);
            $day = input('day','','trim');

            $dinners = Db::name('dinner_group_item')
                ->alias('a')
                ->join('dinner b','a.dinner_id = b.id')
                ->where('a.group_id',$groupId)
                ->where('a.day',$day)
                ->where('b.dinner_type_id',$typeId)
                ->field('a.id,b.name as title')
                ->select();
            $this->assign('groupId',$groupId);
            $this->assign('typeId',$typeId);
            $this->assign('day',$day);
            $this->assign('dinners',$dinners);
            return $this->fetch();
        }

    }

    public function combinationdel(){
        $id = input('id/d',0);
        if($id < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_combination')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        Db::startTrans();
        try{
            $ret = Db::name('dinner_group_combination')->delete($id);
            if(!$ret){
                \exception('操作失败');
            }


            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('操作失败'.$e->getMessage());
        }
        $this->success('操作成功');
    }

    public function combination2(){
        if(request()->isPost()){
            $data = [
                'group_id' => input('group_id/d',0),
                'day' => input('day','','trim'),
                'dinner_type_id' => input('dinner_type_id/d',0),
                'items' => input('items','','trim')
            ];
            if(!$data['items'] && !format_str($data['items'])){
                $this->error('请选择菜品');
            }
            $items = explode(',',format_str($data['items']));
            sort($items);
            if(count($items) <= 1){
                $this->error('组合至少要选两种菜品');
            }
            $data['items'] = implode(',',$items);

//            $ret = Db::name('dinner_group_combination2')
//                ->where('group_id',$data['group_id'])
//                ->where('day',$data['day'])
//                ->where('dinner_type_id',$data['dinner_type_id'])
//                ->column('items');
//            $ret = $ret?$ret:[];
//            $aitems = [];
//            foreach ($ret as $k=>$v){
//                $aitems = array_merge($aitems,explode(',',$v));
//            }
//            if(array_intersect($items,$aitems)){
//                $this->error('选择的部分商品已在其他组合中');
//            }

            $ret = Db::name('dinner_group_combination2')->insert($data);
            if(!$ret){
                $this->error('操作失败');
            }

            $this->success('操作成功');
        }else{
            $groupId = input('groupId/d',0);
            $typeId = input('typeId/d',0);
            $day = input('day','','trim');

            $dinners = Db::name('dinner_group_item')
                ->alias('a')
                ->join('dinner b','a.dinner_id = b.id')
                ->where('a.group_id',$groupId)
                ->where('a.day',$day)
                ->where('b.dinner_type_id',$typeId)
                ->field('a.id,b.name as title')
                ->select();
            $this->assign('groupId',$groupId);
            $this->assign('typeId',$typeId);
            $this->assign('day',$day);
            $this->assign('dinners',$dinners);
            return $this->fetch();
        }

    }

    public function combination2del(){
        $id = input('id/d',0);
        if($id < 0){
            $this->error('参数错误');
        }
        $info = Db::name('dinner_group_combination2')->where('id',$id)->find();
        if(!$info){
            $this->error('记录不存在');
        }

        Db::startTrans();
        try{
            $ret = Db::name('dinner_group_combination2')->delete($id);
            if(!$ret){
                \exception('操作失败');
            }


            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('操作失败'.$e->getMessage());
        }
        $this->success('操作成功');
    }
}