<?php
namespace backendApi\modules\v1\models\lists\shop;

use common\helpers\Cache;
use common\helpers\Tool;
use common\helpers\user\Info;
use common\libs\dataList\DataListInterface;
use common\models\ApproachOrder;
use common\models\ApproachOrderGoods;
use common\models\Order;
use common\models\OrderGoods;
use common\models\ShopGoods;
use common\models\User;
use common\libs\dataList\column\DateTime;
use yii\data\Pagination;
use yii\db\Query;

class OrderList extends \common\libs\dataList\DataList implements DataListInterface
{
    /**
     * 列表名称
     * @return string
     */
    public function getListName(){
        return '订单列表';
    }

    /**
     * 列表筛选到的数据
     */
    public function dataHandle()
    {
        $this->listData = Order::lists($this->condition, $this->params, [
            'select' => 'O.*,U.REAL_NAME,U.DEC_ID,OG.*',
            'orderBy' => 'O.CREATED_AT DESC, O.ID DESC',
            'from' => Order::tableName() . ' AS O',
            'join' => [
                ['LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN'],
                ['LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID'],
            ],
            'page' => $this->page,
            'pageSize' => $this->pageSize,
        ]);
        foreach ($this->listData['list'] as $key => $value) {
            $CREATE_USER_ID = Info::getUserIdByUserName($value['CREATE_USER']);
            $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getUserNameByUserId($value['DEC_ID']);
            $this->listData['list'][$key]['CREATE_USER_NAME'] = Info::getUserRealNameByUserId($CREATE_USER_ID);
//            $this->listData['list'][$key]['GOODS_NO'] = '';
        }
    }

    /**
     * 列表筛选到的数据
     */
//    public function dataHandle()
//    {
//        $orderQuery = Order::find()
//            ->alias('O')
//            ->where($this->condition, $this->params)
//            ->select('O.*,U.REAL_NAME,U.DEC_ID,OG.REAL_PRICE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
//            ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
//            ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
//            ->orderBy('O.CREATED_AT DESC');
//
//        // 订单中间表只查询待支付和支付失败的订单
//        $this->params[':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value'];   // 待支付
//        $this->params[':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value'];   // 支付失败
//        $orderStandardQuery = ApproachOrder::find()
//            ->alias('O')
//            ->where($this->condition . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params)
//            ->select('O.*,U.REAL_NAME,U.DEC_ID,OG.REAL_PRICE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
//            ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
//            ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
//            ->orderBy('O.CREATED_AT DESC');
//
//        $queryAll = $orderQuery->union($orderStandardQuery, true);
//        $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
//
//        $totalCount = $query->count();
//        $pagination = new Pagination(['totalCount' => $totalCount, 'pageSize' => \Yii::$app->request->get('pageSize')]);
//        $lists = $query->offset($pagination->offset)->limit($pagination->limit)->all();
//
//        $this->listData = [
//            'list' => $lists,
//            'currentPage'=>$pagination->page,
//            'totalPages'=>$pagination->pageCount,
//            'startNum' => $pagination->page * $pagination->pageSize + 1,
//            'totalCount' => $pagination->totalCount,
//            'pageSize' => $pagination->pageSize,
//        ];
//
//        foreach ($this->listData['list'] as $key => $value) {
//            $CREATE_USER_ID = Info::getUserIdByUserName($value['CREATE_USER']);
//            $this->listData['list'][$key]['DEC_USER_NAME'] = Info::getUserNameByUserId($value['DEC_ID']);
//            $this->listData['list'][$key]['CREATE_USER_NAME'] = Info::getUserRealNameByUserId($CREATE_USER_ID);
//        }
//    }

