<?php

namespace app\money\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\money\model\EsopPlan as EsopPlanModel;
use app\money\model\EsopPlanRecord as EsopPlanRecordModel;
use app\member\model\Member as MemberModel;
use app\stock\model\StockList as StockListModel;
use Exception;
use think\Db;
use think\Hook;
use think\Cache;

/**
 * 期权计划管理控制器
 * @package app\money\admin
 */
class EsopplanRecord extends Admin
{
    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 获取查询条件
        $map = $this->getMap();
        $order = $this->getOrder();
        empty($order) && $order = 'id desc';
        // 数据列表
        $data_list = EsopPlanRecordModel::getAll($map, $order);
        // 分页数据 
        $page = $data_list->render();

        if (empty($_SERVER["QUERY_STRING"])) {
            $excel_url = substr(http() . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"], 0, -5) . "_export";
        } else {
            $excel_url = substr(http() . $_SERVER["SERVER_NAME"] . $_SERVER["PHP_SELF"], 0, -5) . "_export?" . $_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url, '', '')
        ];

        return ZBuilder::make('table')
            ->setSearch(['mid' => '用户ID', 'member.name' => '姓名', 'member.mobile' => '手机号']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['esop_plan_id', '期权计划id'],
                ['name', '姓名'],
                ['title', '股票'],
                ['affect', '金额'],
                ['surplus', '余额'],
                ['type', '类型'],
                ['info', '详情'],
                ['create_ip', '创建IP'],
                ['create_time', '创建时间', 'datetime'],
            ])
            ->hideCheckbox()
            ->setTableName('esop_plan')
            ->addTopButton('custem', $btn_excel)
            ->addOrder('id,create_time')
            ->setRowList($data_list)
            ->fetch(); // 渲染模板
    }
    
    /**
     * 自动任务，根据设定的期权计划执行释放期权
     */
    public function releaseEsop()
    {
        $where = [];
        //正在执行的期权计划
        $where['status'] = 1;
        //开始释放期权日期不大于当前日期
        $where['release_time'] = ['<=', date("Y-m-d")];
        //待行权值大于0
        $where['remain_account'] = ['>', 0];
        //已释放天数小于总天数，已释放期权小于期权总值
        $esop_plan_list = EsopPlanModel::where($where)->where("release_account<plan_account and days<duration")->select();
        foreach ($esop_plan_list as $k => $v) {
            //更加明细记录判断执行的当天是否已释放过
            $esop_plan_record_today = EsopPlanRecordModel::where("FROM_UNIXTIME(create_time,'%Y-%m-%d')=curdate()")
                ->where(['type' => 1, 'esop_plan_id' => $v['id']])->find();
            if (!$esop_plan_record_today) {
                //计算释放期权金额
                $affect = intval($v['plan_account'] / $v['duration']);
                //如果是最后一天，取余数
                if ($v['duration'] - $v['days'] == 1) {
                    $affect = $v['plan_account'] % $v['duration'];
                }
                //释放期权，更新期权表
                $updateData = [
                    'account' => $v['account'] + $affect,
                    'days' => $v['days'] + 1,
                    'remain_account' => $v['plan_account'] - $affect,
                    'release_account' => $v['release_account'] + $affect
                ];
                EsopPlanModel::where(['id' => $v['id']])->update($updateData);                
                //写入明细表
                $arr = [
                    'mid' => $v['mid'],
                    'stock_id' => $v['stock_id'],
                    'esop_plan_id' => $v['id'],
                    'affect' => $affect,
                    'surplus' => $v['account'] + $affect,
                    'heatos' => 1,
                    'type' => 1,
                    'info' => "自动行权，期权增加" . ($affect / 100),
                    'create_time' => time(),
                    'create_ip' => get_client_ip(1)
                ];
                EsopPlanRecordModel::create($arr);
            }
        }
    }
}
