<?php


/**
 * Class sqShopAction 店铺授权公众号
 */
class sqShopAction extends baseAction
{
    /**
     * @var null 模型
     */
    private $model = null;

    //授权店铺列表
    public function  index()
    {
        LibRule::Check('SL01');
        $param = mvc::$URL_PARAMS;
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = LibFc::Int($param['page']) ? LibFc::Int($param['page']) : 1;
        $where = '';
        if($param['dshop_name']) $where .= sprintf(" and dshop_name like '%%%s%%'",trim($param['dshop_name']));
        if(is_numeric($param['dshop_status'])) $where .= sprintf(" and dshop_status='%s'",$param['dshop_status']);
        if((int) $param['dshop_id']){

            $LibYpApi = new LibYpApi();
            $post = [
                    'filed' => ['u_id', 'u_name', 'u_mobile'],
                    'where' => sprintf(" and (u_name = '%s' or u_mobile='%s') order by u_name limit 1",trim($param['dshop_id']),trim($param['dshop_id'])),
                    true
            ];
            $user = $LibYpApi->get('user/getUser', [], $post);
            if(empty($user['data'])){
                $user['data']['0']['u_id'] = 0;
            }
            $where .= sprintf(" and dshop_id=%d", (int) $user['data']['0']['u_id']);
        } 
        $count = $this->init()->get("sh_dshop",['count(*) as count'],$where,true);
        $count = $count['data']['count'] <= 0 ? 0 : $count['data']['count'];
        if($count > 0){
            $modelSelectArr = $this->modelSelectArr();
            $modelSelectArr = array_column($modelSelectArr,'name','val');
            $where .= sprintf(" limit %s,%s",($page-1)*$pageSize,$pageSize);
            $list = $this->init()->get("sh_dshop",['*'],$where);
            $dshop_id = array_column($list['data'],'dshop_id');
            $shopList = $this->init()->get('sh_dshop_link inner join sh_shop on dsl_from_shop_id=shop_id',['sh_dshop_link.*','sh_shop.shop_id','sh_shop.shop_name'],sprintf(" and dsl_dshop_id in (%s)",implode(',',$dshop_id)));
            $shopLists = [];
            $LibYpApi = new LibYpApi();
            $post = [
                    'filed'=>['u_id', 'u_name', 'u_mobile'],
                    'where'=>sprintf(" and u_id in(%s)", implode(',',$dshop_id)),
                    true
            ];
            $userList = $LibYpApi->get('user/getUser', [], $post);
            if(!empty($userList['data'])){
                $userList = array_column($userList['data'],null,'u_id');
            }else{
                $userList = [];
            }
            foreach ($shopList['data'] as $value){
                $shopLists[$value['dsl_dshop_id']][] = $value;
                unset($value);
            }
            unset($shopList);
            $OthQrcode = new OthQrcode();
            foreach ($list['data'] as &$v){
                if($v['dshop_id'] > 0){
                    $url = mvc::$cfg['HOST']['dshop'].$v['dshop_id'].'/index.php';
                    $v['ewm'] = $OthQrcode->png($url,false, 1, 6);
                }
                if(isset($shopLists[$v['dshop_id']])){
                    $v['link'] = $shopLists[$v['dshop_id']];
                }
                if(isset($userList[$v['dshop_id']])){
                    $v['user_info'] = $userList[$v['dshop_id']];
                }
                if(!empty($v['dshop_etime'])){
                    $v['betime'] = date('Y-m-d',$v['dshop_btime']).' ~ '.date('Y-m-d',$v['dshop_etime']);
                    if($v['dshop_etime'] < time()){
                        $v['betime'] .= '<span class="orange">'.'已过期'.floor((time() - $v['dshop_etime']) / 86400).'天</span>';
                    }else{
                        $v['betime'] .= '<span class="green">'.'剩余'.floor(($v['dshop_etime'] - time()) / 86400).'天</span>';
                    }
                }
                if(isset($modelSelectArr[$v['dshop_model']])){
                    $v['dshop_model'] = $modelSelectArr[$v['dshop_model']];
                }
                $v['dshop_engine'] = $v['dshop_engine'] == 1 ? '<span class="green">'.'支持'.'</span>' : '<span class="orange">'.'不支持'.'</span>';
            }
            unset($shopLists);
            LibTpl::Set('list',$list['data']);
        }else{
            LibTpl::Set('list',[]);
        }
        //var_dump($list['data']);exit();
        $pages = LibPage::Show($count, $pageSize);
        LibTpl::Set('page', $pages);
        LibTpl::Set('Params',$param);
        LibTpl::Set('title', '授权店铺');
        LibTpl::Put();
    }

