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

namespace app\common\logic;

use app\common\model\WageDiy as mWageDiy;
use app\common\model\Role as mRole;
use app\common\validate\WageDiy as vWageDiy;

class WageDiy
{
    private $cache_name = 'wage_diy';

    public function detail($role_id)
    {
        $detail = [];
        if (!empty($role_id)) {
            $mWageDiy = new mWageDiy();
            $where = [];
            $where[] = ['role_id', '=', $role_id];
            $detail = $mWageDiy -> where($where) -> find();
            if (!empty($detail)) {
                $detail['ratio'] = json_decode($detail['ratio']);
                $detail['bind_ratio'] = json_decode($detail['bind_ratio']);
                $detail['elder_bonus'] = json_decode($detail['elder_bonus']);
                $detail['other'] = json_decode($detail['other']);
            } else {
                $detail = [];
            }
        }
        return $detail;
    }

    public function lists()
    {
        $result = ['code' => 200, 'msg' => '', 'data' => []];
        $where = [];
        $field = 'wd.id,r.id as role_id,r.name role_name,base_wage,grow_wage,ratio,bind_ratio,full_reward,overtime_pay,
        room,food,other,statement_date,wd.create_time,wd.update_time,elder_bonus,elder_time';
        $mWageDiy = new mWageDiy();
        $mWageDiyObj = $mWageDiy -> alias('wd')
                -> join(['oa_role' => 'r'], 'wd.role_id = r.id', 'right')
                -> field($field)
                -> where($where)
                -> order('r.id')
                -> select();
        if (!empty($mWageDiyObj)) {
            foreach ($mWageDiyObj as &$v) {
                $v['base_wage'] = $v['base_wage'] ? $v['base_wage'] : 0;
                $v['grow_wage'] = $v['grow_wage'] ? $v['grow_wage'] : 0;
                $v['ratio'] = $v['ratio'] ? json_decode($v['ratio'], true) : [];
                $v['bind_ratio'] = $v['bind_ratio'] ? json_decode($v['bind_ratio'], true) : [];
                $v['full_reward'] = $v['full_reward'] ? $v['full_reward'] : 0;
                $v['overtime_pay'] = $v['overtime_pay'] ? $v['overtime_pay'] : 0;
                $v['room'] = $v['room'] ? $v['room'] : 0;
                $v['food'] = $v['food'] ? $v['food'] : 0;
                $v['other'] = $v['other'] ? json_decode($v['other'], true) : [];
                $v['elder_bonus'] = $v['elder_bonus'] ? json_decode($v['elder_bonus'], true) : [];
                $v['statement_date'] = $v['statement_date'] ? $v['statement_date'] : 0;
                $v['id'] = empty($v['id']) ? 0 : $v['id'];
            }
            unset($v);
        }
        $result['data'] = $mWageDiyObj;
        return $result;
    }

    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        if (empty($param['role_id'])) {
            $result['code'] = 5001;
            $result['msg'] = $this -> errorCode(5001);
            return $result;
        }
        $wageDiyDataObj = mWageDiy ::where('role_id', '=', $param['role_id']) -> find();
        if (empty($wageDiyDataObj)) {
            $wageDiyDataObj = new mWageDiy();
            $wageDiyDataObj -> role_id = $param['role_id'];
        }
        if (isset($param['base_wage'])) {
            $wageDiyDataObj -> base_wage = empty($param['base_wage']) ? 0 : intval($param['base_wage'] * 100);
        }
        if (isset($param['grow_wage'])) {
            $wageDiyDataObj -> grow_wage = empty($param['grow_wage']) ? 0 : intval($param['grow_wage'] * 100);
        }
        if (isset($param['full_reward'])) {
            $wageDiyDataObj -> full_reward = empty($param['full_reward']) ? 0 : intval($param['full_reward'] * 100);
        }
        if (isset($param['overtime_pay'])) {
            $wageDiyDataObj -> overtime_pay = empty($param['overtime_pay']) ? 0 : intval($param['overtime_pay'] * 100);
        }
        if (isset($param['room'])) {
            $wageDiyDataObj -> room = empty($param['room']) ? 0 : intval($param['room'] * 100);
        }
        if (isset($param['food'])) {
            $wageDiyDataObj -> food = empty($param['food']) ? 0 : intval($param['food'] * 100);
        }
        if (!empty($param['elder_time'])) {
            $wageDiyDataObj -> elder_time = $param['elder_time'];
        }
        if (!empty($param['statement_date'])) {
            $wageDiyDataObj -> statement_date = $param['statement_date'];
        }
        if (!empty($param['other'])) {
            $other = [];
            foreach ($param['other'] as $key => $val) {
                $other[$key]['title'] = $val['title'];
                $other[$key]['price'] = intval($val['price'] * 100);
            }
            $wageDiyDataObj -> other = json_encode($other, JSON_UNESCAPED_UNICODE);
        } elseif (empty($wageDiyDataObj -> other)) {
            $wageDiyDataObj -> other = '';
        }
        if (!empty($param['ratio'])) {
            $gears = [];
            foreach ($param['ratio'] as $value) {
                $value['max'] = intval($value['max'] * 100);
                $gears[$value['max']] = $value;
            }
            ksort($gears);
            $gears = array_values($gears);
            $wageDiyDataObj -> ratio = json_encode($gears, JSON_UNESCAPED_UNICODE);
        } elseif (empty($wageDiyDataObj -> ratio)) {
            $wageDiyDataObj -> ratio = '';
        }
        if (!empty($param['elder_bonus'])) {
            $bonus = [];
            foreach ($param['elder_bonus'] as $value) {
                $value['max'] = intval($value['max'] * 100);
                $value['bonus'] = intval($value['bonus'] * 100);
                $bonus[$value['max']] = $value;
            }
            ksort($bonus);
            $bonus = array_values($bonus);
            $wageDiyDataObj -> elder_bonus = json_encode($bonus, JSON_UNESCAPED_UNICODE);
        } elseif (empty($wageDiyDataObj -> elder_bonus)) {
            $wageDiyDataObj -> elder_bonus = '';
        }
        if (!empty($param['spread'])) {
            $spread = $param['spread'];
            if (!isset($spread['min'])) {
                $result['code'] = 5002;
                $result['msg'] = $this -> errorCode(5002);
                return $result;
            }
            $spread['deduct'] = intval(intval($spread['deduct']) * 100);
            $spread['reward'] = intval(intval($spread['reward']) * 100);
            $spread['max_reward'] = intval(intval($spread['max_reward']) * 100);
            $wageDiyDataObj -> spread = json_encode($spread, JSON_UNESCAPED_UNICODE);
        } elseif (empty($wageDiyDataObj -> spread)) {
            $wageDiyDataObj -> spread = '';
        }
        $wageDiyDataObj -> bind_ratio = '';
        if ($wageDiyDataObj -> save()) {
            return $result;
        }
        $result['code'] = 5000;
        $result['msg'] = $this -> errorCode(5000);
        return $result;

    }

    public function create($param)
    {

        $result = ['code' => 200, 'msg' => '修改成功', 'data' => []];
        $vWageDiy = new vWageDiy();
        if (!$vWageDiy -> check($param)) {
            $result['code'] = 5001;
            $result['msg'] = $vWageDiy -> getError();
            return $result;
        }
        $where = [];
        $where[] = ['role_id', '=', $param['role_id']];
        $where[] = ['r.status', 'in', '0,1'];
        $wageDiyId = mWageDiy ::alias('wd')
                -> join(['oa_role' => 'r'], 'wd.role_id = r.id', 'right')
                -> where($where) -> value('wd.id');
        $data = [];
        $data['role_id'] = $param['role_id'];
        $data['base_wage'] = intval($param['base_wage'] * 100);
        if (isset($param['grow_wage'])) {
            $data['grow_wage'] = empty($param['grow_wage']) ? 0 : intval($param['grow_wage'] * 100);
        }
        $spread = $param['spread'];
        if (empty($spread['min'])) {
            $spread['min'] = 0;
//            $result['code'] = 5002;
//            $result['msg'] = $this -> errorCode(5002);
//            return $result;
        }
        $spread['deduct'] = intval((int) $spread['deduct'] * 100);
        $spread['reward'] = intval((int) $spread['reward'] * 100);
        $spread['max_reward'] = intval((int) $spread['max_reward'] * 100);
        $data['spread'] = json_encode($spread, JSON_UNESCAPED_UNICODE);
        if (isset($param['full_reward'])) {
            $data['full_reward'] = empty($param['full_reward']) ? 0 : intval($param['full_reward'] * 100);
        }
        if (isset($param['overtime_pay'])) {
            $data['overtime_pay'] = empty($param['overtime_pay']) ? 0 : intval($param['overtime_pay'] * 100);
        }
        if (isset($param['room'])) {
            $data['room'] = empty($param['room']) ? 0 : intval($param['room'] * 100);
        }
        if (isset($param['food'])) {
            $data['food'] = empty($param['food']) ? 0 : intval($param['food'] * 100);
        }
        if (!empty($param['other'])) {
            $other = [];
            foreach ($param['other'] as $key => $val) {
                $other[$key]['title'] = $val['title'];
                $other[$key]['price'] = intval($val['price'] * 100);
            }
            $data['other'] = json_encode($other, JSON_UNESCAPED_UNICODE);
        } else {
            $data['other'] = '';
        }
        $data['statement_date'] = empty($param['statement_date']) ? 15 : $param['statement_date'];
        $gears = [];
        foreach ($param['ratio'] as $value) {
            $value['max'] = intval($value['max'] * 100);
            $gears[$value['max']] = $value;
        }
        ksort($gears);
        $gears = array_values($gears);
        $data['ratio'] = json_encode($gears, JSON_UNESCAPED_UNICODE);
        $bonus = [];
        foreach ($param['elder_bonus'] as $value) {
            $value['max'] = intval($value['max'] * 100);
            $value['bonus'] = intval($value['bonus'] * 100);
            $bonus[$value['max']] = $value;
        }
        ksort($bonus);
        $bonus = array_values($bonus);
        $data['elder_bonus'] = json_encode($bonus, JSON_UNESCAPED_UNICODE);
        $data['elder_time'] = empty($param['elder_time']) ? 6 : $param['elder_time'];
        $data['bind_ratio'] = '';
        if ($wageDiyId) {
            $data['id'] = $wageDiyId;
            mWageDiy ::update($data);
        } else {
            mWageDiy ::create($data);
        }
        return $result;
    }

    public function detailCache($id = 0)
    {
        if (!empty($id)) {
            $wage_diy = $this -> listsCache();
            return empty($wage_diy[$id]) ? [] : $wage_diy[$id];
        }
        return [];
    }

    public function listsCache($param = [], $paging = false)
    {
        //$expire = strtotime(date('Y-m-01').' +1 month');
        $expire = strtotime(date('Y-m-d')) + 86400;
        $cacheData = cache($this -> cache_name);
        $wage_diy = [];
        if (empty($cacheData) || $cacheData['expire_time'] < time()) {
            $result = $this -> lists();
            if ($result['code'] == 200 && count($result['data'])) {
                foreach ($result['data'] as $key => $value) {
                    $wage_diy[$value['role_id']] = $value;
                }
                cache($this -> cache_name, ['data' => $wage_diy, 'expire_time' => $expire]);
                cache('last_month_wage_diy', empty($cacheData) ? $wage_diy : $cacheData['data']);
            }
        } else {
            $wage_diy = $cacheData['data'];
        }
        if ($paging) {
            //数据分页
            $page = empty($param['page']) ? 1 : $param['page'];
            $limit = empty($param['limit']) ? 10 : $param['limit'];
            $start = ($page - 1) * $limit;
            $result['count'] = count($wage_diy);
            $result['page'] = $page;
            $result['limit'] = $limit;
            $result['data'] = array_slice($wage_diy, $start, $limit);
        } else {
            $result = $wage_diy;
        }
        return $result;
    }

    public function lastMonthlistsCache()
    {
        $this -> listsCache();
        return cache('last_month_wage_diy');
    }

    private function errorCode($code)
    {
        $errorCode = [
                5001 => '缺少标识',
                5002 => '缺少最低达标人数',
                5004 => '角色不存在，或已被删除',
                5005 => '请填写直充流水消费提成',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}