<?php

namespace Mshop\Lib;

use Dever;

class Out
{
    # 1是门店，2是仓库
    public $type = 1;
    # 1是列表，2是详情
    public $view = 1;
    # 获取配置
    public $config = array();
    # table
    public $table = 'shop/out_order';

    public function __construct()
    {
        $this->config = Dever::db($this->table)->config;
    }

    # 设置订单的类型
    public function set($type, $view)
    {
        $this->type = $type;
        $this->view = $view;

        return $this;
    }

    # 获取公共的where
    public function where($id)
    {
        $where = array();
        $where['type'] = $this->type;
        $where['type_id'] = $id;
        
        if (!$where) {
            Dever::alert('参数错误');
        }

        return $where;
    }

    # 采购订单列表
    public function getList($id)
    {
        $where = $this->where($id);

        $data['search_value'] = $where;
        $data['search_value']['day'] = $day = Dever::input('day');
        if ($day) {
            $where['start'] = Dever::maketime($day . ' 00:00:00');
            $where['end'] = Dever::maketime($day . ' 23:59:59');
        }

        $result['search_value']['start'] = $start = Dever::input('start');
        $result['search_value']['end'] = $end = Dever::input('end');
        if ($start && $end) {
            $where['start'] = Dever::maketime($start);
            $where['end'] = Dever::maketime($end);
        }

        $order_num = Dever::input('order_num');
        if ($order_num) {
            $where['order_num'] = $order_num;
        }

        $status = Dever::input('status');
        if ($status) {
            $where['status'] = $status;
        }

        $out_type = Dever::input('out_type');
        if ($out_type) {
            $where['out_type'] = $out_type;
        }

        $excel = Dever::input('excel', 1);
        if ($excel == 2) {
            $data['order'] = Dever::db('shop/out_order')->getData($where);
        } else {
            $data['order'] = Dever::db('shop/out_order')->getAll($where);
        }

        if ($data['order']) {
            foreach ($data['order'] as $k => $v) {
                $data['order'][$k] = $this->getInfo($v);
            }
        }

        return $data;
    }

    # 查看订单详情
    public function getView($id, $order_id, $show = true)
    {
        $where = $this->where($id);
        $where['id'] = $order_id;

        $result = Dever::db($this->table)->find($where);

        if (!$result) {
            Dever::alert('订单不存在');
        }

        if ($show) {
            $result = $this->getInfo($result, true);
        }

        return $result;
    }

    # 出库下单
    public function action($type_id, $name, $num, $goods, $price, $member_id, $out_type, $info, $status = 2, $area = '')
    {
        $order_data = $this->where($type_id);
        if ($area) {
            $order_data['area'] = $area . ',' . $type_id;
        }
        
        $order_data['name'] = $name;
        $order_data['num'] = $num;
        $order_data['info'] = $info;
        $order_data['out_type'] = $out_type;
        $order_data['price'] = $price;
        $order_data['member_id'] = $member_id;
        $order_data['status'] = $status;

        $order_data['order_num'] = $this->getOrderId();
        $id = Dever::db('shop/out_order')->insert($order_data);

        if (!$id) {
            Dever::alert('出库失败');
        }

        foreach($goods as $k => $v) {
            if ($v['ku_state'] == 1) {
                $data['order_id'] = $id;
                $data['goods_id'] = $v['id'];
                $data['sku_id'] = $v['sku_id'];
                $data['price'] = $v['price'];
                $data['num'] = $v['buy_num'];

                $state = Dever::db('shop/out_order_goods')->insert($data);
                if ($state) {
                    # 出库成功 去掉库存
                    Dever::load('shop/lib/goods')->oper($order_data, 2, 1, array($data));
                }
            }
        }

        return array('order_id' => $id);
    }

