<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\model\WageMonth as mWageMonth;
use app\common\model\Manager as mManager;

class Wage extends Base
{
    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 10 : $param['limit'];
        $result['count'] = 0;
        $result['page'] = $page;
        $result['limit'] = $limit;
        $where = [];
        $manager_id = $this -> getManagerId();
        // 查询当前用户所有子用户
        $stat = new Stat();
        if (config('administrators_id') != $manager_id) {
            $subManagerIds = $stat -> getSubManagerIds($manager_id);
            $where[] = ['manager_id', 'in', $subManagerIds];
        }
        if (!empty($param['manager_id'])) {
            $where[] = ['manager_id', '=', $param['manager_id']];
        }
        if (!empty($param['start_time']) && empty($param['end_time'])) {
            $start_time = strtotime($param['start_time'] . '-01');
            $where[] = ['date_time', '=', $start_time];
        } else if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $start_time = strtotime($param['start_time'] . '-01');
            $end_time = strtotime("+1 months", strtotime($param['end_time'] . '-01')) - 1;
            $where[] = ['date_time', 'between time', [$start_time, $end_time]];
        }
        if (empty($param['export'])) {
            $field = 'id, manager_id, year, month, base_wage, grow_wage,elder_bonus, full_reward, overtime_pay, room, food, other, recharge, total_salary, status,send_manager_id';
            $mWageMonthData = mWageMonth ::field($field) -> where($where) -> page($page, $limit) -> order('id desc') -> select();
            $result['count'] = mWageMonth ::where($where) -> count('id');
            foreach ($mWageMonthData as $key => &$wage) {
                $wage['other'] = empty($wage['other']) ? [] : json_decode($wage['other'], true);
                $manager_name = mManager ::where('id', '=', $wage['manager_id']) -> value('name');
                $wage['manager_name'] = $manager_name;
                $send_name = mManager ::where('id', '=', $wage['send_manager_id']) -> value('name');
                $wage['send_name'] = empty($send_name) ? '--' : $send_name;
            }
            $result['page'] = $page;
            $result['limit'] = $limit;
            $result['data'] = empty($mWageMonthData) ? [] : $mWageMonthData;
            return $result;
        } else {
            //导出列表
            $field = 'id, manager_id, year, month, base_wage, grow_wage, elder_bonus, full_reward, overtime_pay, room, food, other, recharge, total_salary, status,send_manager_id';
            $mWageMonthData = mWageMonth ::field($field) -> where($where) -> order('id desc') -> select();
            foreach ($mWageMonthData as $key => $wage) {
                $mWageMonthData[$key]['other'] = empty($wage['other']) ? [] : json_decode($wage['other'], true);
                $manager_name = mManager ::where('id', '=', $wage['manager_id']) -> value('name');
                $mWageMonthData[$key]['manager_name'] = $manager_name;
                $send_name = mManager ::where('id', '=', $wage['send_manager_id']) -> value('name');
                $mWageMonthData[$key]['send_name'] = empty($send_name) ? '--' : $send_name;
            }
            $excel = new Excel();
            $xlsName = "工资结算表";
            $xlsCell = array(
                    array('id', '工资单ID'),
                    array('date', '发放时间'),
                    array('manager_name', '账号'),
                    array('manager_id', '账号ID'),
                    array('base_wage', '底薪'),
                    array('grow_wage', '成长基金'),
                    array('elder_bonus', '元老奖金'),
                    array('recharge', '消费提成'),
                    array('full_reward', '全勤奖'),
                    array('overtime_pay', '加班费'),
                    array('room', '住宿费'),
                    array('food', '餐费'),
                    array('other', '其他'),
                    array('wage', '工资'),
                    array('send_name', '发放人'),
                    array('status', '状态'),
            );
            $xlsData = empty($mWageMonthData) ? [] : $mWageMonthData;
            if (!empty($xlsData)) {
                $totalData = ['id' => '总计', 'date' => '--', 'manager_name' => '--', 'manager_id' => '--', 'base_wage' => 0, 'grow_wage' => 0, 'elder_bonus' => 0, 'recharge' => 0, 'full_reward' => 0, 'overtime_pay' => 0, 'room' => 0, 'food' => 0, 'other' => 0, 'wage' => 0, 'send_name' => '--', 'status' => '--'];
                foreach ($xlsData as &$v) {
                    $v['date'] = $v['year'] . '-' . $v['month'];
                    $v['base_wage'] = round($v['base_wage'] / 100, 2);
                    $v['grow_wage'] = round($v['grow_wage'] / 100, 2);
                    $v['elder_bonus'] = round($v['elder_bonus'] / 100, 2);
                    $v['recharge'] = round($v['recharge'] / 100, 2);
                    $v['full_reward'] = round($v['full_reward'] / 100, 2);
                    $v['overtime_pay'] = round($v['overtime_pay'] / 100, 2);
                    $v['room'] = round($v['room'] / 100, 2);
                    $v['food'] = round($v['food'] / 100, 2);
                    $other_str = '';
                    $bz = 0;
                    if (!empty($v['other'])) {
                        foreach ($v['other'] as $item) {
                            $other_str .= $item['title'] . '：' . round($item['price'] / 100, 2) . ' ';
                            $bz += $item['price'];
                        }
                    }
                    $v['other'] = $other_str;
                    if ($v['status'] == '0') {
                        $v['status'] = '待发放';
                    } elseif ($v['status'] == '1') {
                        $v['status'] = '已发放';
                    } else {
                        $v['status'] = '已通知	';
                    }
                    $v['wage'] = $v['base_wage'] + $v['grow_wage'] + $v['recharge'] + $v['full_reward'] + $v['overtime_pay'] + $v['room'] + $v['food'] + round($bz / 100, 2) + $v['elder_bonus'];
                    //总计发放
                    foreach ($totalData as $field => &$data) {
                        if (is_numeric($data)) {
                            if ($field == 'other') {
                                $data += round($bz / 100, 2);
                            } else {
                                $data += $v[$field];
                            }
                        }
                    }
                    unset($data);
                }
            }
            $xlsData[] = $totalData;
            $excel -> exportExcel($xlsName, $xlsCell, $xlsData);
        }

    }

    public function manager($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 10 : $param['limit'];
        $where = [];
        if ($this -> getManagerId() != config('administrators_id')) {
            $where[] = ['manager_id', '=', $this -> getManagerId()];
        }
        $where[] = ['status', 'in', [1, 2]];
        $field = 'id, manager_id, year, month, base_wage, full_reward, grow_wage, elder_bonus, overtime_pay, room, food, other, recharge, total_salary';
        $mWageMonthData = mWageMonth ::field($field) -> where($where) -> page($page, $limit) -> order('id desc') -> select();
        $result['count'] = mWageMonth ::where($where) -> count('id');
        // 获取员工列表
        $managerLists = mManager ::column('id,name');
        foreach ($mWageMonthData as $key => $data) {
            $mWageMonthData[$key]['other'] = json_decode($data['other'], true);
            $mWageMonthData[$key]['manager_name'] = $managerLists[$data['manager_id']];
        }
        $result['page'] = $page;
        $result['limit'] = $limit;
        $result['data'] = empty($mWageMonthData) ? [] : $mWageMonthData;
        return $result;
    }

    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $saveData = [];
        if (empty($param['id'])) {
            $result['code'] = 9001;
            $result['msg'] = $this -> errorCode(9001);
            return $result;
        }
        if (isset($param['base_wage'])) {
            $saveData['base_wage'] = empty($param['base_wage']) ? 0 : intval($param['base_wage'] * 100);
        }
        if (isset($param['full_reward'])) {
            $saveData['full_reward'] = empty($param['full_reward']) ? 0 : intval($param['full_reward'] * 100);
        }
        if (isset($param['overtime_pay'])) {
            $saveData['overtime_pay'] = empty($param['overtime_pay']) ? 0 : intval($param['overtime_pay'] * 100);
        }
        if (isset($param['room'])) {
            $saveData['room'] = empty($param['room']) ? 0 : intval($param['room'] * 100);
        }
        if (isset($param['food'])) {
            $saveData['food'] = empty($param['food']) ? 0 : intval($param['food'] * 100);
        }
        if (!empty($param['other'])) {
            $saveData['other'] = $param['other'];
        }
        if (isset($param['grow_wage'])) {
            $saveData['grow_wage'] = empty($param['grow_wage']) ? 0 : intval($param['grow_wage'] * 100);
        }
        if (isset($param['elder_bonus'])) {
            $saveData['elder_bonus'] = empty($param['elder_bonus']) ? 0 : intval($param['elder_bonus'] * 100);
        }
        if (empty($saveData)) {
            $result['code'] = 9004;
            $result['msg'] = $this -> errorCode(9004);
            return $result;
        }
        $wageData = mWageMonth ::where('id', '=', $param['id']) -> find();
        if (empty($wageData)) {
            $result['code'] = 9001;
            $result['msg'] = $this -> errorCode(9001);
            return $result;
        }
        if ($wageData['status'] != 0) {
            $result['code'] = 9003;
            $result['msg'] = $this -> errorCode(9003);
            return $result;
        }
        $wageData = $wageData -> getData();
        $wageData['other'] = empty($wageData['other']) ? [] : json_decode($wageData['other'], true);
        $wageData = array_merge($wageData, $saveData);
        $other_total = 0;
        if (!empty($param['other'])) {
            foreach ($wageData['other'] as &$data) {
                $data['price'] = $data['price'] * 100;
                $other_total += $data['price'];
            }
        } else {
            foreach ($wageData['other'] as &$data) {
                $other_total += $data['price'];
            }
        }
        $saveData['other'] = json_encode($wageData['other'], JSON_UNESCAPED_UNICODE);
        $saveData['total_salary'] = $wageData['base_wage'] + $wageData['grow_wage'] + $wageData['full_reward'] + $wageData['overtime_pay'] + $wageData['room'] + $wageData['food'] + $wageData['recharge'] + $other_total + $wageData['elder_bonus'];
        $saveData['id'] = $wageData['id'];
        mWageMonth ::update($saveData);
        return $result;
    }

    public function send($param)
    {
        $result = ['code' => 200, 'msg' => '发放成功', 'data' => []];
        if (empty($param['id'])) {
            $result['code'] = 9001;
            $result['msg'] = $this -> errorCode(9001);
            return $result;
        }
        $saveData = [];
        $saveData['id'] = $param['id'];
        $saveData['send_manager_id'] = $this -> getManagerId();
        $saveData['status'] = 1;
        if (mWageMonth ::update($saveData)) {
            return $result;
        }
        $result['code'] = 9002;
        $result['msg'] = $this -> errorCode(9002);
        return $result;
    }

    public function message($param)
    {
        $result = ['code' => 200, 'msg' => '通知成功', 'data' => []];
        if (empty($param['id'])) {
            $result['code'] = 9001;
            $result['msg'] = $this -> errorCode(9001);
            return $result;
        }
        $wageData = mWageMonth ::field('id, manager_id, month,status') -> where('id', '=', $param['id']) -> find();
        if (empty($wageData)) {
            $result['code'] = 9001;
            $result['msg'] = $this -> errorCode(9001);
            return $result;
        }
        if ($wageData['status'] != '1') {
            $result['code'] = 9007;
            $result['msg'] = $this -> errorCode(9007);
            return $result;
        }
        $managerData = mManager ::field('name,realname,mobile') -> where('id', '=', $wageData['manager_id']) -> find();
        if (!empty($managerData)) {
            $name = empty($managerData['realname']) ? $managerData['name'] : $managerData['realname'];
            $sendData = ['account' => $name, 'month' => $wageData['month']];
            $smsRes = send_wage_msg($managerData['mobile'], json_encode($sendData));
            if ($smsRes == 0) {
                mWageMonth ::update(['id' => $wageData['id'], 'status' => 2]);
            } elseif ($smsRes == 2) {
                $result['code'] = 9008;
                $result['msg'] = $this -> errorCode(9008);
            } else {
                $result['code'] = 9006;
                $result['msg'] = $this -> errorCode(9006);
            }
        } else {
            $result['code'] = 9005;
            $result['msg'] = $this -> errorCode(9005);
        }
        return $result;
    }

    private function errorCode($code)
    {
        $errorCode = [
                9001 => '缺少标识',
                9002 => '工资发放失败',
                9003 => '工资已发放,无法修改',
                9004 => '无修改项',
                9005 => '未找到相关人员',
                9006 => '短信发送失败',
                9007 => '请先确认发放薪资,再短信通知',
                9008 => '短信功能已关闭',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}
