<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\User as UserModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\WorkerForm as WorkerFormModel;
use app\common\model\WorkerIncome as WorkerIncomeModel;

use app\common\model\WorkerShareCate as WorkerShareCateModel;
use app\common\model\WorkerShare as WorkerShareModel;

use app\common\service\WorkerIncomeService;
use think\facade\Db;

class Worker extends BaseController
{

    // 推广海报
    public function shareList()
    {
        $catelist = WorkerShareCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('worker/sharelist', [
            'catelist' => $catelist,
        ]);
    }

    public function shareCateForm()
    {
        $id        = input('id/d', 0);
        $sharecate = WorkerShareCateModel::findOrEmpty($id);
        return view('worker/sharecateform', [
            'sharecate' => $sharecate,
        ]);
    }

    public function shareForm()
    {
        $id       = input('id/d', 0);
        $share    = WorkerShareModel::findOrEmpty($id);
        $catelist = WorkerShareCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('worker/shareform', [
            'share'    => $share,
            'catelist' => $catelist,
        ]);
    }

    public function editShareCate()
    {
        $id   = input('id/d', 0);
        $data = [
            'title'    => input('title/s', ""),
            'status'   => input('status/d', 1),
            'priority' => input('priority/d', 0),
        ];
        if (empty($id)) {
            $sharecate = WorkerShareCateModel::create($data);
        } else {
            $sharecate = WorkerShareCateModel::find($id);
            $sharecate->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function editShare()
    {
        $id   = input('id/d', 0);
        $data = [
            'cateid'   => input('cateid/d', 0),
            'title'    => input('title/s', ""),
            'tilpic'   => input('tilpic/s', ""),
            'status'   => input('status/d', 1),
            'priority' => input('priority/d', 0),
        ];
        if (empty($id)) {
            $share = WorkerShareModel::create($data);
        } else {
            $share = WorkerShareModel::find($id);
            $share->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function listShareCate()
    {
        $limit = input('limit');
        $page  = input('page');
        $list  = WorkerShareCateModel::withCount('workerShare')->order(['priority' => 'desc', 'id' => 'desc'])->limit($limit)->page($page)->append(['status_text'])->select();
        $count = WorkerShareCateModel::count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function listShare()
    {
        $limit  = input('limit');
        $page   = input('page');
        $map    = [];
        $cateid = input('cateid/d', 0);
        if (!empty($cateid)) {
            $map[] = ['cateid', '=', $cateid];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = WorkerShareModel::with('workerShareCate')->where($map)->order(['priority' => 'desc', 'id' => 'desc'])->limit($limit)->page($page)->append(['status_text', 'stype_text'])->select();
        $count = WorkerShareModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function fieldShareCate()
    {
        $id   = input('id/d', 0);
        $info = WorkerShareCateModel::find($id);
        $info->save([
            input('field/s') => input('value/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function fieldShare()
    {
        $id   = input('id/d', 0);
        $info = WorkerShareModel::find($id);
        $info->save([
            input('field/s') => input('value/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delShareCate()
    {
        $id        = input('id/d', 0);
        $sharecate = WorkerShareCateModel::where('id', $id)->select();
        WorkerShareModel::where('cateid', '=', $id)->delete();
        $result = $sharecate->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function delShare()
    {
        $id     = input('id/d', 0);
        $share  = WorkerShareModel::where('id', $id)->select();
        $result = $share->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    // 申请注册经纪人
    public function fworkerList()
    {
        return view('worker/fworkerlist');
    }

    public function fworkerForm()
    {
        $id      = input('id/d, 0');
        $fworker = WorkerFormModel::findOrEmpty($id);
        return view('worker/fworkerform', [
            'fworker' => $fworker,
        ]);
    }

    public function editFworker()
    {
        $id      = input('id/d');
        $fworker = WorkerFormModel::findOrEmpty($id);
        $fworker->save([
            'comname'    => input('comname/s', ""),
            'address'    => input('address/s', ""),
            'details'    => input('details/s', ""),
            'realname'   => input('realname/s', ""),
            'mobile'     => input('mobile/s', ""),
            'address'    => input('address/s', ""),
            'comjobs'    => input('comjobs/s', ""),
            'status'     => input('status/d', 1),
            'remark'     => input('remark/s', ""),
            'createtime' => input('createtime/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function fieldFworker()
    {
        $id   = input('id/d', 0);
        $info = WorkerFormModel::findOrEmpty($id);
        $info->save([
            input('field/s') => input('value/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delFworker()
    {
        $idarr   = input('idarr/a');
        $fworker = WorkerFormModel::whereIn('id', $idarr)->select();
        $result  = $fworker->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listFworker()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['comname|realname', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = WorkerFormModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = WorkerFormModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }


    public function workerList()
    {
        return view('worker/workerlist');
    }

    public function workerForm()
    {
        $id     = input('id/d', 0);
        $worker = WorkerModel::with(['muser'])->findOrEmpty($id);
        return view('worker/workerform', [
            'worker' => $worker,
        ]);
    }

    public function editWorker()
    {
        $id    = input('id/d', "");
        $muser = UserModel::where(['mobile' => input('musermobile/s', '')])->findOrEmpty();
        if ($muser->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "关联的用户不存在。",
            ]));
        }
        $data     = [
            'userid'     => $muser->id,
            'wtype'      => input('wtype/d', 1),
            'title'      => input('title/s', ""),
            'ftitle'     => input('ftitle/s', ""),
            'tilpic'     => input('tilpic/s', ""),
            'realname'   => input('realname/s', ""),
            'mobile'     => input('mobile/s', ""),
            'weixin'     => input('weixin/s', ""),
            'latitude'   => input('latitude/f'),
            'longitude'  => input('longitude/f'),
            'province'   => input('province/s'),
            'city'       => input('city/s'),
            'district'   => input('district/s'),
            'address'    => input('address/s'),
            'picone'     => input('picone/s', ""),
            'pictwo'     => input('pictwo/s', ""),
            'picthr'     => input('picthr/s', ""),
            'details'    => input('details/s'),
            'priority'   => input('priority/d', 0),
            'remark'     => input('remark/s', ""),
            'status'     => input('status/d', 1),
            'idcardzpic' => input('idcardzpic/s', ""),
            'idcardfpic' => input('idcardfpic/s', ""),
        ];
        $password = input('password/s', "");
        if (empty($id)) {
            $data['createtime'] = time();
            $worker             = WorkerModel::create($data);
        } else {
            $worker = WorkerModel::find($id);
            $worker->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function fieldWorker()
    {
        $id   = input('id/d', 0);
        $info = WorkerModel::findOrEmpty($id);
        if ($info->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在。",
            ]));
        } else {
            $info->save([
                input('field/s') => input('value', ""),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delWorker()
    {
        $access_admin = session('access_admin');
        $password     = input('password');
        if ($access_admin['password'] !== md5($password)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "操作密码验证失败",
            ]));
        }
        $idarr  = input('idarr/a');
        $result = Db::name('worker')->whereIn('id', $idarr)->update(['deletetime' => time()]);
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listWorker()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $keywords = input('keywords/s', "");
        if (!empty($keywords)) {
            $map[] = ['title|realname', 'like', '%' . $keywords . '%'];
        }
        $wtype = input('wtype/d', 0);
        if (!empty($wtype)) {
            $map[] = ['wtype', '=', $wtype];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = WorkerModel::with(['muser'])->where($map)->order(['priority' => 'DESC', 'id' => 'DESC'])->limit($limit)->page($page)->append(['wtype_text', 'status_text'])->select();
        //dd($list);
        $count = WorkerModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        //var_dump(json_decode($list,true));
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function incomeList()
    {
        $workerid = input('workerid');
        if (empty($workerid)) {
            exit("未查询到数据");
        }

        return view('worker/incomelist', [
            'workerid' => $workerid,
        ]);
    }

    public function listIncome()
    {
        $workerid = input('workerid');
        if (empty($workerid)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }

        $limit = input('limit/d', 20);
        $page  = input('page/d', 1);
        $map   = [
            ['workerid', '=', $workerid],
        ];
        $list  = WorkerIncomeModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->select();
        $count = WorkerIncomeModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function settleIncome()
    {
        $workerid = input('workerid');
        $value    = input('value');

        if (empty($workerid) || $value <= 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "参数错误",
            ]));
        }

        $worker = WorkerModel::find($workerid);
        if (empty($worker)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        if ($worker['income'] < $value) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "公司收益不足",
            ]));
        }

        $incomeService = new WorkerIncomeService();
        $incomeService->add($workerid, -$value, '商家结算', '平台与劳务公司线下结算');

        exit(json_encode([
            'code' => 0,
            'msg'  => "",
        ]));
    }
}
