<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\CarGiftT;
use common\models\EmsT;
use common\models\GiftT;
use common\models\GiftTicketTUse;
use common\models\GiftTypeT;
use common\models\GiftUseLogT;
use common\models\GroupT;
use common\models\InsurerTypeT;
use common\models\OrderT;
use common\models\StrategyT;
use common\models\UserT;
use Yii;
use yii\data\Pagination;
use yii\web\Response;

class GiftController extends \yii\web\Controller
{
    public $my = null;
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';
    private $_outEncoding = "GB2312";

    public function init()
    {
        parent::init();

        $cookie = Yii::$app->request->cookies;
        $user_id = MyLib::encrypt($cookie->get('aid'),'DECODE');

        if($user_id != 0)
        {
            $this->my = UserT::findOne(['id'=>$user_id]);
        } else {
            Yii::$app->response->redirect('/common/login')->send();
            exit;
        }
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $type_id = $request->get('type_id');
        $name = $request->get('name');

        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftT::find()
            ->where('is_delete=0');
        if($type_id > 0) {
            $query = $query->andWhere('type_id='.$type_id);
        }
        if($name != '') {
            $query = $query->andWhere('name like "'.$name.'"');
        }
        $query = $query->orderBy('id desc');
        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['type'] = $item->showType;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        if($id > 0) {
            $info = GiftT::findOne(['id'=>$id]);
        } else {
            $info = new GiftT();
        }

        return $this->render('edit',[
            'info' => $info
        ]);
    }

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $type_id = $request->post('type_id');
            $name = $request->post('name');
            $img = $request->post('img');
            $price = $request->post('price');
            $remark = $request->post('remark');
            $use_num = (int)$request->post('use_num');

            if($name == '') {
                $result['msg'] = '请输入名称!';
                return $result;
            }

            $pin_name=trim($this->getPinyin($name),' ');

            $row = null;
            if($id > 0) {
                $row = GiftT::findOne(['id'=>$id]);
            } else {
                $row = new GiftT();
            }
            $row->type_id = $type_id;
            $row->name = $name;
            $row->price = $price;
            $row->original_img = $img;
            $row->remark = $remark;
            $row->use_num = $use_num;
            $row->pinyin_name = $pin_name;
            $row->save();

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $row = GiftT::findOne(['id'=>$id]);
                $row->is_delete = 1;
                $row->save();

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }

    public function actionCarAddSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '添加失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $order_id = $request->post('order_id');
            $gift_id = $request->post('gift_id');

            if($gift_id == 0) {
                $result['msg'] = '请选择礼品';
                return $result;
            }
            $gift_info = new CarGiftT();
            $gift_info->car_id = $car_id;
            $gift_info->order_id = $order_id;
            $gift_info->user_id = $this->my->id;
            $gift_info->gift_id = $gift_id;
            $gift_info->submit_time = time();
            $gift_info->status = 0;
            $gift_info->type = 2;
            $gift_info->save();

            $order_info = $gift_info->order;
            $order_info->check_gift = 1;
            $order_info->save();

            $result['success'] = true;
            $result['msg'] = '添加成功';
        }
        return $result;
    }

    public function actionCarDeleteSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $gift_id = $request->post('gift_id');
            $gift_info = CarGiftT::findOne(['id'=>$gift_id]);
            if($gift_info->status == 0) {
                $order_id = $gift_info->order_id;
                $gift_info->delete();
                $total = CarGiftT::find()
                    ->where('order_id='.$order_id.' and (status=0 or status=2)')
                    ->count();
                if($total > 0) {
                    $order_info = OrderT::findOne(['id'=>$order_id]);
                    $order_info->check_gift = 1;
                    $order_info->save();
                }
            } else {
                $gift_info->status = 2;
                $gift_info->save();
                $order_info = $gift_info->order;
                $order_info->check_gift = 1;
                $order_info->save();
            }

            $result['success'] = true;
            $result['msg'] = '删除成功';
        }
        return $result;
    }

    public function actionAjaxCarIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $type = $request->get('type',0);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = CarGiftT::find()
            ->where(['car_id'=>$car_id])
