<?php
/**
 * Created by PhpStorm.
 * User: wz
 * Date: 2018/9/25
 * Time: 11:29
 */

namespace app\admin\controller;


use app\kdnapi\controller\KdnApiController;
use cmf\controller\AdminBaseController;
use think\Db;

class ZjOrderController extends AdminBaseController
{
    /**
     * 订单列表
     */
    public function index()
    {
        $where['o.delete_time'] = 0;
        $arr = [];
        $where1 = [];
        if ($this->request->param()) {
            $arr = input('param.');
            if (!empty($arr['uid'])) {
                $where['o.uid'] = $arr['uid'];
            }
            if (!empty($arr['yi'])) {
                $where['o.cid'] = $arr['yi'];
            }
            if (!empty($arr['er'])) {
                $where['o.cids'] = ['like', '%-' . $arr['er'] . '-%'];
            }
            if (!empty($arr['step'])) {
                $where['o.step'] = $arr['step'];
            }
            if (!empty($arr['num'])) {
                $where['o.order_num'] = $arr['num'];
            }
            if (!empty($arr['name'])) {
                $where['o.name'] = $arr['name'];
            }
            if (!empty($arr['mobile'])) {
                $where['o.mobile'] = $arr['mobile'];
            }
            if (!empty($arr['start_time'])) {
                $where['o.create_time'] = ['egt', strtotime($arr['start_time'])];
            }
            if (!empty($arr['end_time'])) {
                $where1['o.create_time'] = ['elt', strtotime($arr['end_time'])];
            }
        }
        $all = Db::name('zj_order')->alias('o')
            ->join('user u', 'o.uid=u.id', 'left')
            ->where($where)->where($where1)
            ->order('create_time', 'desc')
            ->field('o.*,u.user_nickname')
            ->paginate(15);
        $all->appends($arr);

        //查询商品分类
        $cate = Db::name('zj_category')->where(['delete_time' => '0'])->field('name,id,cid,grade')->select()->toArray();
        $cate1 = [];
        $cate2 = [];
        foreach ($cate as $k => $v) {
            if ($cate[$k]['grade'] == 1) {
                $cate1[$k] = $cate[$k];
            } else {
                $cate2[$k] = $cate[$k];
            }
        }
        $cate1 = array_values($cate1);
        $cate2 = array_values($cate2);
        //计算总金额和总积分
        $whole = 0;
        $whole_num = 0;
        foreach ($all as $item) {
            $whole+=$item['whole'];
            $whole_num+=$item['whole_num'];
        }
        $total = $whole - $whole_num;
        $this->assign('start_time', !empty($arr['start_time']) ? $arr['start_time'] : '');
        $this->assign('end_time', !empty($arr['end_time']) ? $arr['end_time'] : '');
        $this->assign('uid', !empty($arr['uid']) ? $arr['uid'] : '');
        $this->assign('step', !empty($arr['step']) ? $arr['step'] : '');
        $this->assign('num', !empty($arr['num']) ? $arr['num'] : '');
        $this->assign('name', !empty($arr['name']) ? $arr['name'] : '');
        $this->assign('mobile', !empty($arr['mobile']) ? $arr['mobile'] : '');
        $this->assign('yi', !empty($arr['yi']) ? $arr['yi'] : '');
        $this->assign('er', !empty($arr['er']) ? $arr['er'] : '');
        $this->assign('page', $all->render());
        $this->assign('all', $all->items());
        $this->assign('cate1', $cate1);
        $this->assign('cate2', $cate2);
        $this->assign('total', $total);
        $this->assign('whole_num', $whole_num);
        return $this->fetch();
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        if ($this->request->param()) {
            $id = input('param.id');
            $url = input('param.sta');
            if ($url == 1) {
                $url = url('index');
            } elseif ($url == 2) {
                $url = url('backlog');
            }
            $one = Db::name('zj_order')->alias('o')->join('user u', 'o.uid=u.id', 'left')->join('zj_kd k', 'o.kid=k.id', 'left')
                ->where('o.id', $id)->field('o.*,u.user_nickname,k.name as kname')->find();
            $kd = Db::name('zj_kd')->select();
            $all = Db::name('zj_order_goods')->alias('og')->join('zj_goods g', 'og.gid=g.id')->where('oid', $id)
                ->field('g.name,og.num')->select();
            if ($one['step'] > 2 && $one['kid'] != 0) {
                $kdgj = Db::name('zj_kd_order')->where(['kd_num' => $one['kd_num']])->value('text');
                $kdgj = json_decode($kdgj, true);
                $this->assign('kdgj', $kdgj);
            }
            $this->assign('kd', $kd);
            $this->assign('url', $url);
            $this->assign('one', $one);
            $this->assign('all', $all);
            return $this->fetch();
        }
    }

