<?php
/**
 *
 */
include_once(SERVER_ROOT."/model/mBase.php");


class mOrder extends mBase {
    private $obj;
    private $order;

    // 订单编号
    public $order_sn = '';

    // 发货状态,枚举值:1:待发货,2:已发货待签收,3:已签收
    public $order_status = 0;

    // 退款状态,枚举值:1:无售后或售后关闭,2:售后处理中,3:退款中,4: 退款成功
    public $refund_status = 0;

    // 售后状态 0:无售后 2:买家申请退款,待商家处理 3:退货退款,待商家处理 4:商家同意退款,退款中 5:平台同意退款,退款中 6:驳回退款,待买家处理 7:已同意退货退款,待用户发货 8:平台处理中 9:平台拒绝退款,退款关闭 10:退款成功 11:买家撤销 12:买家逾期未处理,退款失败 13:买家逾期,超过有效期 14:换货补寄待商家处理 15:换货补寄待用户处理 16:换货补寄成功 17:换货补寄失败 18:换货补寄待用户确认完成 21:待商家同意维修 22:待用户确认发货 24:维修关闭 25:维修成功 27:待用户确认收货 31:已同意拒收退款,待用户拒收 32:补寄待商家发货
    public $after_sales_status = 0;

    // 支付金额(元)支付金额=商品金额-折扣金额+邮费+服务费
    public $pay_amount = 0;

    // 支付时间
    public $pay_time = '';

    // 商品编号
    public $goods_id = '';

    // 商品规格编码
    public $sku_id = '';

    // 商品销售价格
    public $goods_price = 0;

    // 商品数量
    public $goods_count = 0;

    // 催发货时间
    public $urge_shipping_time = '';

    // 订单承诺发货时间
    public $last_ship_time = '';

    // 买家留言信息
    public $buyer_memo = '';

    public function __construct() {
        $this->obj = new dOrder();
        $this->order = 'order_list';
    }

    public function addOrder($shop_id, $uid) {
        $data = array();
        $data['shop_id'] = $shop_id;
        $data['uid'] = $uid;

        $data['order_status'] = $this->order_status;
        $data['refund_status'] = $this->refund_status;
        $data['after_sales_status'] = $this->after_sales_status;
        $data['pay_amount'] = $this->pay_amount;
        $data['pay_time'] = $this->pay_time;
        $data['goods_id'] = $this->goods_id;
        $data['sku_id'] = $this->sku_id;
        $data['goods_price'] = $this->goods_price;
        $data['goods_count'] = $this->goods_count;

        if ($this->urge_shipping_time) $data['urge_shipping_time'] = $this->urge_shipping_time;
        if ($this->last_ship_time) $data['last_ship_time'] = $this->last_ship_time;
        if ($this->buyer_memo) $data['$buyer_memo'] = $this->buyer_memo;

        $info = $this->getOrderBySn($this->order_sn);
        if ($info) {
            $res = $this->updateOrderBySn($this->order_sn, $data);
            if (!$res) {
                $this->setError('更新订单信息失败');
                return false;
            }
            return $info['id'];
        }

        $data['order_sn'] = $this->order_sn;

        return $this->obj->insert($this->order, $data);
    }

    public function getOrderBySn($order_sn) {
        return $this->obj->select($this->order, array('sql'=>'`order_sn`=?', 'vals'=>array($order_sn)));
    }

    public function updateOrderBySn($order_sn, $data) {
        return $this->obj->update($this->order, $data, array('sql'=>'`order_sn`=?', 'vals'=>array($order_sn)));
    }

