<?php


namespace frontend\controllers;


use common\models\CarT;
use common\models\GiftT;
use common\models\OrderGiftT;
use common\models\UserT;
use common\models\ZhongjiFanxianT;
use common\models\ZhongjiGiftT;
use common\models\ZhongjiTiaojian;
use common\models\ZhongjiUserT;
use common\models\ZhongjiYingxiao;
use yii\web\Response;
use Yii;

class MarketingStrategyController extends UserBaseController
{
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

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

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

        $query = ZhongjiYingxiao::find()
            ->where('is_delete=0')
            ->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();
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionAdd() {
        return $this->render('add');
    }

    public function actionEdit() {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $info = ZhongjiYingxiao::findOne(['id'=>$id]);

        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) {
            $op = $request->post('op', 'add');
            $name = $request->post('name');
            $begin_date = $request->post('begin_date');
            $end_date = $request->post('end_date');
            $remark = $request->post('remark');

            if($op == 'add') {
                $item = new ZhongjiYingxiao();
                $item->celuo_name = $name;
                $item->begin_date = $begin_date;
                $item->end_date = $end_date;
                $item->is_delete = 0;
                $item->remark = $remark;
                $item->save();

                $result['success'] = true;
                $result['msg'] = '保存成功';
                return $result;
            } else {
                $id = $request->post('id');
                $item = ZhongjiYingxiao::findOne(['id'=>$id]);
                if($item) {
                    $item->celuo_name = $name;
                    $item->begin_date = $begin_date;
                    $item->end_date = $end_date;
                    $item->remark = $remark;
                    $item->save();

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

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

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

        if($id == 0)
            return $result;

        $tichengTypeT = ZhongjiYingxiao::findOne(['id'=>$id]);
        if($tichengTypeT) {
            $tichengTypeT->is_delete = 1;
            $tichengTypeT->save();
        }


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

        return $result;
    }

    public function actionUsers() {
        $request = Yii::$app->request;
        $id = $request->get('id');

        return $this->render('users',['id'=>$id]);
    }

    public function actionSearchUser() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有记录';

        $key = $request->get('key');

        $data = [];
        if($key != '') {
            $items = UserT::find()->where('username like "'.$key.'%"')->all();
            foreach($items as $item) {
                $row = [];
                $row['id'] = $item->id;
                $row['name'] = $item->getShowName();
                $data[] = $row;
            }
        }
        $result['success'] = true;
        $result['users'] = $data;
        $result['msg'] = '共有'.count($items).'条记录';
        return $result;
    }

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

        $id = $request->post('id',0);
        $ids = $request->post('ids');

        foreach($ids as $user_id) {
            $item = ZhongjiUserT::findOne(['celuo_id'=>$id,'user_id'=>$user_id]);
            if(!$item) {
                $item = new ZhongjiUserT();
                $item->celuo_id = $id;
                $item->user_id = $user_id;
                $item->save();
            }
        }
        $result['success'] = true;
        $result['msg'] = '保存成功';
        return $result;
    }

    public function actionUsersRead() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有记录';

        $id = $request->get('id');