    /**
     * 要展示和导出的所有字段
     * @return array
     */
    public function getColumn(){
        $regionConfig = Cache::getRegionConfig();
        if(!$this->columns){
            $this->columns = [
                'ID' => null,
                'DEC_SN' => null,
                'USER_NAME' => [
                    'header' => '会员编号',
                    'headerOther' => ['width' => '120'],
                ],
                'DEC_USER_NAME' => [
                    'header' => '报单中心',
                    'headerOther' => ['width' => '120'],
                ],
                'CREATE_USER' => [
                    'header' => '创建人编号',
                    'headerOther' => ['width' => '120'],
                ],
                'CREATE_USER_NAME' => [
                    'header' => '创建人姓名',
                    'headerOther' => ['width' => '120'],
                ],
                'SN' => [
                    'header' => '订单号',
                    'headerOther' => ['width' => '200'],
                ],
                'STATUS' => null,
                'STATUS_NAME' => [
                    'header' => '订单状态',
                    'headerOther' => [
                        'width' => '110',
                    ],
                    'value' => function ($row) {
                        return \Yii::$app->params['orderStatus'][$row['STATUS']]['label'] ?? '';
                    },
                ],
                'SKU_CODE' => [
                    'header' => '存货编码',
                    'headerOther' => ['width' => '150'],
                ],
                'GOODS_TITLE' => [
                    'header' => '存货名称',
                    'headerOther' => ['width' => '200'],
                ],
                'BUY_NUMS' => [
                    'header' => '数量',
                    'headerOther' => ['width' => '100'],
                ],
                'CONSIGNEE' => [
                    'header' => '收货人',
                    'headerOther' => [
                        'width' => '150',
                    ],
                ],
                'MOBILE' => [
                    'header' => '联系方式1',
                    'headerOther' => [
                        'width' => '150',
                    ],
                ],
                'TEL' => [
                    'header' => '联系方式2',
                ],
                'PROVINCE' => [
                    'header' => '省',
                    'headerOther' => ['width' => '120'],
                    'value' => function ($row) use($regionConfig) {
                        return $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
                    },
                ],
                'CITY' => [
                    'header' => '市',
                    'headerOther' => ['width' => '120'],
                    'value' => function ($row) use($regionConfig) {
                        return $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
                    },
                ],
                'COUNTY' => [
                    'header' => '区',
                    'headerOther' => ['width' => '120'],
                    'value' => function ($row) use($regionConfig) {
                        return $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
                    },
                ],
//                'AREA' => [
//                    'header' => '地区',
//                    // 用于导出
//                    'value' => function($row) use($regionConfig) {
//                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
//                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
//                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
//                        return $province.$city.$county;
//                    },
//                    // 用于前台显示
//                    'showValue' => function($row) {
//                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
//                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
//                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
//                        return '<div class="addr" title='.$province.$city.$county.'>'.$province.$city.$county.'</div>';
//                    },
//                    'headerOther' => [
//                        'width' => '200'
//                    ],
//                ],
                'ADDRESS' => [
                    'header' => '详细地址',
                    'headerOther' => [
                        'width' => '300',
                    ],
                ],
                'PERIOD_NUM' => [
                    'header' => '期数',
                ],
                'ORDER_TYPE' => [
                    'header' => '订单类型',
                    'headerOther' => ['width' => '120'],
                    'value' => function ($row) {
                            if($row['ORDER_TYPE']=='ZC'){
                                $orderType = '首单';
                            }else{
//                                $orderType = ($row['PAY_TYPE']=='cash') ? '重消' : '积分';
                                $orderType = '复消';
                            }
                        return $orderType;
                    },
                ],
                'PAY_TYPE' => [
                    'header' => '支付方式',
                    'value' => function ($row) {
                        return ShopGoods::payTypes()[$row['PAY_TYPE']]['name'] ?? '';
                    },
                    'headerOther' => ['width' => '120'],
                ],
                'IS_AUTO' => [
                    'header' => 'Is Auto', // 是否自动
                    'value' => function ($row) {
                        switch ($row['IS_AUTO']) {
                            case 1:
                                return 'Yes';
                            case 0:
                                return 'No';
                        }
                    },
                ],
                'WAREHOUSE' => [
                    'header' => '发货仓',
                ],
                'CREATED_AT' => [
                    'header' => '创建时间',
                    'value' => function ($row) {
                        return (new DateTime([
                            'value' => $row['CREATED_AT'],
                        ]))->result();
                    },
                    'headerOther' => ['width' => '190'],
                ],
                'PAY_AT' => [
                    'header' => '支付时间',
                    'value' => function ($row) {
                        return (new DateTime([
                            'value' => $row['PAY_AT'],
                        ]))->result();
                    },
                    'headerOther' => ['width' => '190'],
                ],
                'SEND_AT' => [
                    'header' => '推送时间',
                    'headerOther' => ['width' => '190'],
                ],
                'DELIVERY_AT' => [
                    'header' => '发货时间',
                    'value' => function ($row) {
                        return (new DateTime([
                            'value' => $row['DELIVERY_AT'],
                        ]))->result();
                    },
                    'headerOther' => ['width' => '190'],
                ],
                'REAL_PRICE' => [
                    'header' => '商品单价',
                    'headerOther' => [
                        'width' => '150',
                    ],
                    'value' => function ($row) {
                        return Tool::formatPrice($row['REAL_PRICE']);
                    },
                    'valueOther' => function ($row) {
                        return [
                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
                        ];
                    },
                ],
                'REAL_PV' => [
                    'header' => '商品PV',
                    'headerOther' => [
                        'width' => '150',
                    ],
                    'value' => function ($row) {
                        return Tool::formatPrice($row['REAL_PV']);
                    },
                    'valueOther' => function ($row) {
                        return [
                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
                        ];
                    },
                ],
                'PAY_FREIGHT' => [
                    'header' => '运费',
                    'headerOther' => [
                        'width' => '150',
                    ],
                    'value' => function ($row) {
                        return Tool::formatPrice($row['FREIGHT']);
                    },
                    'valueOther' => function ($row) {
                        return [
                            'tag' => ['type' => 'danger', 'size' => 'small', 'class' => 'no-border']
                        ];
                    },
                ],
                'EXPRESS_COMPANY' => [
                    'header' => '快递公司',
                    'headerOther' => ['width' => '150'],
                ],
                'ORDER_TRACK_NO' => [
                    'header' => '快递单号',
                    'headerOther' => ['width' => '200'],
                ],
                'EXPRESS_TYPE' => [
                    'header' => '发货方式',
                    'headerOther' => ['width' => '150'],
                    'value' => function ($row) {
                        return $row['EXPRESS_TYPE']==0 ? '邮寄' : '自提';
                    },
                ],
                'FRONT_REMARK' => [
                    'header' => '会员备注',
                    'headerOther' => [
                        'width' => '200',
                    ],
                    'value' => function ($row) {
                        return $row['FRONT_REMARK'];
                    },
                    'showValue' => function ($row) {
                        return '<div title="'.$row['FRONT_REMARK'].'" style="width:180px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'.$row['FRONT_REMARK'].'</div>';
                    },
                ],
                'DELIVERY_STATUS' => null,
                'DELIVERY_STATUS_NAME' => [
                    'header' => '发货状态',
                    'headerOther' => [
                        'width' => '110',
                    ],
                    'value' => function ($row) {
                        return \Yii::$app->params['deliveryStatus'][$row['DELIVERY_STATUS']]['label'] ?? '';
                    },
                ],
            ];
        }
        return $this->columns;
    }

