<?php
namespace app\allwin\controller\home;
use app\common\controller\Official;
use app\allwin\model\AllwinConfig;
use app\allwin\model\Bank;
use app\allwin\model\BankBill;
use app\allwin\model\MchId;
use app\allwin\model\AllwinStore;
use app\allwin\model\StoreBill;
use app\allwin\model\StoreStats;
use app\allwin\model\AllwinUser;
use app\allwin\model\Worker;
use app\allwin\model\WorkerStoreOrder;
use app\common\model\SystemUser;
use app\common\facade\WechatPay;
use app\common\facade\WechatMp;
use app\common\facade\Upload;
use think\facade\Request;
use think\helper\Time;

class agent extends Official{


    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 首页
     */
    public function index(){
        $view['worker']            = Worker::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['uid' => $this->user->id])->find();
        $view['title']             = '合伙人';
        $view['weconfig']          = WechatMp::jsApiList($this->member_miniapp_id);
        $view['workerOnStore']     = WorkerStoreOrder::where(['member_miniapp_id' => $this->member_miniapp_id, 'uid' => $this->user->id, 'pay_state' => 0])->where(['uid' => $this->user->id])->find();
        $view['member_miniapp_id'] = $this->member_miniapp_id;
        $view['setting']           = model('AllwinConfig')->getConfig($this->member_miniapp_id);
        $allWinConfig              = AllwinConfig::where(['member_miniapp_id' => $this->member_miniapp_id])->find();
        $view['sla']               = json_decode($allWinConfig->sla);
        $this->view->engine->layout(false);
        return view()->assign($view);
    }

    /**
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * tabar1数据
     */
    public function myStore(){
        $worker = Worker::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['uid' => $this->user->id])->find();
        if ($worker) {
            $list = AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id])->whereIn('id', $worker->store_ids)->order('create_time desc')->paginate(10, false)->toArray();
            if (count($list['data']) == 0) {
                return enjson(204);
            }
            return enjson(200, '', $list);
        } else {
            return enjson(204);
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * tabar3全部帐单
     */
    public function allBill(int $type = 1){
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        if ($type) {
            switch ($type) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 3:
                    list($start, $end) = $this->beforeYesterday(2);
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['update_time', '>=', $start];
            $condition[] = ['update_time', '<=', $end];
        }
        $list = BankBill::where($condition)->where(['user_id' => $this->user->id])->order('update_time desc')->paginate(10, false)->toArray();
        if (count($list['data']) == 0) {
            return enjson(204);
        }
        return enjson(200, '', $list);
    }

    /**
     * @return \think\response\Json
     * tabar3账单总金额
     */
    public function allBillSum(){
        $worker = Worker::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['uid' => $this->user->id])->find();
        $data   = [
            'worker'   => $worker,
            'user'     => SystemUser::where(['member_miniapp_id' => $this->member_miniapp_id, 'id' => $this->user->id])->find(),
            'storeNum' => AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['is_lock' => 0])->whereIn('id', $worker->store_ids)->count(),
            'sum'      => BankBill::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['user_id' => $this->user->id])->sum('money'),
            'vipNum'   => AllwinUser::where('store_id', '>', 0)->whereIn('store_id', $worker->store_ids)->count(),
            'bank'     => Bank::where(['member_miniapp_id' => $this->member_miniapp_id, 'user_id' => $this->user->id])->find(),
        ];
        return enjson(200, '', $data);
    }

    /**
     * @param int $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * tabar1修改时所需
     */
    public function getDataById(int $id = 0){
        $store = AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id, 'id' => $id])->find();
        $data  = [
            'store' => $store,
            'user'  => SystemUser::where(['member_miniapp_id' => $this->member_miniapp_id, 'id' => $store->manage_uid])->find()
        ];
        return enjson(200, '', $data);
    }

    /**
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * tabar1单个店铺帐单总计
     */
    public function getStoreBill(int $id = 0){
        $storeStats = StoreStats::where(['member_miniapp_id' => $this->member_miniapp_id, 'store_id' => $id])->find();
        return enjson(200, '', $storeStats);
    }

    /**
     * @param $id
     * @param $type
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * tabar1单个店铺帐单列表
     */
    public function storeBillList(int $id = 0,int $type = 1){
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        if ($type) {
            switch ($type) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 3:
                    list($start, $end) = $this->beforeYesterday(2);
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['update_time', '>=', $start];
            $condition[] = ['update_time', '<=', $end];
        }
        $list = StoreBill::where($condition)->where(['store_id' => $id])->order('update_time desc')->paginate(10, false)->toArray();
        if (count($list['data']) == 0) {
            return enjson(204);
        }
        return enjson(200, '', $list);
    }

    /**
     * @param string $name
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * tabar2获取用户数据
     */
    public function getUser($key = ''){
        $user = SystemUser::where(['member_miniapp_id' => $this->member_miniapp_id])->where('nickname|phone_uid', 'like','%' . $key . '%','or')->find();
        if ($user) {
            $store = AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id, 'manage_uid' => $user->id])->find();
            if ($store) {
                return enjson(0, '该店长已绑定其他店铺');
            } else {
                return enjson(200, '', $user);
            }
        } else {
            return enjson(0, '该用户不存在');
        }
    }

    /**
     * @return \think\response\Json
     * 上传图片
     */
    public function upImg(){
        if (request()->isPost()) {
            $rel = Upload::index();
            if ($rel['error'] == 0) {
                return json(['code' => 200, 'msg' => 'success', 'data' => $rel['url']]);
            } else {
                return json(['code' => 204, 'msg' => 'error']);
            }
        }
    }

    /**
     * @return \think\response\Json
     * 修改保存
     */
    public function edit(){
        $worker = Worker::where(['member_miniapp_id' => $this->member_miniapp_id])->where(['uid' => $this->user->id])->find();
        $data = [
            'member_miniapp_id' => $this->member_miniapp_id,
            'uid'               => $this->user->id,
            'id'                => input('post.id/d'),
            'manage_uid'        => input('post.manage_uid/d'),
            'charges'           => input('post.charges/d'),
            'work_time'         => input('post.work_time/s'),
            'name'              => input('post.name/s'),
            'address'           => input('post.address/s'),
            'telphone'          => input('post.telphone/s'),
            'tags'              => input('post.tags/s'),
            'img'               => input('post.img/s')
        ];
        if ($data['id'] > 0) {
            $store = AllwinStore::where(['member_miniapp_id' => $this->member_miniapp_id,'id' =>  $data['id']])->find();
            if($store){
                $workerStoreOrder = WorkerStoreOrder::where(['member_miniapp_id' => $this->member_miniapp_id, 'store_id' => $store->id])->find();
                if($workerStoreOrder){
                    if(isset($workerStoreOrder->pay_state) && $workerStoreOrder->pay_state != 0 && $store->is_lock == 1){
                        return enjson(0, '该数据禁止修改');
                    }
                }else{
                    return enjson(0, '数据访问错误');
                }
            }else{
                return enjson(0, '数据访问错误');
            }
        }
        if ($data['manage_uid'] == 0) {
            return enjson(0, '好店店长不存在');
        }
        $validate = $this->validate($data, 'Store.wechatedit');
        if (true !== $validate) {
            return enjson(0, $validate);
        }
        if ($data['charges'] > 0 && $data['charges'] <= 30) {
            return enjson(0, '抱歉~交易服务费禁止小于30‰');
        }
        $store_id = AllwinStore::wechatEdit($data);
        $workerStoreOrder = WorkerStoreOrder::where(['member_miniapp_id' => $this->member_miniapp_id, 'store_id' =>  $store_id])->find();
        if(!empty($workerStoreOrder) && $workerStoreOrder->pay_state == 1){
            return enjson(200,'操作成功',$store_id);
        }
        $setting                   = model('AllwinConfig')->getConfig($this->member_miniapp_id);
        $order_no                  = $this->user->invite_code . order_no();
        $data['store_id']          = $store_id;
        $data['order_no']          = $order_no;
        $data['uid']               = $this->user->id;
        $data['total_price']       = $setting->workers_on_store;
        $data['price']             = $setting->workers_discount >0 ? $setting->workers_discount/100 * $setting->workers_on_store : $setting->workers_on_store;
        $data['member_miniapp_id'] = $this->member_miniapp_id;
        if(!empty($setting) && isset($setting->workers_on_store) && $setting->workers_on_store > 0){
            $data['pay_state']     = 0;
            $result                = WorkerStoreOrder::createOrder($data);
            $unorder['miniapp_id'] = $this->member_miniapp_id;
            $unorder['name']       = '开通好店费用';
            $unorder['order_no']   = $order_no;
            $unorder['notify_url'] = api(3,'allwin/Partnershipnotify/onStoreNotify',$this->member_miniapp_id);;
            $unorder['total_fee']  = $data['price'] * 100;
            if ($setting->is_psp == 1) {
                $mid              = MchId::getMch(0, $this->member_miniapp_id);
                $unorder['mchid'] = $mid->mchid;
            }
            $unorder['openid'] = $this->user->official_uid;
            $ispay             = WechatPay::orderPay($unorder,true);
            if ($ispay['code'] == 0) {
                return json(['code' => 0, 'return_code' => 'FAIL', 'msg' => $ispay['msg']]);
            }
            return enjson(206,'操作成功', $ispay['data']);
        }else{
            $data['pay_state']     = 2;
            $result                = WorkerStoreOrder::createOrder($data);
            return enjson(200,'操作成功',$store_id);
        }

    }

    /**
     * @param int $day
     * @return array
     * 获取前天时间
     */
    public function beforeYesterday(int $day)
    {
        $yesterday = date('d') - $day;
        return [
            mktime(0, 0, 0, date('m'), $yesterday, date('Y')),
            mktime(23, 59, 59, date('m'), $yesterday, date('Y'))
        ];
    }

    /**
     * @param $uid
     * @return \think\response\Json
     * 下单
     */
    public function pay(){
        $order_no                  = $this->user->invite_code . order_no();
        $data['id']                = Request::param('id/d');
        $data['order_no']          = $order_no;
        $data['uid']               = $this->user->id;
        $data['member_miniapp_id'] = $this->member_miniapp_id;
        $unorder['miniapp_id']     = $this->member_miniapp_id;
        $unorder['name']           = '开通合伙人费用';
        $unorder['order_no']       = $order_no;
        $unorder['notify_url']     = api(4,'allwin/Partnershipnotify/workerNotify',$this->member_miniapp_id);
        $setting                   = model('AllwinConfig')->getConfig($this->member_miniapp_id);
        $unorder['total_fee']      = $setting->workers_on_amount ? $setting->workers_on_amount * 100 : 100;
        $data['price']             = $unorder['total_fee']/100;
        $result                    = Worker::createOrder($data);
        if ($setting->is_psp == 1) {
            $mid              = MchId::getMch(0, $this->member_miniapp_id);
            $unorder['mchid'] = $mid->mchid;
        }
        $unorder['openid'] = $this->user->official_uid;
        $ispay =  WechatPay::orderPay($unorder,true);
        if ($ispay['code'] == 0) {
            return json(['code' => 0, 'return_code' => 'FAIL', 'msg' => $ispay['msg']]);
        }
        return json(['code' => 200, 'msg' => '操作成功', 'data' => $ispay['data']]);
    }
}