<?php
namespace app\admin\controller;

use think\facade\Session;
use app\admin\BaseController;
use app\common\model\ReportFactory as ReportFactoryModel;
use app\common\model\ReportEntry as ReportEntryModel;
use app\common\model\ReportOrder as ReportOrderModel;
use app\common\model\ReportOrderlog as ReportOrderlogModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;

use app\common\validate\ReportFactory as ReportFactoryValidate;
use think\exception\ValidateException;

use PHPExcel_IOFactory;
use PHPExcel;

class Report extends BaseController
{
    
    // 发单记录
    public function orderlog()
    {
        $orderid = input('orderid/d', 0);
        $order = ReportOrderModel::findOrEmpty($orderid);
        $factorylist = ReportFactoryModel::order(['id'=>'desc'])->select();
        $workerlist = WorkerModel::with('agent')->order(['id'=>'desc'])->select();
        return view('report/orderlog', [
            'workerlist'	=> $workerlist,
            'factorylist'	=> $factorylist,
            'order'			=> $order
        ]);
    }
    
    public function addOrderlog()
    {
        $orderid = input('orderid/d', 0);
        $order = ReportOrderModel::findOrEmpty($orderid);
        if ($order->isEmpty()) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "订单信息不存在。"
            )));
        }
        $refpolicy = input('refpolicy/s', "");
        if (empty($refpolicy)) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "返费政策不能为空。"
            )));
        }
        $remark = input('remark/s', "");
        $agentarr = input('agentarr/a', array());
        if (empty($agentarr)) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "推送代理门店必选。"
            )));
        }
        $addlist = array();
        foreach ($agentarr as $wkey=>$wval) {
            foreach ($wval as $akey=>$aval) {
                $addlist[] = array(
                    'orderid'		=> $orderid,
                    'workerid'		=> $wkey,
                    'agentid'		=> $aval,
                    'refpolicy'		=> $refpolicy,
                    'remark'		=> $remark,
                    'status'		=> 1,
                    'createtime'	=> time()
                );
            }
        }
        $orderlog = new ReportOrderlogModel;
        $orderlog->saveAll($addlist);
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function listOrderlog()
    {
        $orderid = input('orderid/d', 0);
        $limit = input('limit/d', 20);
        $page = input('page/d', 1);
        $map = array();
        $map[] = ['orderid', '=', $orderid];
        $keywords = input('keywords/s', "");
        if (!empty($keywords)) {
            $map[] =['refpolicy', 'like', '%'.$keywords.'%'];
        }
        $workeragentarr = explode(",", input('workeragent/s'));
        $workerid = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        $agentid = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
        if (!empty($agentid)) {
            $map[] = ['agentid', '=', $agentid];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = ReportOrderlogModel::with(['reportOrder','worker','agent'])->where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = ReportOrderlogModel::where($map)->count();
        if ($count==0) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "未查询到数据"
            )));
        }
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> "",
            'count' => $count,
            'data'  => $list
        )));
    }
    
    public function fieldOrderlog()
    {
        $id = input('id/d', 0);
        $orderlog = ReportOrderlogModel::findOrEmpty($id);
        if ($orderlog->isEmpty()) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "信息不存在"
            )));
        } else {
            $orderlog->save([
                input('field/s')  => input('value')
            ]);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function delOrderlog()
    {
        $idarr = input('idarr/a');
        $orderlog = ReportOrderlogModel::whereIn('id', $idarr)->select();
        $orderlog->delete();
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> ""
        )));
    }
    
    
    
    // 发单信息
    public function orderList()
    {
        $factorylist = ReportFactoryModel::order(['id'=>'desc'])->select();
        return view('report/orderlist', [
            'factorylist'	=> $factorylist
        ]);
    }
    
    public function listOrder()
    {
        $limit = input('limit/d', 20);
        $page = input('page/d', 1);
        $map = array();
        $keywords = input('keywords/s', "");
        if (!empty($keywords)) {
            $map[] =['title', 'like', '%'.$keywords.'%'];
        }
        $factoryid = input('factoryid/d', 0);
        if (!empty($factoryid)) {
            $map[] = ['factoryid', '=', $factoryid];
        }
        $reftype = input('reftype/d');
        if (!empty($reftype)) {
            $map[] = ['reftype', '=', $reftype];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = ReportOrderModel::with(['reportFactory'])->where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['reftype_text','status_text'])->select();
        $count = ReportOrderModel::where($map)->count();
        if ($count==0) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "未查询到数据"
            )));
        }
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> "",
            'count' => $count,
            'data'  => $list
        )));
    }
    
    public function fieldOrder()
    {
        $id = input('id/d', 0);
        $order = ReportOrderModel::findOrEmpty($id);
        if ($order->isEmpty()) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "信息不存在"
            )));
        } else {
            $order->save([
                input('field/s')  => input('value')
            ]);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function orderForm()
    {
        $id = input('id/d', 0);
        $order = ReportOrderModel::findOrEmpty($id);
        $factorylist = ReportFactoryModel::order(['id'=>'desc'])->select();
        return view('report/orderform', [
            'factorylist'	=> $factorylist,
            'order'			=> $order
        ]);
    }
    
    public function editOrder()
    {
        $id = input('id/d');
        $order = ReportOrderModel::findOrEmpty($id);
        $data = array(
            'factoryid'			=> input('factoryid/d', 0),
            'title'				=> input('title/s', ""),
            'startdate'			=> input('startdate/s', ""),
            'reftype'			=> input('reftype/d', 1),
            'employ'			=> input('employ/s', ""),
            'prompt'			=> input('prompt/s', ""),
            'status'			=> input('status/d', 0),
            'createtime'		=> input('createtime/s', "")
        );
        if ($order->isEmpty()) {
            $order = new ReportOrderModel;
            $order->save($data);
        } else {
            $order->save($data);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function delOrder()
    {
        $idarr = input('idarr/a');
        $order = ReportOrderModel::whereIn('id', $idarr)->select();
        ReportOrderlogModel::whereIn('orderid', $idarr)->delete();
        $order->delete();
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> ""
        )));
    }
    
    
    // 报备名单
    public function entryList()
    {
        $workerlist = WorkerModel::with('agent')->order(['id'=>'desc'])->select();
        $factorylist = ReportFactoryModel::order(['id'=>'desc'])->select();
        return view('report/entrylist', [
            'workerlist'	=> $workerlist,
            'factorylist'	=> $factorylist
        ]);
    }
    
    public function entryForm()
    {
        $id = input('id/d, 0');
        $entry = ReportEntryModel::findOrEmpty($id);
        $workerlist = WorkerModel::with('agent')->order(['id'=>'desc'])->select();
        $factorylist = ReportFactoryModel::order(['id'=>'desc'])->select();
        return view('report/entryform', [
            'workerlist'	=> $workerlist,
            'factorylist'	=> $factorylist,
            'entry'			=> $entry
        ]);
    }
    
    public function entryImport()
    {
        $workerlist = WorkerModel::with('agent')->order(['id'=>'desc'])->select();
        return view('report/entryimport', [
            'workerlist'	=> $workerlist
        ]);
    }
    
    public function importEntry()
    {
        $execlfile = input('execlfile/s', "");
        if (empty($execlfile)) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "请上传导入文件"
            )));
        }
        $filedata = read_excel($execlfile);
        $factorylist = ReportFactoryModel::where(['status'=>1])->column('idnumber,id,title', 'idnumber');
        $workeragentarr = explode(",", input('workeragent/s'));
        $workerid = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
        $agentid = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
        $createtime = input('createtime/s', "");
        $entry = new ReportEntryModel;
        $data = array();
        $sucnumber = 0;
        $errnumber = 0;
        foreach ($filedata as $k=>$v) {
            $idnumber = trim($v[7]);
            if (empty($factorylist[$idnumber])) {
                $errnumber++;
                continue;
            } else {
                $data[] = array(
                    'workerid'			=> $workerid,
                    'agentid'			=> $agentid,
                    'brokerid'			=> 0,
                    'realname'			=> $v[1],
                    'mobile'			=> $v[2],
                    'idcard'			=> $v[3],
                    'gender'			=> $v[4],
                    'nation'			=> $v[5],
                    'address'			=> $v[6],
                    'factoryid'			=> $factorylist[$idnumber]['id'],
                    'startdate'			=> $v[8],
                    'enddate'			=> $v[9],
                    'reftype'			=> $v[10],
                    'refpolicy'			=> $v[11],
                    'agentremark'		=> $v[12],
                    'status'			=> 2,
                    'remark'			=> "",
                    'createtime'		=> $createtime
                );
                $sucnumber++;
            }
        }
        $entry->saveAll($data);
        exit(json_encode(array(
            'code' 	=> 0,
            'sucnumber'	=> $sucnumber,
            'errnumber'	=> $errnumber
        )));
    }
    
    public function editEntry()
    {
        $id = input('id/d');
        $entry = ReportEntryModel::findOrEmpty($id);
        $workeragentarr = explode(",", input('workeragent/s'));
        $workerid = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
        $agentid = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
        $data = array(
            'workerid'			=> $workerid,
            'agentid'			=> $agentid,
            'factoryid'			=> input('factoryid/d', 0),
            'realname'			=> input('realname/s'),
            'mobile'			=> input('mobile/s'),
            'idcard'			=> input('idcard/s'),
            'gender'			=> input('gender/s'),
            'nation'			=> input('nation/s'),
            'address'			=> input('address/s'),
            'startdate'			=> input('startdate/s'),
            'enddate'			=> input('enddate/s'),
            'reftype'			=> input('reftype/s'),
            'refpolicy'			=> input('refpolicy/s'),
            'agentremark'		=> input('agentremark/s'),
            'status'			=> input('status/d'),
            'remark'			=> input('remark/s'),
            'createtime'		=> input('createtime/s')
        );
        if ($entry->isEmpty()) {
            $data['brokerid'] = 0;
            $entry = new ReportEntryModel;
            $entry->save($data);
        } else {
            $entry->save($data);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function fieldEntry()
    {
        $id = input('id/d', 0);
        $entry = ReportEntryModel::findOrEmpty($id);
        if ($entry->isEmpty()) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "信息不存在"
            )));
        } else {
            $entry->save([
                input('field/s')  => input('value')
            ]);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function delEntry()
    {
        $idarr = input('idarr/a');
        $entry = ReportEntryModel::whereIn('id', $idarr)->select();
        $result = $entry->delete();
        if ($result) {
            exit(json_encode(array(
                'code' 	=> 0,
                'msg'	=> ""
            )));
        }
        exit(json_encode(array(
            'code' 	=> 1,
            'msg'	=> "删除失败，请稍后重试"
        )));
    }
    
    public function listEntry()
    {
        $limit = input('limit/d', 20);
        $page = input('page/d', 1);
        $map = array();
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] =['realname|idcard', 'like', '%'.$keywords.'%'];
        }
        $workeragentarr = explode(",", input('workeragent/s'));
        $workerid = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        $agentid = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
        if (!empty($agentid)) {
            $map[] = ['agentid', '=', $agentid];
        }
        $factoryid = input('factoryid/d');
        if (!empty($factoryid)) {
            $map[] = ['factoryid', '=', $factoryid];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = ReportEntryModel::with(['worker','agent','broker','reportFactory'])->where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = ReportEntryModel::where($map)->count();
        if ($count==0) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "未查询到数据"
            )));
        }
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> "",
            'count' => $count,
            'data'  => $list
        )));
    }
    
    public function exportEntry()
    {
        $map = array();
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] =['realname|idcard', 'like', '%'.$keywords.'%'];
        }
        $workeragentarr = explode(",", input('workeragent/s'));
        $workerid = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        $agentid = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
        if (!empty($agentid)) {
            $map[] = ['agentid', '=', $agentid];
        }
        $factoryid = input('factoryid/d');
        if (!empty($factoryid)) {
            $map[] = ['factoryid', '=', $factoryid];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $xlsData = ReportEntryModel::with(['worker','agent','broker','reportFactory'])->where($map)->order('id', 'DESC')->select()->toArray();
        $xlsCell = array(
            array('id','表ID'),
            array('worker.title','劳务公司'),
            array('agent.title','代理门店'),
            array('broker.title','经纪人'),
            array('report_factory.title','意向工厂'),
            array('realname','姓名'),
            array('mobile','手机号'),
            array('idcard','身份证号'),
            array('gender','性别'),
            array('nation','民族'),
            array('address','现居住地'),
            array('startdate','出发日期'),
            array('enddate','预计到达日期'),
            array('reftype','返费模式'),
            array('refpolicy','返费政策'),
            array('agentremark','报备备注'),
            array('status','状态',array(1=>'待确认',2=>'已确认',3=>'已入职',4=>'未通过')),
            array('remark','状态备注'),
            array('createtime','注册时间'),
        );
        export_excel("名单报备", $xlsCell, $xlsData);
    }
    
    // 报备工厂
    public function factoryList()
    {
        return view('report/factorylist');
    }
    
    public function factoryForm()
    {
        $id = input('id/d, 0');
        $factory = ReportFactoryModel::findOrEmpty($id);
        return view('report/factoryform', [
            'factory'		=> $factory
        ]);
    }
    
    public function editFactory()
    {
        $id = input('id/d');
        $vdata = array(
            'id'		=> $id,
            'idnumber'	=> input('idnumber/s'),
            'mobile'    => input('mobile/s')
        );
        try {
            validate(ReportFactoryValidate::class)->check($vdata);
        } catch (ValidateException $e) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> $e->getError()
            )));
        }
        $data = [
            'idnumber'		=> input('idnumber/s'),
            'title'			=> input('title/s'),
            'address'		=> input('address/s'),
            'realname'		=> input('realname/s'),
            'mobile'		=> input('mobile/s'),
            'status'		=> input('status/d')==1 ? 1 : 2,
            'priority'    	=> input('priority/d', 0)
        ];
        if (empty($id)) {
            $data['password'] = empty($password) ? md5("123456789") : md5($password);
            $factory = ReportFactoryModel::create($data);
        } else {
            if (!empty($password)) {
                $data['password'] = md5($password);
            }
            $factory = ReportFactoryModel::find($id);
            $factory->save($data);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function fieldFactory()
    {
        $id = input('id/d', 0);
        $factory = ReportFactoryModel::findOrEmpty($id);
        if ($factory->isEmpty()) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "信息不存在"
            )));
        } else {
            $factory->save([
                input('field/s')  => input('value')
            ]);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
    
    public function delFactory()
    {
        $idarr = input('idarr/a');
        $factory = ReportFactoryModel::whereIn('id', $idarr)->select();
        $result = $factory->delete();
        if ($result) {
            exit(json_encode(array(
                'code' 	=> 0,
                'msg'	=> ""
            )));
        }
        exit(json_encode(array(
            'code' 	=> 1,
            'msg'	=> "删除失败，请稍后重试"
        )));
    }
    
    public function listFactory()
    {
        $limit = input('limit/d', 20);
        $page = input('page/d', 1);
        $map = array();
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] =['title', 'like', '%'.$keywords.'%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = ReportFactoryModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = ReportFactoryModel::where($map)->count();
        if ($count==0) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "未查询到数据"
            )));
        }
        exit(json_encode(array(
            'code' 	=> 0,
            'msg'	=> "",
            'count' => $count,
            'data'  => $list
        )));
    }
}
