<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\controller;


use app\adminapi\logic\ConfigLogic;
use app\api\logic\UserLogic;
use app\common\logic\UserLogic as CommonUserLogic;
use app\api\validate\PasswordValidate;
use app\api\validate\SetUserInfoValidate;
use app\api\validate\UserValidate;
use app\common\logic\contract\ContractLogic;
use app\common\model\Company;
use app\common\model\contract\Contract;
use app\common\model\dict\DictData;
use app\common\model\user\User;
use app\common\model\user\UserAccountLog;
use app\common\model\user\Withdraw;
use Common;
use Symfony\Component\HttpClient\HttpClient;
use think\facade\Db;
use think\facade\Log;

/**
 * 用户控制器
 * Class UserController
 * @package app\api\controller
 */
class UserController extends BaseApiController
{
    public array $notNeedLogin = ['resetPassword'];


    /**
     * @notes 获取个人中心
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/16 18:19
     */
    public function center()
    {
        $data = UserLogic::center($this->userInfo);
        return $this->success('', $data);
    }


    /**
     * @notes 获取个人信息
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/20 19:46
     */
    public function info()
    {
        $params = $this->request->param();
        if(isset($params['id']) && $params['id']>0){
            $id=$params['id'];
        }else{
            $id=$this->userId;
        }
        $result = UserLogic::info($id);
        return $this->data($result);
    }