    public function getOrdersCount($uid, $shop_id, $order_status=0, $refund_status=0, $after_sales_status=0, $pay_stime='', $pay_etime='', $urge_stime='', $urge_etime='', $last_ship_stime='', $last_ship_etime='') {
        $where = array('sql'=>'1=1');

        if ($uid) {
            $where['sql'] .= ' and `uid`=?';
            $where['vals'][] = $uid;
        }

        if ($shop_id) {
            $where['sql'] .= ' and `shop_id`=?';
            $where['vals'][] = $shop_id;
        }

        if ($order_status) {
            $where['sql'] .= ' and `order_status`=?';
            $where['vals'][] = $order_status;
        }

        if ($refund_status) {
            $where['sql'] .= ' and `refund_status`=?';
            $where['vals'][] = $refund_status;
        }

        if ($after_sales_status) {
            $where['sql'] .= ' and `after_sales_status`=?';
            $where['vals'][] = $after_sales_status;
        }

        if ($pay_stime) {
            $where['sql'] .= ' and `pay_time`>=?';
            $where['vals'][] = $pay_stime;
        }

        if ($pay_etime) {
            $where['sql'] .= ' and `pay_time`<=?';
            $where['vals'][] = $pay_etime;
        }

        if ($urge_stime) {
            $where['sql'] .= ' and `urge_shipping_time`>=?';
            $where['vals'][] = $urge_stime;
        }

        if ($urge_etime) {
            $where['sql'] .= ' and `urge_shipping_time`<=?';
            $where['vals'][] = $urge_etime;
        }

        if ($last_ship_stime) {
            $where['sql'] .= ' and `last_ship_time`>=?';
            $where['vals'][] = $last_ship_stime;
        }

        if ($last_ship_etime) {
            $where['sql'] .= ' and `last_ship_time`<=?';
            $where['vals'][] = $last_ship_etime;
        }

        return $this->obj->count($this->order, $where);
    }

    public function getOrderList($uid, $shop_id, $order_status=0, $refund_status=0, $page=1, $pagesize=100) {
        $where = array('sql'=>'1=1');

        if ($uid) {
            $where['sql'] .= ' and `uid`=?';
            $where['vals'][] = $uid;
        }

        if ($shop_id) {
            $where['sql'] .= ' and `shop_id`=?';
            $where['vals'][] = $shop_id;
        }

        if ($order_status) {
            $where['sql'] .= ' and `order_status`=?';
            $where['vals'][] = $order_status;
        }

        if ($refund_status) {
            $where['sql'] .= ' and `refund_status`=?';
            $where['vals'][] = $refund_status;
        }

        $start = ($page - 1) * $pagesize;
        return $this->obj->selectAll($this->order, $where, 'pay_time desc', array($start, $pagesize));
    }

    public function getWaitDeliverOrderList($uid, $shop_id, $page=1, $pagesize=100) {
        $where = array(
            'sql'   =>  '`uid`=? and `shop_id`=? and `order_status`=? and `refund_status`=?',
            'vals'  =>  array($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES)
        );
        $start = ($page - 1) * $pagesize;
        return $this->obj->selectAll($this->order, $where, 'urge_shipping_time desc', array($start, $pagesize));
    }

    public function getNotFinishedOrders() {
        return $this->obj->selectAll($this->order, array('sql'=>'`order_status`!=? and `refund_status`!=?', 'vals'=>array(ORDER_STATUS_SIGNED_FOR, REFUND_STATUS_SUCC)));
    }

//     public function getLastThirtyDaysOrderNum($uid, $shop_id) {
//         $start_date = date("Y-m-d", strtotime("-30 day"));

//         $sql = "select DATE_FORMAT(`pay_time`,'%Y-%m-%d') sale_day, count(*) as count from {$this->order} where `uid`={$uid} and `shop_id`={$shop_id} and `pay_time`>='{$start_date}' group by sale_day order by sale_day asc";
//         $list = $this->obj->execute($sql, true, true);
//         if (!$list) return array();

//         $date2count = array();
//         foreach ($list as $info) {
//             $date2count[$info['sale_day']] = $info['count'];
//         }

//         unset($list);

//         return $date2count;
//     }