    /**
     * 订单详情修改提交
     */
    public function detailPost()
    {
        if ($this->request->param()) {
            $param = input('param.');
            $edit = Db::name('zj_order')->update($param);
            if ($param['step'] == '3') {
                if ($param['kid'] == '0') {
                    $kds = '自提订单';
                } else {
                    //引入快递订阅接口
                    $kd = new KdnApiController();
                    $kds = $kd->orderTracesSubByJson($param['id']);
                    $kds = json_decode($kds, true);
                    if ($kds['Success'] == true) {
                        $kdss = '快递状态订阅成功';
                    } else {
                        $kdss = '快递状态订阅失败';
                    }
                }
            }
            if (empty($edit)) {
                $this->error('修改失败,' . $kdss);
            } else {
                if ($kds['Success'] == true){
                    $this->success('修改成功,' . $kdss);
                }else{
                    $this->error('修改成功',$kdss);
                }
            }
        }
    }


    /**
     * 待处理订单列表
     */
    public function backlog()
    {
        $where['o.delete_time'] = 0;
        $arr = [];
        $where1['o.step'] = ['in', ['2', '6', '8']];
        if ($this->request->param()) {
            $arr = input('param.');
            if (!empty($arr['uid'])) {
                $where['o.uid'] = $arr['uid'];
            }
            if (!empty($arr['step'])) {
                $where['o.step'] = $arr['step'];
            }
            if (!empty($arr['num'])) {
                $where['o.order_num'] = $arr['num'];
            }
            if (!empty($arr['name'])) {
                $where['o.name'] = $arr['name'];
            }
            if (!empty($arr['mobile'])) {
                $where['o.mobile'] = $arr['mobile'];
            }
            if (!empty($arr['start_time'])) {
                $where['o.create_time'] = ['egt', strtotime($arr['start_time'])];
            }
            if (!empty($arr['end_time'])) {
                $where1['o.create_time'] = ['elt', strtotime($arr['end_time'])];
            }
        }
        $all = Db::name('zj_order')->alias('o')->join('user u', 'o.uid=u.id', 'left')->where($where)->where($where1)
            ->order('create_time', 'desc')->field('o.*,u.user_nickname')->paginate(15);
        $all->appends($arr);
        $this->assign('start_time', !empty($arr['start_time']) ? $arr['start_time'] : '');
        $this->assign('end_time', !empty($arr['end_time']) ? $arr['end_time'] : '');
        $this->assign('uid', !empty($arr['uid']) ? $arr['uid'] : '');
        $this->assign('step', !empty($arr['step']) ? $arr['step'] : '');
        $this->assign('num', !empty($arr['num']) ? $arr['num'] : '');
        $this->assign('name', !empty($arr['name']) ? $arr['name'] : '');
        $this->assign('mobile', !empty($arr['mobile']) ? $arr['mobile'] : '');
        $this->assign('page', $all->render());
        $this->assign('all', $all->items());
        return $this->fetch();
    }

