<?php

namespace app\admin\controller;
use think\App;
use think\Db;

class FCleanTask extends Auth {
    public function __construct(App $app = null) {
        parent::__construct($app);
        $this->model = new \app\common\model\FCleanTask();
        $this->table = $this->model->table;
    }
    public function index() {
        if (request()->isAjax()) {
            //分页参数
            $length = input('rows', 10, 'intval');   //每页条数
            $page = input('page', 1, 'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx', 'id', 'trim');      //排序列
            $sort = input('sord', 'desc', 'trim');        //排序方式
            $order = $sortRow . ' ' . $sort;
            $title = input('title', '', 'trim');
            if ($title) {
                $map[] = ['title', 'like', '%' . $title . '%'];
            }
            $enable = input('enable', '', 'trim');
            if ($enable != '') {
                $map[] = ['enable', '=', $enable];
            }
            $status = input('status', '', 'trim');
            if ($status != '') {
                $map[] = ['status', '=', $status];
            }
            $map[] = ['del', '=', 0];
            $map[] = ['org_id', '=', $this->orgId];
            $map = empty($map) ? true : $map;
            //数据查询
            $lists = db($this->table)->where($map)->limit($start, $length)->order($order)->select();
            foreach ($lists as $k => $v) {
                $userlist = Db::name('f_clean_task_user')
                    ->alias('f_clean_task_user')
                    ->join('user user', 'user.id = clean_task_user.user_id')
                    ->field('user.id,user.real_name')
                    ->where('clean_task_user.task_id', $v['id'])
                    ->select();
                $users = array();
                foreach ($userlist as $kk => $vv) {
                    $users[] = $vv['real_name'];
                }
                $lists[$k]['user'] = implode(',', $users);
            }
            //数据返回
            $totalCount = db($this->table)->where($map)->count();
            $totalPage = ceil($totalCount / $length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }
        else {
            $this->assign('m_name', '计划管理');
            return $this->fetch();
        }
    }
    /**
     * 新增/编辑
     */
    public function add($id = 0) {
        if (request()->isPost()) {
            $res = $this->model->updates();
            if ($res) {
                $this->success('操作成功', url('index'));
            }
            else {
                $this->error($this->model->getError());
            }
        }
        else {
            if ($id) {
                $info = db($this->table)->where('id', $id)->find();
                $info['type'] = db('f_clean_task_form')
                    ->where('task_id', $id)
                    ->column('form_id');
                $info['user'] = db('f_clean_task_user')
                    ->where('task_id', $id)
                    ->column('user_id');
                $this->assign('info', $info);
            }
            $this->assign('user', (new \app\common\model\User())->getCleanWorker());
            $this->assign('type', (new \app\common\model\FCleanType())->getGroupList());
            return $this->fetch();
        }
    }
    /**
     * 删除记录
     * @param int $id
     */
    public function del($id = 0) {
        if (!$id) {
            $this->error('参数错误');
        }
        $res = db($this->table)->where('id', $id)->update([
            'del'=>1,
            'del_user_id'=>is_login(),
            'del_datetime'=>getTime(),
        ]);
        if ($res) {
            $this->success('删除成功');
        }
        else {
            $this->error('删除失败');
        }
    }
    /**
     * 改变字段值
     * @param int $fv
     * @param string $fn
     * @param int $fv
     */
    public function changeField($id = 0, $fn = '', $fv = 0) {
        if (!$fn || !$id) {
            $this->error('参数错误');
        }
        $res = db($this->table)->where('id', $id)->setField($fn, $fv);
        if ($res) {
            $this->success('操作成功');
        }
        else {
            $this->error('操作失败');
        }
    }

    public function details($id = 0){

        $info = Db::name('f_clean_task')->where('id',$id)->find();
        if(!$info){
            $this->error('参数错误');
        }
        $info['check_user_name'] =  Db::name('user')->where('id',$info['check_user'])->value('real_name');

        $taskUser = Db::name('f_clean_task_user')
            ->alias('ctu')
            ->join('user u','u.id=ctu.user_id')
            ->where('ctu.task_id',$info['id'])
            ->column('u.real_name');

        $info['task_user'] = $taskUser?implode(',',$taskUser):'';

        $taskFormId = Db::name('f_clean_task_form')->where('task_id',$id)->column('form_id');

        $addr = Db::name('f_clean_type')
            ->alias('ct')
            ->field('cf.id,ct.title')
            ->join('f_clean_form cf','cf.type_id=ct.id')
            ->whereIn('cf.id',$taskFormId)
            ->select();


        foreach ($addr as $k=>$v){
            $record = Db::name('f_clean_record')
                ->alias('cr')
                ->field('cr.*,u.real_name')
                ->join('user u','u.id=cr.user_id')
                ->where('cr.task_id',$id)
                ->where('cr.form_id',$v['id'])
                ->find();
            if($record){
                $record['check_json'] = [];
                if($record['check_json']){
                    $cjson = json_decode($record['check_json'],true);
                    foreach ($cjson as $kk=>$vv){
                        $address = Db::name('address')->where('id',$vv)->value('title');
                        $cjson = [
                            'addr'=>$address,
                            'status'=>$vv['status']
                        ];
                    }
                    $record['check_json'] = $cjson;
                }


            }
            $addr[$k]['record'] = $record;
        }
        $info['formList'] = $addr;

        $this->assign('info',$info);
        return $this->fetch();
    }


    public function subDetail(){
        $id = input('id');
        $info = Db::name('f_clean_record')->where('id',$id)->find();
        $info['user_name'] = Db::name('user')->where('id',$info['user_id'])->value('real_name');
        $info['task_title'] = Db::name('f_clean_task')->where('id',$info['task_id'])->value('title');
        if($info['check_json']){
            $cjson = json_decode($info['check_json'],true);
            $tarr = [];
            foreach ($cjson as $kk=>$vv){
                $address = Db::name('address')->where('id',$vv['id'])->value('title');
                $tarr[] = [
                    'addr'=>$address,
                    'status'=>$vv['status']
                ];
            }
            $info['check_json'] = $tarr;
        }
        $info['items'] = Db::name('f_clean_record_items')
            ->alias('cri')
            ->field('mg.title,cri.*')
            ->join('mate_goods mg','mg.id=cri.items_id')
            ->where('cri.record_id',$info['id'])
            ->select();

        $this->assign('info',$info);
        return $this->fetch();
    }
}