<?php

namespace console\controllers;

use common\models\BusTicket;
use common\models\FxCommissionInfo;
use common\models\OrderMain;
use common\models\ProdCategory;
use common\util\CurlInterface;
use common\util\Util;
use yii\base\Exception;
use yii\console\Controller;

/**
 * Function Description:${CARET}
 * Function Name: CountCommissionController
 * ${PARAM_DOC}
 *
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 *
 * @author 娄梦宁
 */
class CountController extends Controller
{
    //已支付订单过了使用日期状态变成已完成
    public function actionFinish()
    {
        $order_main = new OrderMain();
        $date = date('Y-m-d');
        //获取所有已经过了使用日期的已支付订单
        $finish_order = $order_main->getFinishOrder($date);
        if ($finish_order) {
            $order_arr = explode(',', $finish_order['order_arr']);
            //修改状态，1.order_main 订单状态变为3   2.订单完成日期记录
            $upt_finish_order = $order_main->uptFinishOrder($order_arr);
            Util::addOrderLog(0,0,implode('-',$order_arr),'订单完成',6);
            file_put_contents(ROOT_PATH . '/console/log/finishorder/finishorder.log', date("Y-m-d H:i:s") . " " . $finish_order['order_arr'] . ' 状态变已完成-----今日完成订单数 ' . count($order_arr) . ' 操作成功  ' . $upt_finish_order . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents(ROOT_PATH . '/console/log/finishorder/finishorder.log', date("Y-m-d H:i:s") . " 今日无完成订单" . PHP_EOL, FILE_APPEND);
        }
    }

    public function actionOutTime()
    {
        //待支付15分钟未支付，状态变为已取消
        $order_main = new OrderMain();
        $cancel_count = $order_main->cancelOuttimeOrder();
        if ($cancel_count > 0) {
            file_put_contents(ROOT_PATH . '/console/log/outtimeorder/' . date('Y-m-d') . '.log', date("Y-m-d H:i:s") . '订单取消' . $cancel_count . PHP_EOL, FILE_APPEND);
        }
    }


    //已完成三天的订单佣金从待结算变成已结算
    public function actionCommission()
    {
        $fx_commission_info = new FxCommissionInfo();
        $result = $fx_commission_info->finishCommission();
        file_put_contents(ROOT_PATH . '/console/log/commission/commission.log', date("Y-m-d H:i:s") . '可结算订单编号 ' . $result['order_list'] . '  佣金结算数 ' . $result['count'] . ' 操作用户数' . $result['cnt'] . PHP_EOL, FILE_APPEND);
    }

    /**
     * Des:更新门票数据
     * Name: actionUptTicket
     * @author 倪宗锋
     */
    public function actionUptEntranceTicket()
    {
        $siteConfig = Util::getSiteConfig();
        $add_order_str = '';
        $del_order_str = '';
        $prod_category = new ProdCategory();
        //0.查当前数据库的巴士信息
        $ticket_arr = $prod_category->getEntranceTicket();
        //1.cs查票种信息，存缓存
        $time = time();
        $send_data = [
            'auth_code' => Util::authCodeForCs($time),
            'user_key' => $siteConfig['adm_user_key'],
            'user' => $siteConfig['adm_user'],
            'user_id' => $siteConfig['adm_user_id'],
            'request_time' => $time,
            'action' => 'gate_ticket_all',
            'ticket_type' => 'bus'
        ];
        $curlInterface = new CurlInterface($send_data, 4);
        $curlInterface->setBaseUrl('');
        $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/api/nfx', 'POST');
        if ($ticket_arr_cs['code'] == 0) {
            //新产品则添加
            $new_bus_arr_add = array_diff_key($ticket_arr_cs['list'], $ticket_arr);//新增的票
            foreach ($new_bus_arr_add as $key => $val) {
                $add_order_str .= ',' . $key;
            }
            if ($new_bus_arr_add) {
                $istBusTicket = $prod_category->addEntranceTicketFormCs($new_bus_arr_add);
                if (!$istBusTicket) {
                    file_put_contents(ROOT_PATH . '/console/log/busticket/entranceTicket.log', date("Y-m-d H:i:s") . '新增票种失败' . PHP_EOL, FILE_APPEND);
                }
            };
            //不再使用的产品则删除
            $new_bus_arr_del = array_diff_key($ticket_arr, $ticket_arr_cs['list']);//取消售卖的票
            foreach ($new_bus_arr_del as $key => $val) {
                $del_order_str .= ',' . $key;
            }
            if ($new_bus_arr_del) {
                $delBusTicket = $prod_category->delEntranceTicketFormCs($new_bus_arr_del);
                if (!$delBusTicket) {
                    file_put_contents(ROOT_PATH . '/console/log/busticket/entranceTicket.log', date("Y-m-d H:i:s") . '删除票种失败' . PHP_EOL, FILE_APPEND);
                }
            } else {
                file_put_contents(ROOT_PATH . '/console/log/busticket/entranceTicket.log', date("Y-m-d H:i:s") . '无取消票种' . PHP_EOL, FILE_APPEND);
            }
//            //重新激活产品
//            $new_bus_arr_inter = array_intersect_key($ticket_arr, $ticket_arr_cs['list']);//取消售卖的票
//            if (count($new_bus_arr_inter) >= 1) {
//                $prod_category->interEntranceTicketFormCs($new_bus_arr_inter);
//            }
        } else {
            file_put_contents(ROOT_PATH . '/console/log/busticket/entranceTicket.log', date("Y-m-d H:i:s") . '接口错误' . PHP_EOL, FILE_APPEND);
        }
        file_put_contents(ROOT_PATH . '/console/log/busticket/entranceTicket.log', date("Y-m-d H:i:s") . '更新完成，今日新增票种' . $add_order_str . '  今日删除票种' . $del_order_str . PHP_EOL, FILE_APPEND);

    }


    /**
     * Function Description:定时同步巴士数据
     * Function Name: actionUptBus
     *
     *
     * @author 娄梦宁
     */
    public function actionUptBus()
    {
        $siteConfig = Util::getSiteConfig();
        $add_order_str = '';
        $del_order_str = '';
        $bus_ticket = new BusTicket();
        //0.查当前数据库的巴士信息
        $ticket_arr = $bus_ticket->getBusArr();
        //1.cs查票种信息，存缓存
        $time = time();
        $send_data = [
            'auth_code' => Util::authCodeForCs($time),
            'user_key' => $siteConfig['adm_user_key'],
            'user' => $siteConfig['adm_user'],
            'user_id' => $siteConfig['adm_user_id'],
            'request_time' => $time,
            'action' => 'get_ticket_array',
            'ticket_type' => 'bus'
        ];
        $curlInterface = new CurlInterface($send_data, 4);
        $curlInterface->setBaseUrl('');
        $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/api/nfx', 'POST');
        //2.比较新数据和缓存的差集
        if ($ticket_arr_cs['code'] == 0) {
            //新增售卖票种
            $new_bus_arr_add = array_diff_key($ticket_arr_cs['data'], $ticket_arr);//新增的票
            foreach ($new_bus_arr_add as $key => $val) {
                $add_order_str .= ',' . $key;
            }
            if ($new_bus_arr_add) {
                $istBusTicket = $bus_ticket->istBusTicket($new_bus_arr_add);
                if (!$istBusTicket) {
                    file_put_contents(ROOT_PATH . '/console/log/busticket/busticket.log', date("Y-m-d H:i:s") . '新增票种失败' . PHP_EOL, FILE_APPEND);
                }
            };
            //取消售卖票种
            $new_bus_arr_del = array_diff_key($ticket_arr, $ticket_arr_cs['data']);//取消售卖的票
            foreach ($new_bus_arr_del as $key => $val) {
                $del_order_str .= ',' . $key;
            }
            if ($new_bus_arr_del) {
                $delBusTicket = $bus_ticket->delBusTicket($new_bus_arr_del);
                if (!$delBusTicket) {
                    file_put_contents(ROOT_PATH . '/console/log/busticket/busticket.log', date("Y-m-d H:i:s") . '删除票种失败' . PHP_EOL, FILE_APPEND);
                }
            } else {
                file_put_contents(ROOT_PATH . '/console/log/busticket/busticket.log', date("Y-m-d H:i:s") . '无取消票种' . PHP_EOL, FILE_APPEND);
            }
//            //重新激活产品
//            if (count($ticket_arr_cs['data']) >= 1) {
//                $bus_ticket->updateBus($ticket_arr_cs['data']);
//            }
        } else {
            file_put_contents(ROOT_PATH . '/console/log/busticket/busticket.log', date("Y-m-d H:i:s") . '接口错误' . PHP_EOL, FILE_APPEND);
        }
        file_put_contents(ROOT_PATH . '/console/log/busticket/busticket.log', date("Y-m-d H:i:s") . '更新完成，今日新增票种' . $add_order_str . '  今日删除票种' . $del_order_str . PHP_EOL, FILE_APPEND);
    }

    /**
     * Des:每日设置产品销售量
     * Name: actionSetSaleCnt
     * @return string
     * @author 倪宗锋
     */
    public function actionSetSaleCnt()
    {
        $day = date('d');
        $prodCate = new ProdCategory();
        $flag = $prodCate->setSaleCnt($day);
        if ($flag) {
            $msg = '更新产品销售量成功';
        } else {
            $msg = '更新产品销售量失败';
        }
        file_put_contents(ROOT_PATH . '/console/log/busticket/setSalCnt.log', date("Y-m-d H:i:s") . $msg . PHP_EOL, FILE_APPEND);
        return $msg;
    }

    public function actionUpLineProd()
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            /**将品类表不存在的线路插入产品品类表*/
            $sql = '' . "INSERT INTO `prod_category` (`pro_cate_name`, `category_id`, `commission`,`create_time`, `sign`, show_price, bus_ticket_id,bus_line_type)
            SELECT a.line_name,1,5,NOW(),a.line_id,a.price,a.ticket_id,a.line_type
            from (
            SELECT  line_id,line_name,MAX(prod_price) price,ticket_id,line_type
            from bus_ticket
            WHERE line_type in (255,256)
            GROUP BY line_id
            ) a
            LEFT JOIN prod_category b on a.line_id = b.sign and b.category_id=1
            where b.pro_cate_id is NULL;";
            \Yii::$app->getDb()->createCommand($sql)->execute();
            /**将产品品类表存在，产品表没有产品的添加产品*/
            $sql1 = '' . "INSERT INTO `prod_main` ( `prod_cate_id`, `prod_name`, `prod_price`,  `create_time`)
            SELECT a.pro_cate_id,'成人票',a.show_price,NOW()
            from prod_category a
            left JOIN prod_main b on a.pro_cate_id = b.prod_cate_id
            WHERE a.sign != '' and a.category_id = 1 and b.prod_id is NULL
            UNION ALL
            SELECT a.pro_cate_id,'儿童票',a.show_price,NOW()
            from prod_category a
            left JOIN prod_main b on a.pro_cate_id = b.prod_cate_id
            WHERE a.sign != '' and a.category_id = 1 and b.prod_id is NULL;";
            \Yii::$app->getDb()->createCommand($sql1)->execute();
            /**更新所有线路的产品状态*/
            $sql2 = '' . "UPDATE
             prod_category a
            LEFT JOIN
            (
                SELECT  line_id,line_name,MAX(prod_price) price
                from bus_ticket
                WHERE line_type in (255,256)
                GROUP BY line_id
            ) b on b.line_id = a.sign
            set a.delete_flag = if(b.line_id is null,1,0)
            where a.sign != '' and a.category_id = 1 ;
            ";
            \Yii::$app->getDb()->createCommand($sql2)->execute();
            $transaction->commit();
            file_put_contents(ROOT_PATH . '/console/log/busticket/busticketLine.log', date("Y-m-d H:i:s") . '同步成功！' . PHP_EOL, FILE_APPEND);
            return 'success';
        } catch (Exception $e) {
            $transaction->rollBack();
            file_put_contents(ROOT_PATH . '/console/log/busticket/busticketLine.log', date("Y-m-d H:i:s") . '同步失败！' . PHP_EOL, FILE_APPEND);
            return 'fail';
        }
    }
}