        $data = [];
        if($id > 0) {
            $items = ZhongjiUserT::find()->where('celuo_id='.$id)->all();
            foreach($items as $item) {
                if(!$item->user) continue;
                $row = [];
                $row['id'] = $item->user->id;
                $row['name'] = $item->user->getShowName();
                $data[] = $row;
            }
        }
        $result['success'] = true;
        $result['users'] = $data;
        $result['msg'] = '共有'.count($items).'条记录';
        return $result;
    }

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

        $id = $request->post('id');
        $user_id = $request->post('user_id');

        $info = ZhongjiUserT::find()
            ->where(['celuo_id'=>$id,'user_id'=>$user_id])
            ->one();
        if($info) $info->delete();
        $result['success'] = true;
        $result['msg'] = '删除成功';
        return $result;
    }

    public function actionFanxian() {
        $request = Yii::$app->request;
        $celuo_id = $request->get('celuo_id');

        return $this->render('fanxian',['celuo_id'=>$celuo_id]);
    }

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

        $celuo_id = $request->post('celuo_id',0);
        $baofei = $request->post('baofei', 0);
        $car_type_id = $request->post('car_type_id',[]);
        $company_id = $request->post('company_id', []);
        $car_use_id = $request->post('car_use_id', []);
        $type_id = $request->post('type_id', []);
        $rate = $request->post('rate', 0);
        $max_cashback = $request->post('max_cashback', 0);

        $tran = ZhongjiTiaojian::getDb()->beginTransaction();
        try {
            $tiaojian = new ZhongjiTiaojian();
            $tiaojian->baofei = floatval($baofei);
            $tiaojian->fanxian = 0;
            $tiaojian->xianzhong_one = '';
            $tiaojian->xianzhong_two = '';
            $tiaojian->car_type_id = join(',',$car_type_id);
            $tiaojian->car_use_id = join(',',$car_use_id);
            $tiaojian->company_ids = join(',',$company_id);
            $tiaojian->type_ids = join(',',$type_id);
            $tiaojian->type = 1;
            $tiaojian->celuo_id = $celuo_id;
            if(!$tiaojian->save()) {
                throw new \Exception(print_r($tiaojian->getErrors(), true));
            }
            $fanxian = new ZhongjiFanxianT();
            $fanxian->celuo_id = $celuo_id;
            $fanxian->tiaojian_id = $tiaojian->id;
            $fanxian->fanxian_rate = $rate;
            $fanxian->max_cashback = $max_cashback;
            $fanxian->save();

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

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

    public function actionFanxianRead() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有记录';

        $celuo_id = $request->get('celuo_id');

        $data = [];
        if($celuo_id > 0) {
            $items = ZhongjiFanxianT::find()->where('celuo_id='.$celuo_id)->all();
            foreach($items as $item) {
                if(!$item->tiaojian) continue;
                $row = $item->toArray();
                $row['tiaojian']['baofei'] = $item->tiaojian->baofei;

                $car_type_ids = explode(',',$item->tiaojian->car_type_id);
                $car_type_names = [];
                foreach($car_type_ids as $car_type_id) {
                    if($car_type_id == 1) $car_type_names[] = '京牌';
                    if($car_type_id == 2) $car_type_names[] = '非京牌';
                }
                $row['tiaojian']['car_type'] = join(',', $car_type_names);

                $car_use_ids = explode(',',$item->tiaojian->car_use_id);
                $car_use_names = [];
                foreach($car_use_ids as $car_use_id) {
                    if($car_use_id == 1) $car_use_names[] = '家庭自用车';
                    if($car_use_id == 2) $car_use_names[] = '党政机关、事业团体';
                    if($car_use_id == 3) $car_use_names[] = '非营业企业客车';
                    if($car_use_id == 4) $car_use_names[] = '不区分营业非营业';
                    if($car_use_id == 5) $car_use_names[] = '出租租赁';
                    if($car_use_id == 6) $car_use_names[] = '营业货车';
                    if($car_use_id == 7) $car_use_names[] = '非营业货车';
                    if($car_use_id == 8) $car_use_names[] = '城市公交';
                }
                $row['tiaojian']['car_use'] = join(',', $car_use_names);

                $company_ids = explode(',',$item->tiaojian->company_ids);
                $company_names = [];
                foreach($company_ids as $company_id) {
                    if($company_id == 1) $company_names[] = '人保';
                    if($company_id == 4) $company_names[] = '太平洋';
                    if($company_id == 7) $company_names[] = '人寿';
                    if($company_id == 8) $company_names[] = '平安';
                }
                $row['tiaojian']['company_name'] = join(',', $company_names);

                $type_ids = explode(',',$item->tiaojian->type_ids);
                $type_names = [];
                foreach($type_ids as $type_id) {
                    if($type_id == 1) $type_names[] = '新保';
                    if($type_id == 2) $type_names[] = '续保';
                }
                //条件
                $row['tiaojian']['type_name'] = join(',', $type_names);
                //礼品
                $row['gifts'] = [];
                $gifts = ZhongjiGiftT::find()
                    ->where(['fanxian_id'=>$item->id,'gift_type'=>1])
                    ->all();
                foreach($gifts as $gift) {
                    $tmp_row = [];
                    $tmp_row['id'] = $gift->id;
                    $tmp_row['gifts'] = json_decode($gift->gift_ids,true);
                    if($gift->free_type == 1) $tmp_row['free_type'] = '免费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
                    if($gift->free_type == 2) $tmp_row['free_type'] = '收费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
                    $row['gifts'][] = $tmp_row;
                }
                //礼券
                $row['quans'] = [];
                $gifts = ZhongjiGiftT::find()
                    ->where(['fanxian_id'=>$item->id,'gift_type'=>2])
                    ->all();
                foreach($gifts as $gift) {
                    $tmp_row = [];
                    $tmp_row['id'] = $gift->id;
                    $tmp_row['gifts'] = json_decode($gift->gift_ids,true);
                    if($gift->free_type == 1) $tmp_row['free_type'] = '免费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
                    if($gift->free_type == 2) $tmp_row['free_type'] = '收费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
                    $row['quans'][] = $tmp_row;
                }
                $data[] = $row;
            }
        }
        $result['success'] = true;
        $result['fanxians'] = $data;
        $result['msg'] = '共有'.count($items).'条记录';
        return $result;
    }

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

        $fanxin_id = $request->post('fanxin_id');
        $user_id = $request->post('user_id');

        $info = ZhongjiFanxianT::find()
            ->where('id='.$fanxin_id)
            ->one();
        if($info) {
            $info->tiaojian->delete();
            $items = ZhongjiGiftT::find()
                ->where(['fanxian_id'=>$info->id])
                ->all();
            foreach($items as $item) {
                $item->delete();
            }
            $info->delete();
        }
        $result['success'] = true;
        $result['msg'] = '删除成功';
        return $result;
    }

    public function actionGifts() {
        $request = Yii::$app->request;
        $celuo_id = $request->get('celuo_id');
        $fanxian_id = $request->get('fanxian_id');
        $type = $request->get('type',1);

        $items = GiftT::find()
            ->where(['type_id'=>$type])
            ->all();

        return $this->render('gifts',[
            'celuo_id'=>$celuo_id,
            'fanxian_id'=>$fanxian_id,
            'items'=>$items,
            'type' => $type
        ]);
    }

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

        $celuo_id = $request->post('celuo_id',0);
        $fanxian_id = $request->post('fanxian_id',0);
        $gift_type = $request->post('gift_type', 1);
        $free_type = $request->post('free_type', 0);
        $n = $request->post('n', 0);
        $gift_ids = $request->post('gift_ids', []);
        $gift_prices = $request->post('gift_prices', []);

        $gifts = [];
        foreach($gift_ids as $gift_id) {
            $tmp_gift = GiftT::find()->where(['id'=>$gift_id])->one();
            $row = $tmp_gift->toArray();
            $row['price'] = $gift_prices[$gift_id];
            $gifts[] = $row;
        }
        $item = new ZhongjiGiftT();
        $item->celuo_id = $celuo_id;
        $item->fanxian_id = $fanxian_id;
        $item->gift_type = $gift_type;
        $item->free_type = $free_type;
        $item->n = intval($n);
        $item->gift_ids = json_encode($gifts);
        if(!$item->save()) {
            $result['msg'] = print_r($item->getErrors(), true);
            return $result;
        }

        $result['success'] = true;
        $result['msg'] = '保存成功';
        return $result;
    }
    public function actionGiftDelete() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '删除失败';

        $id = $request->post('id');
        $celuo_id = $request->post('celuo_id');

        $info = ZhongjiGiftT::find()
            ->where(['id'=>$id,'celuo_id'=>$celuo_id])
            ->one();
        if($info) {
            $info->delete();
        }
        $result['success'] = true;
        $result['msg'] = '删除成功';
        return $result;
    }

    public function actionGetYingxiao() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有合适的策略';

        $car_id = $request->post('car_id');
        $total1_clear = $request->post('total1_clear', 0);
        $car_no = $request->post('car_no');
        $car_use_id = $request->post('car_use_id', 0);
        $company_id = $request->post('company_id', 0);

        $car_info = CarT::findOne($car_id);
        if(!$car_info) {
            $result['msg'] = '车辆信息不存在';
            return $result;
        }
        //获取自己的所有策略
        $items = ZhongjiUserT::find()
            ->where(['user_id'=>$this->my->id])
            ->all();
        $celuo_ids = [];
        foreach($items as $item) {
            $celuo_ids[] = $item->celuo_id;
        }
        $date = date('Y-m-d H:i:s');
        $query = ZhongjiYingxiao::find()
            ->where('is_delete=0 and begin_date<=:begin_date and end_date>=:end_date',[':begin_date'=>$date,':end_date'=>$date])
            ->andWhere(['in','id',$celuo_ids])
            ->orderBy('id desc');
        $yingxiao_item = $query->one();
        if(!$yingxiao_item) {
            return $result;
        }
        $items = ZhongjiTiaojian::find()
            ->where('celuo_id=:celuo_id and type=1',[':celuo_id'=>$yingxiao_item->id])
            ->andWhere(['<=','baofei', $total1_clear])
            ->all();
        $ids = [];
        $flags = [];
        foreach($items as $item) {
            //车牌
            $flags[0] = 0;
            if($item->car_type_id != '') {
                $car_type_ids = explode(',',$item->car_type_id);
                $tmp_type_id = 1;
                if(mb_substr($car_no, 0, 1, 'utf-8') != '京')
                    $tmp_type_id = 2;
                if(in_array($tmp_type_id, $car_type_ids)) {
                    $flags[0] = 1;
                } else {
                    $flags[0] = -1;
                }
            }
            //保险公司
            $flags[1] = 0;
            if($item->company_ids != '') {
                $company_ids = explode(',',$item->company_ids);
                if(in_array($company_id, $company_ids)) {
                    $flags[1] = 1;
                } else {
                    $flags[1] = -1;
                }
            }
            //车辆使用类型
            $flags[2] = 0;
            if($item->car_use_id != '') {
                $car_use_ids = explode(',',$item->car_use_id);
                if(in_array($car_use_id, $car_use_ids)) {
                    $flags[2] = 1;
                } else {
                    $flags[2] = -1;
                }
            }
            //新保、续保
            $flags[3] = 0;
            if($item->type_ids != '') {
                $type_ids = explode(',',$item->type_ids);
                $tmp_type_id = 1;
                if($car_info->is_xubao > 0)
                    $tmp_type_id = 2;
                if(in_array($tmp_type_id, $type_ids)) {
                    $flags[3] = 1;
                } else {
                    $flags[3] = -1;
                }
            }

            $flag = true;
            foreach($flags as $tmp_flag) {
                if($tmp_flag == 0) continue;
                if($tmp_flag == -1) {
                    $flag = false;
                    break;
                }
            }
            if($flag) {
                $ids[] = $item->id;
            }
        }
        if(count($ids) == 0) {
            return $result;
        }
        $result['success'] = true;
        $result['ids'] = join(',',$ids);
        $result['celuo_id'] = $yingxiao_item->id;
        return $result;
    }

    public function actionSelectFanxian() {
        $request = Yii::$app->request;
        $ids = explode(',', $request->get('ids'));

        $items = ZhongjiFanxianT::find()
            ->where(['id'=>$ids])
            ->all();

        return $this->render('select-fanxian', [
            'items' => $items
        ]);
    }

    public function actionGetFanxian() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有可选返现';

        $fanxian_id = $request->get('fanxian_id', 0);
        $fanxian_item = ZhongjiFanxianT::findOne(['id'=>$fanxian_id]);
        if($fanxian_item) {
            $result['fanxian_rate'] = $fanxian_item->fanxian_rate / 100;
            $result['max_fanxian'] = $fanxian_item->max_cashback;
        }
        $result['success'] = true;
        $result['msg'] = '获取成功';
        return $result;
    }

    public function actionGetGifts() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '没有可选项目';

        $fanxian_id = $request->get('fanxian_id', 0);
        $type = $request->get('type', 0);
        $order_id = $request->get('order_id', 0);

        $order_gift_items = OrderGiftT::find()
            ->where(['order_id'=>$order_id,'gift_type'=>$type])
            ->all();
        $order_gift_ids = [];
        $order_gift_srcs = [];
        foreach($order_gift_items as $order_gift_item) {
            $order_gift_ids[] = $order_gift_item->gift_id;
            $order_gift_srcs[$order_gift_item->gift_id] = $order_gift_item->gift_src;
        }
        $gifts = ZhongjiGiftT::find()
            ->where(['fanxian_id'=>$fanxian_id,'gift_type'=>$type])
            ->all();
        foreach($gifts as $gift) {
            $tmp_row = [];
            $tmp_row['id'] = $gift->id;
            $tmp_row['gifts'] = json_decode($gift->gift_ids,true);
            if($gift->free_type == 1) $tmp_row['free_type'] = '免费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
            if($gift->free_type == 2) $tmp_row['free_type'] = '收费模式-'.count($tmp_row['gifts']).'选'.$gift->n;
            foreach($tmp_row['gifts'] as $index => $gift_info) {
                if(in_array($gift_info['id'], $order_gift_ids)) {
                    $tmp_row['gifts'][$index]['selected'] = 1;
                    $tmp_gift = GiftT::find()->where('id='.$gift_info['id'])->one();
                    if($tmp_gift && $tmp_gift->type_id == 2) {
                        $tmp_row['gifts'][$index]['img_src'] = $order_gift_srcs[$gift_info['id']];
                    } else {
                        $tmp_row['gifts'][$index]['img_src'] = '';
                    }
                } else {
                    $tmp_row['gifts'][$index]['selected'] = 0;
                }
            }
            $result['success'] = true;
            $result['gifts'][] = $tmp_row;
        }
        return $result;
    }
}