    /**
     * @notes 重置密码
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/16 18:06
     */
    public function resetPassword()
    {
        $params = (new PasswordValidate())->post()->goCheck('resetPassword');
        $result = UserLogic::resetPassword($params);
        if (true === $result) {
            return $this->success('操作成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }


    /**
     * @notes 修改密码
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/20 19:16
     */
    public function changePassword()
    {
        $params = (new PasswordValidate())->post()->goCheck('changePassword');
        $result = UserLogic::changePassword($params, $this->userId);
        if (true === $result) {
            return $this->success('操作成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }


    /**
     * @notes 获取小程序手机号
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 16:46
     */
    public function getMobileByMnp()
    {
        $params = (new UserValidate())->post()->goCheck('getMobileByMnp');
        $params['user_id'] = $this->userId;
        $result = UserLogic::getMobileByMnp($params);
        if ($result === false) {
            return $this->fail(UserLogic::getError());
        }
        return $this->success('绑定成功', [], 1, 1);
    }


    /**
     * @notes 编辑用户信息
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 17:01
     */
    public function setInfo()
    {
        $params = (new SetUserInfoValidate())->post()->goCheck(null, ['id' => $this->userId]);
        $result = UserLogic::setInfo($this->userId, $params);
        if (false === $result) {
            return $this->fail(UserLogic::getError());
        }
        return $this->success('操作成功', [], 1, 1);
    }


    /**
     * @notes 绑定/变更 手机号
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 17:29
     */
    public function bindMobile()
    {
        $params = (new UserValidate())->post()->goCheck('bindMobile');
        $params['user_id'] = $this->userId;
        $result = UserLogic::bindMobile($params);
        if ($result) {
            return $this->success('绑定成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    /**
     * 获取用户当前可提现的截止时间以及可提现的金额
     */
    public function getCurrCycleWithdraw()
    {
        $userInfo = User::find(['id' => $this->userId]);
        $company = Company::find(['id' => $userInfo['company_id']]);
        // 用户提现周期截止日期
        $endCycle = $company['withdraw_deadline'];
        $isDraw = time() >= $endCycle? 1: 0; // 当前时间大于截止时间,可提现
        // 计算公司周期内所有用户已完成的 变动类型为任务收益金额增加 动作为增加的 未提现状态 的变动金额之和
        $currTotalWithdrawMoney = UserAccountLog::where(['company_id'=>$userInfo['company_id'], 'action'=>1, 'status'=>1, 'is_withdraw'=>0, 'change_type'=>202])->where('create_time', '<', $endCycle)->sum('change_amount');
        return $this->success('成功', ['is_draw' => $isDraw,'end_cycle'=>$endCycle, 'user_currrent_total_withdraw_money'=>$currTotalWithdrawMoney], 1, 1);
    }
    public function withdraw()
    {
        $params = $this->request->param();
        if(!isset($params['amount'])) {
            return $this->fail('参数错误');
        }
        $params['user_id'] = $this->userId;
        $result = UserLogic::withdraw($params);
        if ($result) {
            return $this->success('提现申请已提交', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    public function withdrawList()
    {
        [$page, $limit] = $this->getPage();
        [$count, $list] = UserLogic::withdrawList($this->userId, $page, $limit);
        return $this->success('success', ['count' => $count, 'data' => $list]);
    }

    //**发起合同 */
    public function initiate_contract()
    {
        $params = $this->request->param();
        $admin_id = Db::name('user')->where('id', $this->userId)->value('admin_id');
        $params['check_status'] = 1;
        $params['party_a']=$this->userInfo['company_id'];
        $result = ContractLogic::initiate_contract($params, $admin_id);
        if ($result == true) {
            return $this->success('发起成功,等待平台风控部上传合同');
        }
        return $this->fail(ContractLogic::getError());
    }
    // /**生成合同 */
    public function Draftingcontracts()
    {
        $params = $this->request->param();
        $result = ContractLogic::Draftingcontracts($params,2);
        if ($result == true) {
            return $this->success('生成合同成功');
        }
        return $this->fail(ContractLogic::getError());
    }

    //**发送短信 */
    public function postsms()
    {
        $params = $this->request->param();
        $id=Contract::where('party_b', $params['id'])->value('id');
        $res = ContractLogic::postsms(['id'=>$id]);
        if ($res == true) {
            return $this->success('发送成功', [], 1, 1);
        } else {
            return $this->fail(ContractLogic::getError());
        }
    }

    /**
     * 获取公司以设置的小队
     */
    public function company_brigade(){
        $company_id=$this->userInfo['company_id'];
        $res=User::where('company_id',$company_id)->where('is_captain',1)->column('brigade');
        return $this->success('发送成功', $res);

    }

    // 交易任务进度
    public function getTradeTaskInfo()
    {
        $company = Company::where('id', $this->userInfo['company_id'])->find();

        $start_time = date('Y-m-d');
        $time = strtotime($start_time) + 86399;
        $end_time = date('Y-m-d H:i:s', $time);
        $parmas = [
            "start_date" => $start_time,
            "end_date" => $end_time
        ];
        $parmas['brigade_id'] = $company['responsible_area'];
        $parmas['village_code'] = $company['village'];
        $parmas['street_code'] = $company['street'];
        $parmas['district_code'] = $company['area'];
        $parmas['city_code'] = $company['city'];

        // 查询片区每日交易额
        $res = HttpClient::create()->request('GET', env('url.shop_prefix') . '/api/order/statistics', [
            'query' => $parmas,
        ]);
        $response = json_decode($res->getContent(), true);

        // 日实际交易金额
        $actualTradeAmount =  $response['data']['total_price'];

        // 月目标交易金额 2.1w x 实际导入户数(100) / 12(个月)
        $monthTargetTradeAmount = bcdiv(bcmul(21000, 100, 2),12,2);

        // 完成进度占比
        $rate = bcdiv($actualTradeAmount, $monthTargetTradeAmount, 2);
        // 个人每月总补贴 2.1w x 实际导入户数(100) / 12(个月) x  0.023
        $userMonthTotalMoney = bcmul(bcdiv(bcmul(21000, 100, 2),12,2), 0.023, 2);
        // 当日可获得补贴  个人每月总补贴 x 实际完成交易额率 x 自定义点率
        $dayTotalMoney = self::countDayMoney($userMonthTotalMoney, $rate);
        $dayMoney = bcdiv($dayTotalMoney, 2, 2);
        $dayDeposity = $dayMoney;
        return $this->success('成功', compact('rate', 'dayMoney', 'dayDeposity'));
    }

    public static function countDayMoney($userMonthTotalMoney, $rate)
    {
        // 个人每月总补贴 x 实际完成交易额率 x 自定义点率
        if ($rate == 0) {
            return 0;
        }
        // rate < 29%     50%
        if ($rate <= 0.29) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 0.5, 2);
        }
        // 30% <= rate < 39%     60%
        if (0.3 <= $rate && $rate <= 0.49) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 0.6, 2);
        }
        // 30% <= rate < 39%     70%
        if (0.5 <= $rate && $rate <= 0.69) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 0.7, 2);
        }
        // 30% <= rate < 39%     80%
        if (0.7 <= $rate && $rate <= 0.89) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 0.8, 2);
        }
        // rate >= 90%     90%
        if (0.9 <= $rate && $rate < 1) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 0.9, 2);
        }
        // rate >= 90%    100%
        if ( $rate >= 1) {
            return bcmul(bcmul($userMonthTotalMoney, $rate, 2), 1, 2);
        }
    }

    public function getFirstOrderLog()
    {
        $page = $this->request->param('page_no', 1);
        $limit = $this->request->param('page_size', 15);
        $firstOrderLogList = Db::name('user_invite_first_order_log')->where('user_id', $this->userId)->page($page, $limit)->select()->toArray();

        foreach ($firstOrderLogList as &$item) {
            $item['order_info'] = Db::connect('mysql2')->name('store_order')->alias('o')->field('o.total_num,p.store_name,p.image')->leftJoin('store_order_product op', 'o.order_id=op.order_id')->leftJoin('store_product p', 'op.product_id = p.product_id')->where('o.order_sn', $item['order_no'])->select();
        }
        $data = [
            'lists' => $firstOrderLogList,
            'count' => Db::name('user_invite_first_order_log')->where('user_id', $this->userId)->count(),
            'total_money' => Db::name('user_invite_first_order_log')->where('user_id', $this->userId)->sum('order_money'),
            'page_no' => $page,
            'page_size' => $limit,
        ];
        return $this->success('成功', $data);
    }
}