<?php

namespace app\crontab\controller;

use app\common\logic\Stat;
use app\common\model\Manager as mManager;
use app\common\model\WageDiy as mWageDiy;
use app\common\model\WageMonth as mWageMonth;

class Wage extends Base
{


    /**
     * @生成员工薪资
     *
     * @author: zsl
     * @since: 2021/3/11 19:00
     */
    public function generate()
    {
        set_time_limit(0);
        $result = ['code' => 1, 'msg' => '员工薪资生成成功', 'data' => []];
        //获取当前是几号
        $currentDay = date("d");
        //获取自定义薪资配置
        $mWageDiy = new mWageDiy();
        $field = "w.id,role_id,statement_date,base_wage,grow_wage,ratio,elder_bonus,full_reward,overtime_pay,
        room,food,other";
        $where = [];
        $where[] = ['r.status', '=', 1];
        $wageDiy = $mWageDiy -> alias('w')
                -> field($field)
                -> join(['oa_role' => 'r'], 'w.role_id = r.id')
                -> where($where)
                -> select();
        if (!empty($wageDiy)) {
            foreach ($wageDiy as $v) {
                //判断当前是否为出账日期
                if ($v['statement_date'] == $currentDay) {
                    $this -> statUserWage($v);
                }
            }
        }
        return json($result);
    }


    /**
     * @统计用户薪资
     *
     * @throws \Exception
     * @since: 2021/3/13 11:45
     * @author: zsl
     */
    private function statUserWage($wageDiy)
    {
        //获取角色所有员工id
        $mManager = new mManager();
        $stat = new Stat();
        $where = [];
        $where[] = ['role_id', '=', $wageDiy['role_id']];
        $managerIds = $mManager -> auth() -> where($where) -> column('manager_id');
        if (empty($managerIds)) {
            return false;
        }
        //生成员工上月薪资数据
        $mWageMonth = new mWageMonth();
        $lastMonth = $this -> getLastMonth();
        $year = date("Y", $lastMonth[0]);
        $month = date("m", $lastMonth[0]);
        $wageData = [];
        foreach ($managerIds as $k => $managerId) {
            //检查员工薪资是否生成过
            $where = [];
            $where[] = ['manager_id', '=', $managerId];
            $where[] = ['year', '=', $year];
            $where[] = ['month', '=', $month];
            $wageMonthInfo = $mWageMonth -> where($where) -> find();
            if (!empty($wageMonthInfo)) {
                return false;
            }
            //获取员工数据
            $managerData = $stat -> data($managerId, $lastMonth[0], $lastMonth[1], false);
            $wageData[$k]['manager_id'] = $managerId;
            $wageData[$k]['year'] = $year;
            $wageData[$k]['month'] = $month;
            $wageData[$k]['date_time'] = strtotime($year.'-'.$month.'-01');
            $wageData[$k]['base_wage'] = $wageDiy['base_wage']; //基本工资
            $wageData[$k]['grow_wage'] = $wageDiy['grow_wage']; //成长基金
            $wageData[$k]['elder_bonus'] = $this -> getElderBonusNum($wageDiy['elder_bonus'], $managerData['recharge_pay_sum'] * 100); //元老奖励
            $wageData[$k]['full_reward'] = $wageDiy['full_reward']; //全勤奖
            $wageData[$k]['overtime_pay'] = $wageDiy['overtime_pay']; //加班费
            $wageData[$k]['room'] = $wageDiy['room']; //住宿费
            $wageData[$k]['food'] = $wageDiy['food']; //餐费
            $wageData[$k]['other'] = $wageDiy['other']; //其他
            $wageData[$k]['recharge'] = $this -> getRechargeNum($wageDiy['ratio'], $managerData['recharge_pay_sum'] * 100); //消费提成
            $wageData[$k]['total_salary'] = $this -> getTotalSalary($wageData[$k]); //总工资
            $wageData[$k]['send_manager_id'] = 0; //发放人id
            $wageData[$k]['status'] = 0; //发放人id
        }
        $result = $mWageMonth -> saveAll($wageData);
        if (false === $result) {
            return false;
        }
        return true;
    }


    /**
     * @获取元老奖励薪资
     *
     * @author: zsl
     * @since: 2021/3/13 14:14
     */
    private function getElderBonusNum($rule, $pay_num)
    {
        $elderRule = json_decode($rule, true);
        if (!$elderRule) {
            return 0;
        }
        $sort = array_column($elderRule, 'max');
        array_multisort($sort, SORT_DESC, $elderRule);
        foreach ($elderRule as $v) {
            if ($pay_num > $v['max']) {
                return $v['bonus'];
            }
        }
        return 0;
    }

    /**
     * @获取消费提成
     *
     * @author: zsl
     * @since: 2021/3/13 14:39
     */
    private function getRechargeNum($rule, $pay_num)
    {
        $elderRule = json_decode($rule, true);
        if (!$elderRule) {
            return 0;
        }
        $sort = array_column($elderRule, 'max');
        array_multisort($sort, SORT_DESC, $elderRule);
        foreach ($elderRule as $v) {
            if ($pay_num > $v['max']) {
                $recharge = round($pay_num * $v['ratio'] / 100, 0);
                return $recharge;
            }
        }
        return 0;
    }

    /**
     * @获取总工资
     *
     * @author: zsl
     * @since: 2021/3/13 14:42
     */
    private function getTotalSalary($wageData)
    {
        $other = json_decode($wageData['other'], true);
        if ($other) {
            $otherTotal = array_sum(array_column($other, 'price'));
        } else {
            $otherTotal = 0;
        }
        $total = $wageData['base_wage'] + $wageData['grow_wage'] + $wageData['elder_bonus'] + $wageData['full_reward'] + $wageData['overtime_pay']
                + $wageData['room'] + $wageData['food'] + $wageData['recharge'] + $otherTotal;
        return $total;
    }


    /**
     * @获取上个月开始和结束时间
     *
     * @author: zsl
     * @since: 2021/3/13 11:56
     */
    private function getLastMonth()
    {
        $m = date('Y-m-d', mktime(0, 0, 0, date('m') - 1, 1, date('Y')));
        $t = date('t', strtotime($m)); //上个月共多少天
        $start = mktime(0, 0, 0, date('m') - 1, 1, date('Y')); //上个月的开始日期
        $end = mktime(0, 0, 0, date('m') - 1, $t, date('Y')) + 86399; //上个月的结束日期
        return [$start, $end];
    }


}
