<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2022/10/29
 * Time: 11:08
 */

namespace app\api\controller;

use app\admin\model\Addr;
use app\admin\model\device\Chargedevice;
use app\admin\model\device\Chargegroup;
use app\admin\model\device\Site;
use app\admin\model\order\Contract;
use app\admin\model\order\Order as OrderModel;
use app\admin\model\order\Usercontract;
use app\admin\model\users\Agent;
use app\api\model\PaymentLogModel;
use app\common\controller\Api;
use \app\admin\model\users\Users;
use think\Db;
use think\Exception;

/**
 * 订单接口
 * Class Order
 * @package app\api\controller
 */
class Order extends Api
{


    protected $noNeedLogin = ['myselforderlist'];
    protected $noNeedRight = ['*'];


    /**
     * 订单列表
     */
    public function orderList()
    {
        $page = $this->request->post('page', 1);
        $order_type = $this->request->post('order_type', ''); //0=充电订单,2=包月订单,4=广告订单,5=设备下单
        $date_type = $this->request->post('date_type', ''); //查询时间类型  day:日度查询，month:月度查询
        $date = $this->request->post('date', ''); //具体日期
        $charge_device_sn = $this->request->post('charge_device_sn','');//充电桩外壳编号
        $where = ['cd.user_id' => $this->auth->id];
        if($order_type != ''){
            $where['o.order_type'] = $order_type;
        }
       /* if ($order_type) {
            if ($order_type == 1) {
                $order_type = 0;
            } elseif ($order_type == 3) {
                $order_type = 4;
            }
            $where['o.order_type'] = $order_type;
        }else{
            $where['o.order_type'] = ['neq',5];
        }*/
        if($charge_device_sn){
            $where['o.device_sign'] = $charge_device_sn;
        }
        switch ($date_type) {
            case 'day':
                $arr = date_parse_from_format('Y.m.d', $date);
                $start_time = mktime(0, 0, 0, $arr['month'], $arr['day'], $arr['year']);
                $end_time = $start_time + 86400;
                break;
            case 'month':
                $arr = date_parse_from_format('Y.m', $date);
                $start_time = mktime(0, 0, 0, $arr['month'], 1, $arr['year']);
                $end_time = mktime(0, 0, 0, $arr['month'] + 1, 1, $arr['year']);
                break;
            default:
                $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end_time = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                break;
        }
        $where['o.createtime'] = ['between', [$start_time, $end_time]];

        $order_list = Chargedevice::alias('cd')
            ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
            ->where($where)
            ->field('o.*,FROM_UNIXTIME(o.createtime,"%Y-%m-%d %H:%i") as createtime,cd.area_name')
            ->field("REPLACE(o.mobile, SUBSTR(mobile,4,4), '****') as mobile")
            ->order('o.createtime desc')
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        $order_money = Chargedevice::alias('cd')
            ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
            ->where($where)
            ->sum('o.need_pay');
        $order_count = Chargedevice::alias('cd')
            ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
            ->where($where)
            ->count();
        if (!$order_list) {
            $this->error('暂无订单');
        }
        $this->success('获取成功', ['order_list' => $order_list, 'order_count' => $order_count, 'order_money' => sprintf("%.2f",$order_money)]);
    }

    /**
     * 获取设备认购记录
     */
    public function getBuyOrderlist(){
        $page = $this->request->post('page',1);
        $where['order_type'] = 5;//认购订单
        $where['user_id'] = $this->auth->id;
        $where['sale_status'] = 2;
        $buy_orders = OrderModel::where($where)
            ->field('*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i") as createtime')
            ->page($page)
            ->limit($this->pageSize)
            ->select();//认购订单
        if(!$buy_orders){
            $this->error('暂无认购设备');
        }
        $buy_order_money = OrderModel::where($where)->sum('total_price');//累计认购金额
        $buy_order_num = OrderModel::where($where)->sum('num');//累计设备台数
        $this->success('获取成功', ['buy_orders' => $buy_orders, 'buy_order_money' => sprintf("%.2f",$buy_order_money), 'buy_order_num' => $buy_order_num]);
    }

    /**
     * 获取生成订单数据
     *
     */
    public function generateOrder()
    {
        $group_id = $this->request->post('group_id', 0);//设备id
        $agent_user_id = $this->request->post('agent_user_id', 0);//合伙人(桩主)
        $num = $this->request->post('num', 1);//认购数量
        $data =[];
        $agent = Agent::where(['agent_user_id' =>$agent_user_id])->find();
        if($agent){
            $agent['province']= Db::name('addr')->where(['ID' =>$agent['province_id']])->value('Name');
            $agent['city']= Db::name('addr')->where(['ID' =>$agent['city_id']])->value('Name');
            $agent['area']= Db::name('addr')->where(['ID' =>$agent['area_id']])->value('Name');
        }
        $device = Chargedevice::where(['group_id' =>$group_id,'authorizestatus' =>1])->find();
        $data['device'] = $device;
        $data['total_fee'] = sprintf("%.2f",$device['price']*$num);
        $data['agent'] = $agent;
        $this->success('获取成功',$data);
    }