    /**
     * 订单发货
     */
    public function fahuo()
    {
        if ($this->request->param()) {
            $param = input('param.id');
            //获取订单数据
            $one = Db::name('zj_order')->alias('o')->join('user u', 'o.uid=u.id', 'left')
                ->where('o.id', $param)->field('o.*,u.user_nickname')->find();
            //获取快递公司数据
            $kd = Db::name('zj_kd')->select();
            //获取订单商品
            $all = Db::name('zj_order_goods')->alias('og')->join('zj_goods g', 'og.gid=g.id')->where('oid', $param)
                ->field('g.name,og.num')->select();
            if ($one['step'] > 2) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>订单已发货</p></div>";
            } elseif ($one['step'] == 1) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>订单未支付</p></div>";
            } else {
                $this->assign('kd', $kd);
                $this->assign('one', $one);
                $this->assign('all', $all);
                return $this->fetch();
            }
        }
    }

    /**
     * 订单发货提交
     */
    public function fhPost()
    {
        if ($this->request->param()) {
            $param = input('param.');
            if (empty($param['kd_num'])) {
                $this->error('快递单号不能为空');
            }

            $param['step'] = 3;
            $edit = Db::name('zj_order')->update($param);
            //引入快递订阅接口
            $kd = new KdnApiController();
            $kds = $kd->orderTracesSubByJson($param['id']);
            $kds = json_decode($kds, true);
            if ($kds['Success'] == true) {
                $kds = '快递状态订阅成功';
            } else {
                $kds = '快递状态订阅失败';
            }
            if (empty($edit)) {
                $this->error('订单状态更新失败,' . $kds);
            } else {
                $this->success('订单状态更新成功,' . $kds);
            }
        }
    }

    /**
     * 订单退款审核
     */
    public function check()
    {
        if ($this->request->param()) {
            $param = input('param.id');
            //获取订单数据
            $one = Db::name('zj_order')->alias('o')->join('user u', 'o.uid=u.id', 'left')->where('o.id', $param)
                ->field('o.*,u.user_nickname')->find();
            //获取订单商品
            $all = Db::name('zj_order_goods')->alias('og')->join('zj_goods g', 'og.gid=g.id')->where('oid', $param)
                ->field('g.name,g.price,og.num')->select();
            if ($one['step'] < 6) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>订单未退货</p></div>";
            } elseif ($one['step'] > 6) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>退款审核通过</p></div>";
            } else {
                $this->assign('one', $one);
                $this->assign('all', $all);
                return $this->fetch();
            }
        }
    }

    /**
     * 订单退款审核提交
     */
    public function checkPost()
    {
        if ($this->request->param()) {
            $param = input('param.');
            //判断审核是否通过
            if (!empty($param['sta'])) {
                $param['step'] = 5;
                unset($param['sta']);
                $edit = Db::name('zj_order')->update($param);
            } else {
                $param['step'] = 7;
                $edit = Db::name('zj_order')->update($param);
            }
            if (empty($edit)) {
                $this->error('订单状态更新失败');
            } else {
                $this->success('订单状态更新成功');
            }
        }
    }

    /**
     * 订单退款
     */
    public function refund()
    {
        if ($this->request->param()) {
            $param = input('param.id');
            //获取订单数据
            $one = Db::name('zj_order')->alias('o')->join('user u', 'o.uid=u.id', 'left')->where('o.id', $param)
                ->field('o.*,u.user_nickname')->find();
            //获取订单商品
            $all = Db::name('zj_order_goods')->alias('og')->join('zj_goods g', 'og.gid=g.id')->where('oid', $param)
                ->field('g.name,g.price,og.num')->select();
            if ($one['step'] > 8) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>订单已退款</p></div>";
            } elseif ($one['step'] < 8) {
                echo "<div style='width: 100%;text-align: center;padding-top: 50px'><p style='font-size: 25px'>订单状态错误</p></div>";
            } else {
                $this->assign('one', $one);
                $this->assign('all', $all);
                return $this->fetch();
            }
        }
    }

    /**
     * 订单退款提交
     */
    public function refundPost()
    {
        if ($this->request->param()) {
            $param = input('param.');
            if (Db::name('zj_order')->where(['id' => $param['id']])->value('step') == 8) {
                if ($param['refund_fee'] <= 0) {
                    $this->error('退款金额需大于0');
                }
                $return = $this->wxRefund($param['id'], $param['refund_fee']);
                if ($return !== false) {
                    $out_refund_no = Db::name('zj_order')->where(['id'=>$param['id']])->value('out_refund_no');
                    if($out_refund_no == '' && $out_refund_no != $return) {
                        $param['step'] = 9;
                        $param['out_refund_no'] = $return;
                        $edit = Db::name('zj_order')->update($param);
                        if (empty($edit)) {
                            $this->error('订单退款失败1');
                        } else {
                            $this->success('订单退款成功');
                        }
                    }else {
                        $this->error('禁止重复退款');
                    }
                } else {
                    $this->error('订单退款失败2');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }

    private function wxRefund($oid, $refundFee)
    {
        $info = Db::name('zj_order')->field('order_num,whole,whole_num,out_trade_no,step')->where(['id' => $oid])->find();
        if ($info['step'] == 8) {
            $totalFee = $info['whole'] - $info['whole_num'];
            if ($refundFee > $totalFee) {
                $this->error('退款金额不能大于实际支付金额');
            } else {
                require_once EXTEND_PATH . '/Refund.php';
                $refund = new \Refund($info['out_trade_no'], $totalFee * 100, $info['order_num'], $refundFee * 100);
                $return = $refund->refund();
                if ($return['return_code'] == 'SUCCESS' && $return['result_code'] == 'SUCCESS') {
                    return $return['out_refund_no'];
                } else {
                    return false;
                }
            }
        } else {
            $this->error('非法操作');
        }
    }

}