    public function addPage()
    {
        $param = mvc::$URL_PARAMS;
        $id = LibFc::Int($param['id']);
        $data = [];
        $shop_name = $this->init()->get('sh_shop',['shop_id','shop_name'],' and shop_status=1 order by convert( shop_name using gbk ) collate gbk_chinese_ci asc');
        $shop_names = array_column($shop_name['data'],null,'shop_id');
        if($id > 0){
            LibRule::Check('SL03');
            $data = $this->init()->get('sh_dshop left join sh_dshop_link on dsl_dshop_id=dshop_id',['sh_dshop.*','group_concat(dsl_from_shop_id) as dsl_from_shop_id','group_concat(dsl_btime) as dsl_btime','group_concat(dsl_etime) as dsl_etime'],sprintf(" and dshop_id=%d group by dshop_id",$id),true);
            $data = $data['data'];
            $data['link'] = [];
            if(!empty($data['dsl_from_shop_id'])){
                $dsl_from_shop_id = explode(',',$data['dsl_from_shop_id']);
                $dsl_btime = explode(',',$data['dsl_btime']);
                $dsl_etime = explode(',',$data['dsl_etime']);
                $count = count($dsl_from_shop_id);
                for ($i = 0; $i < $count; $i++)
                {
                    $data['link'][] = [
                        'dsl_from_shop_id' => $dsl_from_shop_id[$i],
                        'shop_name' => $shop_names[$dsl_from_shop_id[$i]]['shop_name'],
                        'dsl_time' => date('Y-m-d',$dsl_btime[$i]).' ~ '.date('Y-m-d',$dsl_etime[$i]),
                    ];
                }
            }
            $LibYpApi = new LibYpApi();
            $post = [
                'filed'=>['u_id', 'u_name', 'u_mobile'],
                'where'=>sprintf(" and u_id=%d order by u_name limit 1", $data['dshop_id']),
                true
            ];
            $res = $LibYpApi->get('user/getUser', [], $post);
            $data['dshop_u_name'] = $res['data']['0']['u_name'];
            $data['dshop_conf'] = json_decode($data['dshop_conf'],true);
            $data['dshop_btime'] = date('Y-m-d H:i:s',$data['dshop_btime']).' ~ '.date('Y-m-d h:i:s',$data['dshop_etime']);
        }else{
            LibRule::Check('SL02');
        }

        LibTpl::Set('modelSelectArr',$this->modelSelectArr());
        LibTpl::Set('shop',json_encode($shop_name['data']));
        LibTpl::Set('count',isset($count) ? $count : 0);
        LibTpl::Set('data', $data ?: []);
        LibTpl::Set('title',$id > 0 ? '编辑代理店铺' : '添加代理店铺');
        LibTpl::Put();
    }