    /**
     * 获取合同模板
     *
     */
    public function getContractType()
    {
        $group_id = $this->request->post('group_id', 0);//设备id
        $device = Chargedevice::where(['group_id' =>$group_id])->find();
        if($device['price'] == 10800){
            $where = ['id' =>2];
        }else{
            $where = ['id' =>1];
        }
        $where['status'] = 1;
        $contract = Contract::where($where)->find();
        $this->success('获取成功',$contract);
    }

    /**
     * 客户签订后提交合同
     *
     */
    public function addUsersContract()
    {
        $image = $this->request->post('image', '');//签订好的合同图片地址
        $contract_id = $this->request->post('contract_id', 0);//签订好的合同id
        $order_id = $this->request->post('order_id', 0);//认购订单id
        $data = [
            'user_id' =>$this->auth->id,
            'contract_id' =>$contract_id,
            'order_id' =>$order_id,
            'image' =>$image,
            'createtime' =>time(),
        ];
        $res = Usercontract::create($data);
        $this->success('提价成功',['user_contract' =>$res->toArray()]);
    }

    /**
     *读取省市区数据,联动列表
     */
    public function address(){
        $params = $this->request->post();
        $province = isset($params['province_id']) ? $params['province_id'] : '';
        $city = isset($params['city_id']) ? $params['city_id'] : '';
        $where = ['LevelType' => 1];
        $provincelist = null;
        if ($province !== '') {
            if ($province) {
                $where['ParentId'] = $province;
                $where['LevelType'] = 2;
            }
            if ($city !== '') {
                if ($city) {
                    $where['ParentId'] = $city;
                    $where['LevelType'] = 3;
                }
            }
        }
        $provincelist = Db::name('addr')->where($where)->field('ID as value,Name as name')->select();
        $this->success('获取成功', $provincelist);
    }