    # 生成订单号
    public function getOrderId()
    {
        $where['order_num'] = Dever::order('OUT');
        $state = Dever::db('shop/out_order')->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderId();
        }
    }

    # 审核出库单
    public function yes_api()
    {
        $id = Dever::input('id');
        $order_id = Dever::input('order_id');
        $type = Dever::input('type', 2);
        $this->set($type, 1);

        $info = $this->getView($id, $order_id, false);

        if ($info && $info['status'] == 1) {
            $where['where_id'] = $info['id'];
            $where['status'] = 2;
            $state = Dever::db('shop/out_order')->update($where);
        }

        return 'reload';
    }

    # 取消出库单
    public function no()
    {
        $id = Dever::input('id');
        $order_id = Dever::input('order_id');
        $type = Dever::input('type', 2);
        $this->set($type, 1);

        $this->cancel($id, $order_id);

        return 'reload';
    }

    # 取消出库单
    public function cancel($id, $order_id)
    {
        $info = $this->getView($id, $order_id, false);

        if ($info && $info['status'] == 1) {
            $where['where_id'] = $info['id'];
            $where['status'] = 3;
            $state = Dever::db('shop/out_order')->update($where);

            if ($state) {
                # 取消成功，恢复库存
                $goods = Dever::db('shop/out_order_goods')->select(array('order_id' => $info['id']));
                if ($goods) {
                    Dever::load('shop/lib/goods')->oper($info, 1, 1, $goods);
                }
            }
        }

        return 'ok';
    }

    # 获取订单详细信息
    private function getInfo($info, $view = false)
    {
        $info['goods'] = Dever::db('shop/out_order_goods')->select(array('order_id' => $info['id']));
        $info['cdate'] = date('Y-m-d H:i', $info['cdate']);

        $type = Dever::db('shop/out_order')->config['config_type'];
        $type = $type();
        $info['type_name'] = $type[$info['out_type']]['name'];

        $status = Dever::db('shop/out_order')->config['config_status'];
        $info['status_name'] = $status[$info['status']];
        if ($view || $this->view == 2) {
            foreach ($info['goods'] as $k => $v) {
                $info['goods'][$k]['info'] = Dever::load('goods/lib/info')->getPayInfo($v['goods_id'], $v['sku_id']);
            }

            $info['member'] = Dever::db('shop/member')->find($info['member_id']);
        }
        return $info;
    }

    # 展示订单详情
    public function show()
    {
        $id = Dever::input('order_id');

        $type = Dever::input('type', 1);

        $config = Dever::db('shop/out_order')->config;

        $info = Dever::db('shop/out_order')->one($id);

        $status = $config['config_status'][$info['status']];

        $config_type = $config['config_type'];
        $config_type = $config_type();
        if (isset($config_type[$info['out_type']])) {
            $out_type = $config_type[$info['out_type']]['name'];
        } else {
            $out_type = '其他';
        }

        $cdate = date('Y-m-d H:i', $info['cdate']);
        
        if ($info['type'] == 1) {
            $type_info = Dever::db('shop/info')->find($info['type_id']);
            $member = Dever::db('shop/member')->find($info['member_id']);
            $name = '门店名称';
        } elseif ($info['type'] == 2) {
            $type_info = Dever::db('store/info')->find($info['type_id']);
            $member = Dever::db('store/member')->find($info['member_id']);
            $name = '仓库名称';
        }

        $result = array();

        $result[$info['order_num']] = array
        (
            'type' => 'info',
            'content' => array
            (
                array
                (
                    array($name, $type_info['name']),
                    array('出库单状态', $status),
                    array('填单时间', $cdate),
                    
                ),
                
                array
                (
                    array('填单人', $member['name']),
                    array('出库类别', $out_type),
                    array('原因备注', $info['info']),
                ),
            )
        );

        $button = array();
        if ($type == 2) {
            $config = Dever::load('store/admin/auth.config');
            if ($info['status'] == 1) {
                $button[] = array
                (
                    'type' => 'action',
                    'link' => Dever::url('admin/out.cancel?order_id='.$info['id'], 'store'),
                    'name' => '取消',
                );
            }
            $config['phone'] = '您的专属客服：' . $config['kf_name'] . '，联系电话：' . $config['phone'];
            
            $button[] = array
            (
                'type' => 'link',
                'link' => Dever::url('admin/out.print?id=' . $info['id'] . '&type=2', 'store'),
                'name' => '打印出库单',
            );

            $button[] = array
            (
                'type' => 'link',
                'link' => Dever::url('lib/out.excel_one?show=2&type='.$info['type'].'&id='.$info['id'], 'mshop'),
                'name' => '导出',
            );

            $button[] = array
            (
                'type' => 'alert',
                'content' => $config['phone'],
                'name' => '联系平台',
            );

        } elseif ($info['status'] == 1) {
            
            $button[] = array
            (
                'type' => 'action',
                'link' => Dever::url('lib/out.yes?id='.$info['type_id'].'&order_id='.$info['id'] . '&type=' . $info['type'], 'mshop'),
                'name' => '审核通过',
            );

            $button[] = array
            (
                'type' => 'action',
                'link' => Dever::url('lib/out.no?id='.$info['type_id'].'&order_id='.$info['id'] . '&type=' . $info['type'], 'mshop'),
                'name' => '审核不通过',
            );

            $button[] = array
            (
                'type' => 'link',
                'link' => Dever::url('lib/out.excel_one?type='.$info['type'].'&id='.$info['id'], 'mshop'),
                'name' => '导出',
            );
        }

        $body = array();
        $body_total = array();
        $body_total['price'] = 0;
        $body_total['num'] = 0;
        $goods = Dever::db('shop/out_order_goods')->select(array('order_id' => $info['id']));
        $goods_status = Dever::db('shop/out_order_goods')->config['status'];

        foreach ($goods as $k => $v) {
            $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
            $status = $goods_status[$v['status']];

            if (isset($goods_info['sku'])) {
                $sku = $goods_info['sku']['string'];
            } else {
                $sku = '无';
            }

            $d = array
            (
                'pic' => $goods_info['cover'],
                'name' => $goods_info['name'],
                'sku' => $sku,
                'price' => $v['price'],
                'num' => $v['num'],
            );
            if ($goods_info['price_type'] > 2) {
                $d['goods'] = $goods_info['goods'];
            }

            if ($info['type'] == 2) {
                unset($d['price']);
            }
            $body[] = $d;
            $price = $v['price']*$v['num'];
            $body_total['price'] += $price;

            $body_total['num'] += $v['num'];
        }

        if ($body) {

            if ($info['type'] == 2) {
                unset($body_total['price']);
            }
            $result['出库商品清单'] = array
            (
                'type' => 'list',
                'content' => $body,
                'total' => $body_total,
            );
        }

        $head = array
        (
            'name' => '基本信息',
            'btn' => $button,
        );
        $html = Dever::show($head, $result);

        return $html;
    }

    public function printer($user)
    {
        $id = Dever::input('id');

        $type = Dever::input('type', 2);

        $factory_config = Dever::db('main/factory_config')->find();
        $main_config = Dever::db('main/config')->find();
        $config = Dever::db('main/config')->find();

        $config = Dever::db('shop/out_order')->config;

        $info = Dever::db('shop/out_order')->one($id);

        if ($info['type'] == 1) {
            $type_info = Dever::db('shop/info')->find($info['type_id']);
            $member = Dever::db('shop/member')->find($info['member_id']);
        } elseif ($info['type'] == 2) {
            $type_info = Dever::db('store/info')->find($info['type_id']);
            $member = Dever::db('store/member')->find($info['member_id']);
        }

        $status = $config['config_status'][$info['status']];

        $config_type = $config['config_type'];
        $config_type = $config_type();
        if (isset($config_type[$info['out_type']])) {
            $out_type = $config_type[$info['out_type']]['name'];
        } else {
            $out_type = '其他';
        }
        

        $cdate = date('Y-m-d H:i', $info['cdate']);

        $pdf = Dever::load('pdf/lib/base')->init();

        $pdf->hr('-', $main_config['name']);

        $pdf->br()->font(20)->center('出库单号：' . $info['order_num']);
        $pdf->font(10);
        $pdf->br(2);

        $pdf->br()->left('仓库名称：' . $type_info['name'], 80)->left('制单人：' . $user['name'], 60)->left('制单时间：' . date('Y-m-d H:i'), 40);

        $pdf->hr();

        $pdf->br()->left('出库单状态：' . $status, 140)->left('出库填单时间：' . $cdate, 40);

        $pdf->left('出库类别：' . $out_type);

        $pdf->left('原因备注：' . $info['info']);

        $pdf->hr();

        $head = array(array('商品编号', 40), array('商品名称', 70), array('商品属性', 60), array('出库数量', 20));

        $data = Dever::db('shop/out_order_goods')->select(array('order_id' => $info['id']));

        if ($data) {
            $body = array();
            $body_total = array();
            $body_total['num'] = 0;

            foreach ($data as $k => $v) {

                $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v['goods_id'], $v['sku_id']);
                if (isset($goods_info['sku'])) {
                    $sku = $goods_info['sku']['string'];
                } else {
                    $sku = '';
                }

                $body[] = array
                (
                    $goods_info['id'],
                    $goods_info['name'],
                    $sku,
                    'x ' . $v['num'],
                );

                $body_total['num'] += $v['num'];
            }

            $pdf->br();
            foreach ($head as $k => $v) {
                $pdf->left($v[0], $v[1]);
            }

            foreach ($body as $k => $v) {
                $pdf->br();
                foreach ($head as $k1 => $v1) {
                    $pdf->left($v[$k1], $v1[1]);
                }
            }
            $pdf->br();
            $pdf->right('共'.$body_total['num'].'件商品');
            $pdf->hr();
        }

        $pdf->br(1);
        
        $pdf->right('如遇任何问题请致电客服');
        $pdf->br();

        $pdf->font(20);
        $pdf->left($main_config['name'], 160);

        $pdf->font(10);
        $pdf->right('电话：' . $factory_config['phone'], 30);

        $pdf->br();

        $pdf->left($main_config['site'], 160);

        $pdf->font(10);
        $pdf->right($main_config['worktime'], 30);

        $pdf->out('库存清单');
    }

    # 导出单个订单
    public function excel_one_api()
    {
        $this->type = Dever::input('type');
        $id = Dever::input('id');
        $data = Dever::db('shop/out_order')->select($id);
        $this->excel($data);
    }

    # 导出订单
    public function excel($data)
    {
        if (!$data) {
            Dever::alert('无导出数据');
        }
        $file = '出库订单';
        $type = Dever::input('search_option_type', $this->type);

        $header = array('所属仓库', '出库单号', '商品名称', '商品规格属性', '商品采购价格', '商品出库数量', '采购总价格', '出库类型', '出库状态', '出库时间');

        $table = 'store/info';
        if ($type == 1) {
            $header[0] = '所属门店';
            $header[4] = '商品销售价格';
            $header[6] = '销售总价格';
            $table = 'shop/info';
        }

        $show = Dever::input('show', 1);
        if ($type == 2) {
            unset($header[4]);
            unset($header[6]);
        }

        $body = array();
        $out_type = Dever::db('shop/out_type')->getAll();
        $status = Dever::db('shop/out_order')->config['config_status'];
        foreach ($data as $k => $v) {
            if (!is_array($v)) {
                continue;
            }
            $type_info = Dever::db($table)->find($v['type_id']);
            $goods = Dever::db('shop/out_order_goods')->select(array('order_id' => $v['id']));
            if (isset($out_type[$v['out_type']]) && $out_type[$v['out_type']]) {
                $out_type_name = $out_type[$v['out_type']]['name'];
            } else {
                $out_type_name = '其他';
            }
            $status_name = $status[$v['status']];

            $cdate = strstr($v['cdate'], '-') ? $v['cdate'] : date('Y-m-d H:i', $v['cdate']);
            
            foreach ($goods as $k1 => $v1) {

                $goods_info = Dever::load('goods/lib/info')->getInfoBySku($v1['goods_id'], $v1['sku_id']);
                if (isset($goods_info['sku'])) {
                    $sku = $goods_info['sku']['string'];
                } else {
                    $sku = '';
                }

                $d = array
                (
                    $type_info['name'],
                    $v['order_num'],
                    $goods_info['name'],
                    $sku,
                    $v1['price'],
                    $v1['num'],
                    $v1['price']*$v1['num'],
                    $out_type_name,
                    $status_name,
                    $cdate,
                );

                if ($type == 2) {
                    unset($d[4]);
                    unset($d[6]);
                }

                $body[] = $d;
            }
        }

        Dever::excelExport($body, $header, $file);
    }
}