    public function add()
    {
        LibRule::Check('SL03');
        if(!empty($_POST)){
            if((int) $_POST['dshop_id'] <= 0){
                if(empty($_POST['dshop_u_name'])){
                    LibFc::ajaxJsonEncode(['status' => false,'data' => '请输入用户名手机号']);
                }
                $LibYpApi = new LibYpApi();
                $post = [
                    'filed'=>['u_id', 'u_name', 'u_mobile'],
                    'where'=>sprintf(" and (u_name = '%s' or u_mobile='%s') order by u_name limit 1", $_POST['dshop_u_name'],$_POST['dshop_u_name']),
                    true
                ];
               
                $res = $LibYpApi->get('user/getUser', [], $post);
                 if(empty($res['0']['data'])){
                    LibFc::ajaxJsonEncode(['status' => false,'data' => '没有找到该手机或者用户名']);
                }
                $_POST['dshop_id'] = $res['data']['0']['u_id'];
            }
            $data = [
                'dshop_id' => (int) $_POST['dshop_id'],
                'dshop_name' => trim($_POST['dshop_name']),
                'dshop_logo' => trim($_POST['dshop_logo']),
                'dshop_remark' => trim($_POST['dshop_remark']),
                'dshop_status' => (int) $_POST['dshop_status'],
                'dshop_conf' => !empty($_POST['dshop_conf']) ? json_encode($_POST['dshop_conf']) : '{}',
                'dshop_engine' => (int) $_POST['dshop_engine'] ?: 0,
            ];
            if(!empty($_POST['dshop_btime'])){
                $temp = array_map(function ($value){
                    return strtotime($value);
                },explode(" ~ ",$_POST['dshop_btime']));
                $data['dshop_btime'] = (int) current($temp);
                $data['dshop_etime'] = (int) next($temp);
            }
            if(!empty($_POST['dshop_model'])){
                $data['dshop_model'] = base64_decode($_POST['dshop_model']);
            }else{
                $data['dshop_model'] = '{}';
            }
            if($data['dshop_id'] <= 0){
                LibFc::ajaxJsonEncode(['status' => false,'data' => '用户ID 不可为空']);
            }
            $link = [];
            $count = count($_POST['dsl_from_shop_id']);
            if($count > 0){
                for ($i = 0 ; $i < $count; $i++)
                {
                    if(empty($_POST['dsl_time'][$i])){
                        LibFc::ajaxJsonEncode(['status' => false,'data' => '授权时间区间不可为空']);
                    }
                    $temp = explode(' ~ ',$_POST['dsl_time'][$i]);
                    $temp = array_map('strtotime',$temp);
                    $link[] = [
                        'dsl_dshop_id' => (int) $_POST['dshop_id'],
                        'dsl_from_shop_id' => (int) $_POST['dsl_from_shop_id'][$i],
                        'dsl_btime' => (int) $temp['0'],
                        'dsl_etime' => (int) $temp['1']
                    ];
                }
            }
            $result = $this->init()->update($data,$link);

			//复制目录文件
			$superSys = mvc::$cfg['ROOT'].'dshop/';
			if(!file_exists($superSys.$data['dshop_id']))
			{
				LibDir::copydir($superSys.'demo', $superSys.$data['dshop_id']);
			}

            LibFc::ajaxJsonEncode($result);
        }else{
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
    }


    public function shopDelete()
    {
        LibRule::Check('SL04');
        $param = mvc::$URL_PARAMS;
        $id = (int) $param['id'];
        if($id <= 0){
            LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        }
        $result = $this->init()->delete($id);
        LibFc::ajaxJsonEncode($result);
    }

    //删除关系
    public function deleteLink()
    {
        LibRule::Check('SL04');
        $result = $this->init()->del("sh_dshop_link",sprintf(" and dsl_dshop_id=%d and dsl_from_shop_id=%d", (int) $_POST['dsl_dshop_id'], (int) $_POST['dsl_from_shop_id']));
        LibFc::ajaxJsonEncode($result);
    }

    /**
     * 初始化
     * @return B2cBase|null
     */
    private function init()
    {
        if(is_null($this->model)){
            $this->model = new B2cSq();
        }
        return $this->model;
    }

    /**
     * @return string[][]
     */
    private function modelSelectArr()
    {
        return mvc::$cfg['MODEL_OPTS'];
    }
}