    /**
     * 前台用于筛选的类型集合
     * @return mixed
     */
    public function getFilterTypes()
    {
        if(!$this->filterTypes){
            $this->filterTypes = [
                'SN'=> ['name'=> '订单编号'],
                'USER_NAME'=> ['name'=> '会员编号'],
                'MOBILE'=> ['name'=> '联系方式1'],
                'PERIOD_NUM'=> ['name'=> '期数'],
                'CREATED_AT'=> ['name'=> '创建时间', 'other'=>'date'],
                'IS_AUTO' => [
                    'name'=>'自动',
                    'other'=> 'select',
                    'selectData'=> [
                        ['id'=>1, 'name'=>'是'],
                        ['id'=>0, 'name'=>'否'],
                    ]
                ],
                'PAY_TYPE' => [
                    'name'=>'支付方式',
                    'other'=> 'select',
                    'selectData'=> [
                        ['id' => 'cash', 'name' => '充值账户'],
                        ['id' => 'exchange', 'name' => '兑换点数'],
                        ['id' => 'points', 'name' => '复消积分'],
                        ['id' => 'online', 'name' => 'IPay88'],
                        ['id' => 'wechat', 'name' => '微信'],
                        ['id' => 'alipay', 'name' => '支付宝'],
                    ]
                ],
            ];
        }
        return $this->filterTypes;
    }
}