    public function addOrders($order_list, $shop_id, $uid) {
        $goods_list = array();

        foreach ($order_list as $order) {
            $this->writeLog('kuaileorder', 'orderinfo.log', json_encode($order));

            $this->order_sn = $order['order_sn'];
            $this->order_status = $order['order_status'];
            $this->refund_status = $order['refund_status'];
            $this->after_sales_status = $order['after_sales_status'];
            $this->pay_amount = $order['pay_amount'];
            $this->pay_time = $order['pay_time'];
            $this->goods_id = $order['item_list'][0]['goods_id'];
            $this->sku_id = $order['item_list'][0]['sku_id'];
            $this->goods_price = $order['item_list'][0]['goods_price'];
            $this->goods_count = $order['item_list'][0]['goods_count'];
            $this->urge_shipping_time = $order['urge_shipping_time'];
            $this->last_ship_time = $order['last_ship_time'];
            $this->buyer_memo = $order['buyer_memo'];

            $this->addOrder($shop_id, $uid);

            $g = array();
            $g['goods_id'] = $order['item_list'][0]['goods_id'];
            $g['goods_name'] = $order['item_list'][0]['goods_name'];
            $g['goods_price'] = $order['item_list'][0]['goods_price'];
            $g['sku_id'] = $order['item_list'][0]['sku_id'];
            $g['sku_name'] = $order['item_list'][0]['goods_spec'];
            $g['shop_id'] = $shop_id;
            $g['uid'] = $uid;

            $goods_list[] = $g;
        }

        $gobj = new mGoods();
        foreach ($goods_list as $goods) {
            $gobj->addGoods($goods['goods_id'], $goods['goods_name'], $goods['goods_price'], $goods['sku_id'], $goods['sku_name'], $goods['shop_id'], $goods['uid']);
        }

        return true;
    }