//            ->andWhere('type=2')
            ->orderBy('id ASC');

        if($type == 0)
            $query = $query->andWhere('type=2');
        $items = $query->all();

        $html = $this->renderPartial('ajax-car-index',[
            'car_id' => $car_id,
            'items' => $items
        ]);
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionAjaxCompanyIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $order_id = $request->get('order_id');
        $total1_clear = $request->get('total1_clear');
        $type = $request->get('type',0);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $order_info = OrderT::findOne(['id'=>$order_id]);

        //处理全部范围,没有最低费用限制和最高消费
        $query = StrategyT::find()
            ->where('min_money=0 and group_id=0 and max_money=0')
            ->orderBy('id ASC');
//        echo $query->createCommand()->rawSql."\r\n";
        $items = $query->all();
        if($total1_clear > 0) {
            //处理全部范围,没有最低,只有最高消费
            $query = StrategyT::find()
                ->where('min_money=0 and group_id=0 and max_money>='.$total1_clear)
                ->orderBy('id ASC');
//        echo $query->createCommand()->rawSql."\r\n";
            if($query->count() > 0)
                $items = array_merge($items,$query->all());
            //处理全部范围,有最低,没有最高消费
            $query = StrategyT::find()
                ->where('min_money>0 and min_money<='.$total1_clear.' and group_id=0 and max_money=0')
                ->orderBy('id ASC');
//            echo $query->createCommand()->rawSql."\r\n";
            if($query->count() > 0)
                $items = array_merge($items,$query->all());
            //处理全部范围,有最低,有最高消费
            $query = StrategyT::find()
                ->where('min_money>0 and min_money<='.$total1_clear.' and group_id=0 and max_money>='.$total1_clear)
                ->orderBy('id ASC');
//            echo $query->createCommand()->rawSql."\r\n";
            if($query->count())
                $items = array_merge($items,$query->all());
        }
        //处理指定范围,没有最低,没有最高消费
        $query = StrategyT::find()
            ->where('min_money=0 and group_id>0 and max_money=0')
            ->orderBy('id ASC');
//        echo $query->createCommand()->rawSql."\r\n";
        $tmp_items = $query->all();
        foreach($tmp_items as $item) {
            $group_info = GroupT::findOne(['id'=>$item->group_id]);
            if($group_info->hasChild($order_info->user->group_id)) {
                $items[] = $item;
            }
            if($group_info->id == $order_info->user->group_id) {
                $items[] = $item;
            }
        }
        if($total1_clear > 0) {
            //处理指定范围,没有最低,有最高消费
            $query = StrategyT::find()
                ->where('min_money=0 and group_id>0 and max_money>='.$total1_clear)
                ->orderBy('id ASC');
//            echo $query->createCommand()->rawSql."\r\n";
            $tmp_items = $query->all();
            foreach($tmp_items as $item) {
                $group_info = GroupT::findOne(['id'=>$item->group_id]);
                if($group_info->hasChild($order_info->user->group_id)) {
                    $items[] = $item;
                }
                if($group_info->id == $order_info->user->group_id) {
                    $items[] = $item;
                }
            }
            //处理指定范围,有最低,没有最高消费
            $query = StrategyT::find()
                ->where('min_money>0 and min_money<='.$total1_clear.' and group_id>0 and max_money=0')
                ->orderBy('id ASC');
//            echo $query->createCommand()->rawSql."\r\n";
            $tmp_items = $query->all();
            foreach($tmp_items as $item) {
                $group_info = GroupT::findOne(['id'=>$item->group_id]);
                if($group_info->hasChild($order_info->user->group_id)) {
                    $items[] = $item;
                }
                if($group_info->id == $order_info->user->group_id) {
                    $items[] = $item;
                }
            }
            //处理指定范围,有最低,有最高消费
            $query = StrategyT::find()
                ->where('min_money>0 and min_money<='.$total1_clear.' and group_id>0 and max_money>='.$total1_clear)
                ->orderBy('id ASC');
//            echo $query->createCommand()->rawSql."\r\n";
            $tmp_items = $query->all();
            foreach($tmp_items as $item) {
                $group_info = GroupT::findOne(['id'=>$item->group_id]);
                if($group_info->hasChild($order_info->user->group_id)) {
                    $items[] = $item;
                }
                if($group_info->id == $order_info->user->group_id) {
                    $items[] = $item;
                }
            }
        }

        //获取已经得到的礼品
        $tmp_query = CarGiftT::find()
            ->where('car_id='.$car_id.' and order_id='.$order_id.' and strategy_id>0');