    /**
     * 设备（充电桩）下单
     */
    public function addDeviceOrder(){
//        $device_id = $this->request->post('device_id', 0);//设备id
        $group_id = $this->request->post('group_id', 0);//小区站点组id
        $share_id = $this->request->post('share_id', 0);//邀请人ID
        $num = $this->request->post('num', 1);//下单数量
        $total_fee = $this->request->post('total_fee', 0);//下单金额
        $area_id = $this->request->post('area_id', 0);//区县id
        $city_id = $this->request->post('city_id', 0);//市级id
        $pay_way = $this->request->post('pay_way', 'weixin');//支付方式:weixin=微信,money=钱包,alipay=支付宝
        $mobile = $this->request->post('mobile', '');//手机号
        $realname = $this->request->post('realname', '');//真实姓名
        $identity_number = $this->request->post('identity_number', '');//用户身份证号
        $detail_address = $this->request->post('detail_address', '');//居住详细地址
        $order_type = $this->request->post('order_type', 'device');//订单类型
        $contract_image = $this->request->post('image', '');//签订好的合同图片地址
        $chargegroup = Chargegroup::where(['id' =>$group_id])->find();
        $auth_device_count = Chargedevice::where(['authorizestatus' =>1,'group_id' =>$group_id])->count();//剩余未认购总设备数
        if($num > $auth_device_count){
            $this->error('认购数量已超出此站点剩余未认购总数');
        }
        if($share_id == $this->auth->id){
            $this->error('自己不能推自己');
        }
        /*$device = Chargedevice::where(['id' =>$device_id,'authorizestatus' =>1])->find();
        if(!$device){
            $this->error('此设备已被认购');
        }*/
        try {
            Db::startTrans();
            $order_data = [
                'user_id' => $this->auth->id,
                'order_sn' => getOrdersn($order_type),
                'total_price' => $total_fee,
                'need_pay' => $total_fee,
//                'code' => $device['code'],
//                'device_sign' => $device['charge_device_sn'],
                'chargingGroupName' => $chargegroup['group_name'],
//                'chargingName' => $device['charge_device_name'],
                'createtime' => time(),
                'order_type' =>5,
                'sale_status' =>1,//待支付
                'group_id' =>$group_id,
                'contract_image' =>$contract_image,
                'num' =>$num,
            ];
            if($share_id){
                $order_data['share_id'] = $share_id;
            }
            $order = OrderModel::create($order_data);//生成一条待支付订单数据
            $data = [
                'user_id' =>$this->auth->id,
//                'contract_id' =>$contract_id,
                'order_id' =>$order->id,
                'image' =>$contract_image,
                'createtime' =>time(),
                'status' =>2,
            ];
            Usercontract::create($data);//同时创建订单合同管理记录
            $pay_arr = [
                'user_id' => $this->auth->id,
                'order_sn' =>$order->order_sn,
                'order_id' => $order->id,
                'order_type' => $order_type,
                'need_pay' =>$total_fee,
                'pay_way' =>$pay_way,
                'status' => 1,
                'createtime' => time(),
            ];
            $payment_log = PaymentLogModel::create($pay_arr);
            //登记为合伙人（桩主）隐藏状态
            $agent = Agent::where(['agent_user_id' =>$this->auth->id])->find();
            if(!$agent){
                $city = Addr::where(['ID' =>$city_id])->find();
                $province_id = $city ? $city['ParentId'] :0;
                $agent_arr = [
                    'agent_user_id' =>$this->auth->id,
                    'parent_user_id' =>$share_id,
                    'realname' =>$realname,
                    'identity_number' =>$identity_number,
                    'mobile' =>$mobile,
                    'province_id' =>$province_id,
                    'city_id' =>$city_id,
                    'area_id' =>$area_id,
                    'detail_address' =>$detail_address,
                    'createtime' =>time(),
                    'status' =>2//隐藏状态
                ];
                Agent::create($agent_arr);
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('提交订单失败', $e->getMessage());
        }
        $this->success('提交订单成功', ['order_id' => $order->id, 'log' => $payment_log]);
    }

    /**
     * 查看合同
     *
     */
    public function getUsersContract()
    {
        $order_id = $this->request->post('order_id', 0);//认购订单id
        $orderinfo = OrderModel::where(['id' =>$order_id,'sale_status' =>2])->find();
        if(!$orderinfo){
            $this->error('订单还未支付');
        }
        $this->success('提价成功',['orderinfo' =>$orderinfo]);
    }

    /**
     * 鹿马请求我的订单列表接口
     */
    public function mySelfOrderList()
    {
        if (!$this->request->isPost()) {
            $this->error('获取失败');
        }
        $data = $params = $this->request->post();
        unset($params['sign']);
        unset($params['user_id']);
        /* $arr = array_merge($params, [
             'token' => config('luma.token'),
         ]);*/
        ksort($params);
        if ($data['sign'] == sha1(urldecode(http_build_query($params).'token='.config('luma.token')))) {
            $where = ['cd.user_id' => $data['user_id']];
            if ($data['order_type'] != '') {
                $where['o.order_type'] = $data['order_type'];
            }

            if ($data['charge_device_sn']) {
                $where['o.device_sign'] = $data['charge_device_sn'];
            }
            switch ($data['order_type']) {
                case 'day':
                    $date_arr = date_parse_from_format('Y.m.d', $data['date']);
                    $start_time = mktime(0, 0, 0, $date_arr['month'], $date_arr['day'], $date_arr['year']);
                    $end_time = $start_time + 86400;
                    break;
                case 'month':
                    $date_arr = date_parse_from_format('Y.m', $data['date']);
                    $start_time = mktime(0, 0, 0, $date_arr['month'], 1, $date_arr['year']);
                    $end_time = mktime(0, 0, 0, $date_arr['month'] + 1, 1, $date_arr['year']);
                    break;
                default:
                    $start_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                    $end_time = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                    break;
            }
            $where['o.createtime'] = ['between', [$start_time, $end_time]];

            $order_list = Chargedevice::alias('cd')
                ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
                ->where($where)
                ->field('o.*,FROM_UNIXTIME(o.createtime,"%Y-%m-%d %H:%i") as createtime,cd.area_name')
                ->field("REPLACE(o.mobile, SUBSTR(mobile,4,4), '****') as mobile")
                ->order('o.createtime desc')
                ->page($data['page'])
                ->limit($this->pageSize)
                ->select();
            $order_money = Chargedevice::alias('cd')
                ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
                ->where($where)
                ->sum('o.need_pay');
            $order_count = Chargedevice::alias('cd')
                ->join('order o', 'cd.charge_device_sn = o.device_sign', 'left')
                ->where($where)
                ->count();
            if (!$order_list) {
                $this->error('暂无订单');
            }
            $this->success('获取成功', ['order_list' => $order_list, 'order_count' => $order_count, 'order_money' => sprintf("%.2f", $order_money)]);
        }else{
            $this->error('获取失败,签名错误');
        }
    }
}