    public function getTodayData($uid, $shop_id) {
        $stime = date("Y-m-d").' 00:00:00';
        $etime = date("Y-m-d").' 23:59:59';

        $data = array();

        // 催发订单
        $data['urge_order_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES, 0, '', '', $stime, $etime)+0;

        // 倒计时订单(12h)
        $data['countdown_order_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES, 0, '', '', '', '', $stime, date("Y-m-d H:i:s", strtotime('-12 h')))+0;

        // 待发货订单
        $data['wait_deliver_goods_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES, 0, $stime, $etime)+0;

        // 平台介入中
        $data['platform_processing_count'] = $this->getOrdersCount($uid, $shop_id, 0, 0, AFTER_SALES_STATUS_PLATFORM_PROCESSING, $stime, $etime)+0;

        // 待售后订单
        $data['wait_after_sale_count'] = $this->getOrdersCount($uid, $shop_id, 0, 0, AFTER_SALES_STATUS_BUYER_APPLIES_FOR_REFUND, $stime, $etime)+0;

        return $data;
    }

    public function getToalData($uid, $shop_id) {
        $data = array();

        // 催发订单
        $data['total_urge_order_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES, 0, '', '', '2022-01-01')+0;

        // 倒计时订单(12h)
        $data['total_countdown_order_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES, 0, '', '', '', '', '', '', date("Y-m-d H:i:s", strtotime('-12 h')))+0;

        // 待发货订单
        $data['total_wait_deliver_goods_count'] = $this->getOrdersCount($uid, $shop_id, ORDER_STATUS_WAIT_DELIVER_GOODS, REFUND_STATUS_NO_AFTER_SALES)+0;

        // 平台介入中
        $data['total_platform_processing_count'] = $this->getOrdersCount($uid, $shop_id, 0, 0, AFTER_SALES_STATUS_PLATFORM_PROCESSING)+0;

        // 待售后订单
        $data['total_wait_after_sale_count'] = $this->getOrdersCount($uid, $shop_id, 0, 0, AFTER_SALES_STATUS_BUYER_APPLIES_FOR_REFUND)+0;

        return $data;
    }

    public function getSumData($uid, $shop_id, $day=7) {
        $end_time = date("Y-m-d").' 23:59:59';

        $dates = array();

        if ($day == 7) {
            $start_time = date("Y-m-d", strtotime('-6 day')).' 00:00:00';

            for ($i=0;$i<7;$i++) {
                $dates[] = date("Y-m-d", strtotime('-'.$i.' day'));
            }

            $sql = 'select IFNULL(sum(`pay_amount`), 0) as sumgroup,DATE_FORMAT(`pay_time`,"%Y-%m-%d") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m-%d")';

        } elseif ($day == 30) {
            $start_time = date("Y-m-d", strtotime('-29 day')).' 00:00:00';
            for ($i=0;$i<29;$i++) {
                $dates[] = date("Y-m-d", strtotime('-'.$i.' day'));
            }

            $sql = 'select sum(`pay_amount`) as sumgroup,DATE_FORMAT(`pay_time`,"%Y-%m-%d") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and  `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m-%d")';

        } elseif ($day == 365) {
            $start_time = date("Y-m-d", strtotime('-1 year')).' 00:00:00';

            for ($i=0;$i<12;$i++) {
                $dates[] = date("Y-m", strtotime('-'.$i.' month'));
            }

            $sql = 'select sum(`pay_amount`) as sumgroup,DATE_FORMAT(`pay_time`,"%Y-%m") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m")';

        }

        $res = $this->obj->execute($sql, true, true);
        if (!$res) return array();

        $date2sum = array();
        foreach ($res as $info) {
            $date2sum[$info['dategroup']] = $info['sumgroup'];
        }

        $dates = array_reverse($dates);

        $data = array();
        foreach ($dates as $date) {
            $data[$date] = $date2sum[$date] ? $date2sum[$date] : 0;
        }

        unset($res);
        unset($date2sum);

        return $data;
    }

    public function getRefundCountData($uid, $shop_id, $day=7) {
        $end_time = date("Y-m-d").' 23:59:59';

        $dates = array();

        if ($day == 7) {
            $start_time = date("Y-m-d", strtotime('-6 day')).' 00:00:00';

            for ($i=0;$i<7;$i++) {
                $dates[] = date("Y-m-d", strtotime('-'.$i.' day'));
            }

            $sql = 'select count(*) as countgroup,DATE_FORMAT(`pay_time`,"%Y-%m-%d") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and `refund_status` != '.REFUND_STATUS_NO_AFTER_SALES.' and `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m-%d")';

        } elseif ($day == 30) {
            $start_time = date("Y-m-d", strtotime('-29 day')).' 00:00:00';
            for ($i=0;$i<29;$i++) {
                $dates[] = date("Y-m-d", strtotime('-'.$i.' day'));
            }

            $sql = 'select count(*) as countgroup,DATE_FORMAT(`pay_time`,"%Y-%m-%d") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and `refund_status` != '.REFUND_STATUS_NO_AFTER_SALES.' and  `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m-%d")';

        } elseif ($day == 365) {
            $start_time = date("Y-m-d", strtotime('-1 year')).' 00:00:00';

            for ($i=0;$i<12;$i++) {
                $dates[] = date("Y-m", strtotime('-'.$i.' month'));
            }

            $sql = 'select count(*) as countgroup,DATE_FORMAT(`pay_time`,"%Y-%m") as dategroup from '.$this->order.' where `uid`='.$uid.' and `shop_id`='.$shop_id.' and `refund_status` != '.REFUND_STATUS_NO_AFTER_SALES.' and `pay_time`>="'.$start_time.'" and `pay_time`<="'.$end_time.'" group by DATE_FORMAT(`pay_time`,"%Y-%m")';
        }

        $res = $this->obj->execute($sql, true, true);
        if (!$res) return array();

        $date2count = array();
        foreach ($res as $info) {
            $date2count[$info['dategroup']] = $info['countgroup'];
        }

        $dates = array_reverse($dates);

        $data = array();
        foreach ($dates as $date) {
            $data[$date] = $date2count[$date] ? $date2count[$date] : 0;
        }

        unset($res);
        unset($date2count);

        return $data;
    }
}