<?php
namespace model\sample;
use \model\pro\factory;
use \model\collocation;
use \model\pro\cate;
class expect extends \model
{
    public $table = 'sample_expect';
    public $key = 'sample_expect_id';
    public $order = 'sample_expect_id';
    public $factory = null;
    public $collocation = null;
    public $cate = null;
    public $findCaches = []; //查询临时缓存
    public $cacheCateRows = []; //

	public function __construct()
    {
		parent::__construct();
        $this->factory = new factory();
        $this->collocation = new collocation();
        $this->cate = new cate();
	}

	function list($rules, $where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby=''){
        $cellEdit = 0;
        $fields = '*';
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data){
            switch ($field) {
                case 'parent_id':
                    $field = 'id';
                    $op = 'eq';
                    $data = $this->cate->likeAndChilds($data);
                    if (empty($data)) $data = [0];
                    break;                
            }
        });
		$where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
        $where['RAW #1'] = raw('`right` - `left` = 1');
        if ($rules['year'] == $rules['yearEnd'] && $rules['month'] == $rules['monthEnd']) {
                //只选择一个月 则 外连接
                $join['[>]sample_expect(exp)'] = [
                    'cate.id' => 'sample_expect_cate',
                    '#1' => '@sample_expect_year =' . $rules['year'],
                    '#2' =>'@sample_expect_month = ' . $rules['month'],
                ];
        } else {
            $join['[<]sample_expect(exp)'] = ['cate.id' => 'sample_expect_cate'];
            $where['RAW1'] = raw('(sample_expect_year > ' . $rules['year'] . ' OR (sample_expect_year = ' . $rules['year'] . ' AND sample_expect_month > ' . $rules['month'] . ' ))');
            $where['RAW2'] = raw('(sample_expect_year < ' . $rules['yearEnd'] . ' OR (sample_expect_year = ' . $rules['yearEnd'] . ' AND sample_expect_month < ' . $rules['monthEnd'] . ' ))');
            $fields = [
                'id',
                'parent_id',
                'cn_name',
                'en_name',
                '@SUM(sample_expect_want_qty) sample_expect_want_qty',
                '@SUM(sample_expect_finish_qty) sample_expect_finish_qty',
                'sample_expect_opuser',
            ];
            $where['GROUP'] = 'id';
        }
        if ($rules['p_cate']) {
            $where['cate.id'] = explode(',', $rules['p_cate']);
        }
        if ($page > 0 && $pagesize > 0) {
            $pages = $this->paging('pro_cate(cate)', $join, '*', $where, $page, $pagesize);
            $where["LIMIT"] = [$pages['limit'], $pagesize];
        }
		$rows = $this->db->select('pro_cate(cate)', $join,$fields,$where);
        //dd($this->db->last());
        if(!empty($rows)) foreach($rows as $k=>&$row){
            if (empty($this->cacheCateRows[$row['parent_id']])) {
                $bigCateRow = $this->cate->getRowByKey($row['parent_id']);
                $this->cacheCateRows[$row['parent_id']] = $bigCateRow;
            } else {
                $bigCateRow = $this->cacheCateRows[$row['parent_id']];
            }
            $row['captions']['parent_id'] = $bigCateRow[cateName()];
            $row['cate_id'] = $row['id'];

            $row['sample_expect_yearMonth'] = $rules['year'] . '/' . $rules['month'];
            $row['sample_expect_yearMonthEnd'] = $rules['yearEnd'] . '/' . $rules['monthEnd'];
            if ($row['sample_expect_finish_qty'] && $row['sample_expect_want_qty'])  {
                $row['sample_expect_finish_rate'] = (round(($row['sample_expect_finish_qty']*1) / ($row['sample_expect_want_qty']*1), 4) * 100);
                $row['sample_expect_finish_rate'] .= '%';
            }

        }
        //是否已冻结
        if ($rules['month']) {
            $checkoutRow = $this->db->get('sample_expect_checkout', '*', ['ORDER' => ['sample_expect_checkout_id' => 'DESC'], 'LIMIT' => 1]);
            if ($checkoutRow) {
                $dateTime1 = \DateTime::createFromFormat('Y-m', $rules['year'] . '-' . $rules['month']);
                $dateTime2 = \DateTime::createFromFormat('Y-m', $checkoutRow['sample_expect_checkout_year'] . '-' . $checkoutRow['sample_expect_checkout_month']);  
                 
                if ($dateTime1 > $dateTime2) {
                    $cellEdit = 1; // 允许编辑
                }
            }
        }
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $rows,
            'userdata' => ['cellEdit' => $cellEdit]
		];
		return $data;
    }

    function setQtyValue($expect_id, $cate, $wantQty, $year, $month){
        if (!empty($expect_id)) {
            $this->db->update('sample_expect', [
                'sample_expect_want_qty' => $wantQty,
                'sample_expect_opuser' => getOpuser()
            ], ['sample_expect_id' => $expect_id]);
        } else {
            $this->db->insert('sample_expect', [
                'sample_expect_year' => $year,
                'sample_expect_month' => ltrim($month, '0'),
                'sample_expect_cate' => $cate,
                'sample_expect_want_qty' => $wantQty,
                'sample_expect_opuser' => getOpuser()
            ]);
        }
    }

}