//        echo $tmp_query->createCommand()->rawSql."<br>";
        $car_gift_items = $tmp_query->all();

        $order_gift_items = array();
        foreach($car_gift_items as $item) {
            $order_gift_items[] = $item->strategy_id.'-'.$item->gift_id;
        }

        $html = $this->renderPartial('ajax-company-index',[
            'car_id' => $car_id,
            'order_id' => $order_id,
            'items' => $items,
            'order_gift_items' => $order_gift_items
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionMngList()
    {
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = OrderT::find()
            ->where('status_id>1 and check_gift=1')
            ->orderBy('submit_date DESC, id DESC');
        if($car_man != '') {
            $query = $query->andWhere('car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('link_phone="'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
//        echo $query->createCommand()->rawSql;
        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getPageInfo($pagination);

        return $this->render('mng-list',[
            'items' => $items,
            'car_man' => $car_man,
            'phone' => $phone,
            'car_no' => $car_no,
            'page' => $page,
            'page_info' => $page_info
        ]);
    }

    public function actionMngListInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $order_info = OrderT::findOne(['id'=>$id]);
        $car_info = $order_info->car;

        //快递
        $ems_items = EmsT::find()
            ->where(['car_id'=>$car_info->id,'order_id'=>$order_info->id])
            ->orderBy('id ASC')
            ->all();
        //礼品
        $gift_items = CarGiftT::find()
            ->where('order_id='.$order_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

        $insurer_type_items = InsurerTypeT::find()
            ->all();

        return $this->render('mng-list-info',[
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'ems_items' => $ems_items,
            'gift_items' => $gift_items
        ]);
    }


    public function actionOkSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '出库失败';

        if($request->isPost) {
            $gift_ids = $request->post('gift_ids',array());
            $order_id = $request->post('order_id');

            foreach($gift_ids as $id) {
                $item = CarGiftT::findOne(['id'=>$id]);
                if($item->status == 0) {
                    $item->status = 1;
                    $item->save();
                }
            }
            $total = CarGiftT::find()
                ->where('order_id='.$order_id.' and status=0')
                ->count();
            if($total == 0) {
                $order_info = OrderT::findOne(['id'=>$order_id]);
                $order_info->check_gift = 0;
                $order_info->save();
            }
            $result['success'] = true;
            $result['msg'] = '出库成功';
        }
        return $result;
    }

    public function actionCancelSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '退货失败';

        if($request->isPost) {
            $gift_ids = $request->post('gift_ids',array());
            $order_id = $request->post('order_id');

            foreach($gift_ids as $id) {
                $item = CarGiftT::findOne(['id'=>$id]);
                if($item->status == 2) {
                    $item->delete();
                }
            }
            $total = CarGiftT::find()
                ->where('order_id='.$order_id.' and status=0')
                ->count();
            if($total == 0) {
                $order_info = OrderT::findOne(['id'=>$order_id]);
                $order_info->check_gift = 0;
                $order_info->save();
            }
            $result['success'] = true;
            $result['msg'] = '退货成功';
        }
        return $result;
    }
    public function getPinyin($str,$pix=' ',$code = 'gb2312'){
        $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
        $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254";
        $_TDataKey = explode ( '|', $_DataKey );
        $_TDataValue = explode ( '|', $_DataValue );
        $data = (PHP_VERSION >= '5.0') ? array_combine ( $_TDataKey, $_TDataValue ) : $this->_Array_Combine( $_TDataKey, $_TDataValue );
        arsort ( $data );
        reset ( $data );
        $str = $this->safe_encoding ( $str );
        $_Res = '';
        for($i = 0; $i < strlen ( $str ); $i ++) {
            $_P = ord ( substr ( $str, $i, 1 ) );
            if ($_P > 160) {
                $_Q = ord ( substr ( $str, ++ $i, 1 ) );
                $_P = $_P * 256 + $_Q - 65536;
            }
            $_Res .= $this->_Pinyin ( $_P, $data ).$pix;
        }
        return preg_replace ( "/[^a-z0-9".$pix."]*/", '', $_Res );
    }
    private function _Pinyin($_Num, $_Data) {
        if ($_Num > 0 && $_Num < 160)
            return chr ( $_Num );
        elseif ($_Num < - 20319 || $_Num > - 10247)
            return '';
        else {
            foreach ( $_Data as $k => $v ) {
                if ($v <= $_Num)
                    break;
            }
            return $k;
        }
    }
    public function getFirstChar($str=''){
        if( !$str ) return null;
        $fchar=ord($str{0});
        if($fchar>=ord("A") and $fchar<=ord("z") )return strtoupper($str{0});
        $s= $this->safe_encoding($str);
        $asc=ord($s{0})*256+ord($s{1})-65536;
        if($asc>=-20319 and $asc<=-20284)return "A";
        if($asc>=-20283 and $asc<=-19776)return "B";
        if($asc>=-19775 and $asc<=-19219)return "C";
        if($asc>=-19218 and $asc<=-18711)return "D";
        if($asc>=-18710 and $asc<=-18527)return "E";
        if($asc>=-18526 and $asc<=-18240)return "F";
        if($asc>=-18239 and $asc<=-17923)return "G";
        if($asc>=-17922 and $asc<=-17418)return "H";
        if($asc>=-17417 and $asc<=-16475)return "J";
        if($asc>=-16474 and $asc<=-16213)return "K";
        if($asc>=-16212 and $asc<=-15641)return "L";
        if($asc>=-15640 and $asc<=-15166)return "M";
        if($asc>=-15165 and $asc<=-14923)return "N";
        if($asc>=-14922 and $asc<=-14915)return "O";
        if($asc>=-14914 and $asc<=-14631)return "P";
        if($asc>=-14630 and $asc<=-14150)return "Q";
        if($asc>=-14149 and $asc<=-14091)return "R";
        if($asc>=-14090 and $asc<=-13319)return "S";
        if($asc>=-13318 and $asc<=-12839)return "T";
        if($asc>=-12838 and $asc<=-12557)return "W";
        if($asc>=-12556 and $asc<=-11848)return "X";
        if($asc>=-11847 and $asc<=-11056)return "Y";
        if($asc>=-11055 and $asc<=-10247)return "Z";
        return null;
    }
    function safe_encoding($string) {
        $encoding="UTF-8";
        for($i=0;$i<strlen($string);$i++) {
            if(ord($string{$i})<128) continue;
            if((ord($string{$i})&224)==224) { //第一个字节判断通过
                $char=$string{++$i};
                if((ord($char)&128)==128) { //第二个字节判断通过
                    $char=$string{++$i};
                    if((ord($char)&128)==128) {
                        $encoding="UTF-8";
                        break;
                    }
                }
            }
            if((ord($string{$i})&192)==192) { //第一个字节判断通过
                $char=$string{++$i};
                if((ord($char)&128)==128) { //第二个字节判断通过
                    $encoding="GB2312";
                    break;
                }
            }
        }
        if(strtoupper($encoding)==strtoupper($this->_outEncoding))

            return $string;
        else
            return iconv($encoding,$this->_outEncoding,$string);
    }
    private function _Array_Combine($_Arr1, $_Arr2){
        $_Res=array();
        for($i = 0; $i < count ( $_Arr1 ); $i ++)
            $_Res [$_Arr1 [$i]] = $_Arr2 [$i];
        return $_Res;
    }

    public function actionStastics() {
        return $this->render('stastics');
    }

    public function actionStasticsJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftT::find()
            ->where('is_delete=0');
        $query = $query->orderBy('id desc');
        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['total'] = $item->getTicketsUse()->count();
            $type_id = $item->type_id;
            if($type_id ==1){//礼品
                $row['out_total'] = $item->getTicketsUse()->where('status=3')->count();
                $row['use_total'] = $item->getTicketsUse()->where('status=3')->count();
            }elseif ($type_id==2){
                $row['out_total'] = $item->getTicketsUse()->count();
                $row['use_total'] = $item->getTicketsUse()->where('status>1')->count();
            }
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionGiftOut() {
        $type_items = GiftT::find()
            ->where(['type_id'=>1,'is_delete'=>0])
            ->all();
        return $this->render('gift-out', [
            'type_items' => $type_items
        ]);
    }

    public function actionGiftOutJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $code = $request->get('code');
        $car_no = $request->get('car_no');
        $username = $request->get('username');
        $s_begin_date = $request->get('s_begin_date');
        $s_end_date = $request->get('s_end_date');
        $p_begin_date = $request->get('p_begin_date');
        $p_end_date = $request->get('p_end_date');
        $status = $request->get('status');
        $frame_no = $request->get('frame_no');
        $engine_no = $request->get('engine_no');
        $insurer1_no = $request->get('insurer1_no');
        $type_id = $request->get('type_id');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftTicketTUse::find()
            ->leftJoin('order_t','order_t.id=gift_ticket_t_use.order_id')
            ->leftJoin('gift_t','gift_t.id=gift_ticket_t_use.type_id')
            ->leftJoin('user_t','user_t.id=gift_ticket_t_use.user_id')
            ->where('gift_t.type_id=1')
            ->orderBy('id DESC');
        if($code != '') {
            $query = $query->andWhere('gift_ticket_t_use.code="'.$code.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('gift_ticket_t_use.car_no like "'.$car_no.'"');
        }

        if($username != ''){
            $user = UserT::find()->where('username="'.$username.'"')->andWhere('is_delete=0')->one();
            $query = $query->andWhere('gift_ticket_t_use.op_id='.$user->id);
        }

        if($s_begin_date != ''){
            $query = $query->andWhere('order_t.submit_date>="'.$s_begin_date.'"');
        }
        if($s_end_date != ''){
            $query = $query->andWhere('order_t.submit_date<="'.$s_begin_date.'"');
        }
        if($p_begin_date != ''){
            $query = $query->andWhere('order_t.print_date>="'.$p_begin_date.'"');
        }
        if($p_end_date != ''){
            $query = $query->andWhere('order_t.print_date<="'.$p_begin_date.'"');
        }

        if ($status == 1) {//礼券未使用
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=1');
        } elseif ($status == 2) {//礼券使用中
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=2');
        }
        if ($status == 3) {//礼券使用完
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=3');
        }
        if ($status == 4) {//礼品未出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=1');
        }
        if ($status == 5) {//礼品已出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=3');
        }

        if($frame_no != '') {
            $query = $query->andWhere('order_t.car_frame_no="'.$frame_no.'"');
        }
        if($engine_no != '') {
            $query = $query->andWhere('order_t.engine_no="'.$engine_no.'"');
        }
        if($insurer1_no != '') {
            $query = $query->andWhere('order_t.insurer1_no='.$insurer1_no);
        }
        if($type_id > 0) {
            $query = $query->andWhere('gift_ticket_t_use.type_id='.$type_id);
        }

//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $items = $query->offset($offset)->limit($limit)->all();
        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $order_info = $item->order;
            $gift_info = $item->typeNew;

            $row = $item->toArray();
            $row['name'] = $gift_info->name;
            $row['car_no'] = $item->car_no;
            $row['car_frame_no'] = $order_info->car_no;
            $row['op'] = $item->op?$item->op->getShowName():'';
            $row['finished_date'] = $item->finished_date != '0000-00-00'?$item->finished_date:'';
            $row['user'] = ($item->user && $item->status > 0)?$item->user->getShowName():'';
            $row['status'] = $item->getStatus();
            $row['use_num'] = $gift_info->use_num;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionGiftUse() {
        $type_items = GiftT::find()
            ->where(['type_id'=>1,'is_delete'=>0])
            ->all();
        return $this->render('gift-use', [
            'type_items' => $type_items
        ]);
    }

    public function actionGiftUseJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $code = $request->get('code');
        $car_id = $request->get('car_id',0);
        $car_no = $request->get('car_no');
        $order_id = $request->get('order_id');
        $username = $request->get('username');
        $s_begin_date = $request->get('s_begin_date');
        $s_end_date = $request->get('s_end_date');
        $p_begin_date = $request->get('p_begin_date');
        $p_end_date = $request->get('p_end_date');
        $status = $request->get('status');
        $frame_no = $request->get('frame_no');
        $engine_no = $request->get('engine_no');
        $insurer1_no = $request->get('insurer1_no');
        $type_id = $request->get('type_id');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftTicketTUse::find()
            ->leftJoin('order_t','order_t.id=gift_ticket_t_use.order_id')
            ->leftJoin('gift_t','gift_t.id=gift_ticket_t_use.type_id')
            ->leftJoin('user_t','user_t.id=gift_ticket_t_use.user_id')
            ->where('gift_t.type_id=1')
            ->orderBy('id DESC');
        if($code != '') {
            $query->andWhere('gift_ticket_t_use.code="'.$code.'"');
        }
        if($car_id > 0) {
            $query->andWhere('order_t.car_id='.$car_id);
        }
        if($order_id > 0) {
            $query->andWhere('order_t.id='.$order_id);
        }
        if($car_no != '') {
            $query->andWhere('gift_ticket_t_use.car_no like "'.$car_no.'"');
        }
        if($username != ''){
            $user = UserT::find()->where('username="'.$username.'"')->andWhere('is_delete=0')->one();
            $query->andWhere('gift_ticket_t_use.op_id='.$user->id);
        }

        if($s_begin_date != ''){
            $query->andWhere('order_t.submit_date>="'.$s_begin_date.'"');
        }
        if($s_end_date != ''){
            $query = $query->andWhere('order_t.submit_date<="'.$s_begin_date.'"');
        }
        if($p_begin_date != ''){
            $query = $query->andWhere('order_t.print_date>="'.$p_begin_date.'"');
        }
        if($p_end_date != ''){
            $query = $query->andWhere('order_t.print_date<="'.$p_begin_date.'"');
        }

        if ($status == 1) {//礼券未使用
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=1');
        } elseif ($status == 2) {//礼券使用中
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=2');
        }
        if ($status == 3) {//礼券使用完
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=3');
        }
        if ($status == 4) {//礼品未出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=1');
        }
        if ($status == 5) {//礼品已出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=3');
        }

        if($frame_no != '') {
            $query = $query->andWhere('order_t.car_frame_no="'.$frame_no.'"');
        }
        if($engine_no != '') {
            $query = $query->andWhere('order_t.engine_no="'.$engine_no.'"');
        }
        if($insurer1_no != '') {
            $query = $query->andWhere('order_t.insurer1_no='.$insurer1_no);
        }
        if($type_id > 0) {
            $query = $query->andWhere('gift_ticket_t_use.type_id='.$type_id);
        }

//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $items = $query->offset($offset)->limit($limit)->all();
        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $order_info = $item->order;
            $gift_info = $item->typeNew;

            $row = $item->toArray();
            $row['name'] = $gift_info->name;
            $row['car_no'] = $item->car_no;
            $row['car_frame_no'] = $order_info->car_no;
            $row['op'] = $item->op?$item->op->getShowName():'';
            $row['finished_date'] = $item->finished_date != '0000-00-00'?$item->finished_date:'';
            $row['username'] = ($item->user && $item->status > 0)?$item->user->getShowName():'';
            $row['submit_user'] = $order_info->user ? $order_info->user->getShowName():'';
            $row['status'] = $item->getStatus();
            $row['use_num'] = $gift_info->use_num;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionTicketUse() {
        $type_items = GiftT::find()
            ->where(['type_id'=>2,'is_delete'=>0])
            ->all();
        return $this->render('ticket-use', [
            'type_items' => $type_items
        ]);
    }

    public function actionTicketUseJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $code = $request->get('code');
        $car_id = $request->get('car_id',0);
        $car_no = $request->get('car_no');
        $order_id = $request->get('order_id');
        $username = $request->get('username');
        $s_begin_date = $request->get('s_begin_date');
        $s_end_date = $request->get('s_end_date');
        $p_begin_date = $request->get('p_begin_date');
        $p_end_date = $request->get('p_end_date');
        $status = $request->get('status');
        $frame_no = $request->get('frame_no');
        $engine_no = $request->get('engine_no');
        $insurer1_no = $request->get('insurer1_no');
        $type_id = $request->get('type_id');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftTicketTUse::find()
            ->leftJoin('order_t','order_t.id=gift_ticket_t_use.order_id')
            ->leftJoin('gift_t','gift_t.id=gift_ticket_t_use.type_id')
            ->leftJoin('user_t','user_t.id=gift_ticket_t_use.user_id')
            ->where('gift_t.type_id=2')
            ->orderBy('id DESC');
        if($code != '') {
            $query->andWhere('gift_ticket_t_use.code="'.$code.'"');
        }
        if($car_id > 0) {
            $query->andWhere('order_t.car_id='.$car_id);
        }
        if($order_id > 0) {
            $query->andWhere('order_t.id='.$order_id);
        }
        if($car_no != '') {
            $query->andWhere('gift_ticket_t_use.car_no like "'.$car_no.'"');
        }
        if($username != ''){
            $user = UserT::find()->where('username="'.$username.'"')->andWhere('is_delete=0')->one();
            $query->andWhere('gift_ticket_t_use.op_id='.$user->id);
        }

        if($s_begin_date != ''){
            $query->andWhere('order_t.submit_date>="'.$s_begin_date.'"');
        }
        if($s_end_date != ''){
            $query = $query->andWhere('order_t.submit_date<="'.$s_begin_date.'"');
        }
        if($p_begin_date != ''){
            $query = $query->andWhere('order_t.print_date>="'.$p_begin_date.'"');
        }
        if($p_end_date != ''){
            $query = $query->andWhere('order_t.print_date<="'.$p_begin_date.'"');
        }

        if ($status == 1) {//礼券未使用
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=1');
        } elseif ($status == 2) {//礼券使用中
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=2');
        }
        if ($status == 3) {//礼券使用完
            $query = $query->andWhere('gift_t.type_id=2 and gift_ticket_t_use.status=3');
        }
        if ($status == 4) {//礼品未出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=1');
        }
        if ($status == 5) {//礼品已出库
            $query = $query->andWhere('gift_t.type_id=1 and gift_ticket_t_use.status=3');
        }

        if($frame_no != '') {
            $query = $query->andWhere('order_t.car_frame_no="'.$frame_no.'"');
        }
        if($engine_no != '') {
            $query = $query->andWhere('order_t.engine_no="'.$engine_no.'"');
        }
        if($insurer1_no != '') {
            $query = $query->andWhere('order_t.insurer1_no='.$insurer1_no);
        }
        if($type_id > 0) {
            $query = $query->andWhere('gift_ticket_t_use.type_id='.$type_id);
        }

//        echo $query->createCommand()->rawSql;exit;
        $total = $query->count();
        $items = $query->offset($offset)->limit($limit)->all();
        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $order_info = $item->order;
            $gift_info = $item->typeNew;

            $row = $item->toArray();
            $row['name'] = $gift_info->name;
            $row['car_no'] = $item->car_no;
            $row['car_frame_no'] = $order_info->car_no;
            $row['op'] = $item->op?$item->op->getShowName():'';
            $row['finished_date'] = $item->finished_date != '0000-00-00'?$item->finished_date:'';
            $row['username'] = ($item->user && $item->status > 0)?$item->user->getShowName():'';
            $row['submit_user'] = $order_info->user ? $order_info->user->getShowName():'';
            $row['status'] = $item->getStatus();
            $row['use_num'] = $gift_info->use_num;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionGiftTj() {
        return $this->render('gift-tj');
    }

    public function actionGiftTjJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $date_type = $request->get('date_type');
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftT::find()->where(['type_id'=>1, 'is_delete'=>0]);

//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $items = $query->offset($offset)->limit($limit)->all();
        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $total = $item->getTicketsUseByDate($date_type,$begin_date,$end_date)->count();
            $out_total = $item->getTicketsUseByDate($date_type,$begin_date,$end_date)->andWhere('gift_ticket_t_use.status=3')->count();

            $row = $item->toArray();
            $row['total'] = $total;
            $row['unout_total'] = $total - $out_total;
            $row['out_total'] = $out_total;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionTicketTj() {
        return $this->render('ticket-tj');
    }

    public function actionTicketTjJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $date_type = $request->get('date_type');
        $begin_date = $request->get('begin_date');
        $end_date = $request->get('end_date');
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = GiftT::find()->where(['type_id'=>2, 'is_delete'=>0]);

//        echo $query->createCommand()->rawSql;
        $total = $query->count();
        $items = $query->offset($offset)->limit($limit)->all();
        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $total = $item->getTicketsUseByDate($date_type,$begin_date,$end_date)->count();
            $use_total = $item->getTicketsUseByDate($date_type,$begin_date,$end_date)->andWhere('gift_ticket_t_use.status=3')->count();

            $row = $item->toArray();
            $row['total'] = $total;
            $row['unuse_total'] = $total - $use_total;
            $row['use_total'] = $use_total;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionGiftUseEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        if($id > 0) {
            $info = GiftTicketTUse::findOne(['id'=>$id]);
        } else {
            $info = new GiftTicketTUse();
        }



        return $this->render('gift-use-edit',[
            'info' => $info
        ]);
    }

    public function actionTicketUseEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        if($id > 0) {
            $info = GiftTicketTUse::findOne(['id'=>$id]);
        } else {
            $info = new GiftTicketTUse();
        }



        return $this->render('ticket-use-edit',[
            'info' => $info
        ]);
    }
    public function actionHistoryLogJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->get('id');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = GiftUseLogT::find()
            ->where('gift_use_id='.$id)
            ->orderBy('op_time DESC');

        $total = $query->count();

        $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['op_time'] = date('Y-m-d H:i:s', $item->op_time);
            $data['rows'][] = $row;
        }

        return $data;
    }
    public function actionUseSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id');
            $remark = $request->post('remark');

            $tran = GiftTicketTUse::getDb()->beginTransaction();
            try {
                $ticket_info = GiftTicketTUse::findOne(['id'=>$id]);
                if(!$ticket_info) {
                    $result['msg'] = '礼品券不存在!';
                    return $result;
                }

                $use_num = $ticket_info->typeNew->use_num;
                $finished_num = $ticket_info->finished_num + 1;
                $ticket_info->user_id = $this->my->id;
                $ticket_info->finished_num =  $finished_num;
                $ticket_info->finished_date =  date('Y-m-d');
                $ticket_info->use_date = date('Y-m-d H:i:s');

                if($finished_num < $use_num){
                    $ticket_info->status = 2;
                }elseif ($finished_num >= $use_num){
                    $ticket_info->status = 3;
                }

                if(!$ticket_info->save()) {
                    throw new \Exception(print_r($ticket_info->getErrors(), true));
                }

                $this->addGiftUseLog($id,'使用了一次',$remark);
                $result['success'] = true;
                $result['msg'] = '保存成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }

        }
        return $result;
    }

    public function addGiftUseLog($id,$info,$remark,$type=1)
    {
        $log_info = new GiftUseLogT();
        $log_info->gift_use_id = $id;
        $log_info->op_time = time();
        $log_info->op_man = $this->my->getShowName();
        $log_info->group_name = $this->my->group?$this->my->group->getPath():'';
        $log_info->type = $type;
        $log_info->remark = $remark;
        $log_info->info = $info;
        if(!$log_info->save()) {
            throw new \Exception(print_r($log_info->getErrors(), true));
        }
    }
}
