<?php

namespace common\helpers\bonus\Calc;

use common\helpers\Date;
use common\models\CalcRecord;
use common\models\PerfMonth;
use common\models\PerfPeriod;
use common\models\PerfStandard;

/**
 * 从计算服务拉取生成的业绩单
 */
class PullPerfDataFromCalc extends BasePerfBusiness
{

    public function __construct($periodNum)
    {
        parent::__construct($periodNum);
    }

    public function start(): array
    {
        try {
            //验证状态值
            if ($this->verify()) {
                //清空业绩单相关数据
                $this->clearPerfPeriod();
                if ($this->_isCalcMonth) {
                    //拉取月业绩
                    $this->pullPerfMonth();
                }
                //拉取期业绩数据
                $this->pullPerfPeriod();
                //同步周期表的值到业务系统
                self::pullPeriodForUpdate($this->_periodNum);

                return $this->success();
            } else {
                return $this->fail('业绩单还未生成');
            }
        } catch (\Exception $e) {
            return $this->fail('msg:' . $e->getMessage() . 'line:' . $e->getLine());
        }
    }

    public function verify(): bool
    {
        $db   = $this->_calc_db_name;
        $data = \Yii::$app->$db->createCommand("SELECT IS_PREPARE,IS_PERFED FROM AR_PERIOD where PERIOD_NUM = $this->_periodNum")->queryOne();;

        if (
//            2 == $data['IS_PREPARE'] //计算业绩阶段
//            &&
            1 == $data['IS_PERFED']  //1表示累计业绩已完成
            || 3 == $data['IS_PERFED']
        ) {
            return true;
        }
        return false;
    }

    public function clearPerfPeriod()
    {
        // 周业绩
        PerfPeriod::pageDeleteAll('PERIOD_NUM=' . $this->_periodNum);
        CalcRecord::record($this->_periodNum, "【期业绩】业务系统，AR_PERF_PERIOD表，已清除当期所有记录");
        // 业绩单
//        PerfOrder::pageDeleteAll('PERIOD_NUM=' . $this->_periodNum);
        // 删除活跃用户
        // PerfActiveUser::pageDeleteAll('PERIOD_NUM='.$this->_periodNum.'  AND IS_SENT=0 ');
        // 月结时要清空的数据
        if ($this->_isCalcMonth) {
            // 月业绩表
            PerfMonth::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
            CalcRecord::record($this->_periodNum, "【期业绩】业务系统，是月结点，AR_PERF_MONTH表，已清除当月所有记录");
            //达标业绩表
//            PerfStandard::pageDeleteAll("CALC_MONTH='{$this->_calcYearMonth}'");
        }
    }

    public function pullPerfMonth(): bool
    {
        $db      = $this->_calc_db_name;
        $_offset = 0;
        $countPerfMonth = 0;

        //        $pCalcMonth = date('Y-m-d', strtotime($formatOrderData['CREATED_AT']));
        $pCalcMonth = Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);

        periodMonth:
        $offset = $_offset * $this->_limit;
        //u.EMP_LV as LAST_EMP_LV,
        $data   = \Yii::$app->$db->createCommand("SELECT p.*,'$pCalcMonth' as P_CALC_MONTH ,u.DEC_LV as LAST_DEC_LV,
        ifnull(u.STATUS,0) as LAST_STATUS FROM AR_PERF_MONTH as p LEFT JOIN AR_USER AS u ON p.user_id = u.id
        where p.CALC_MONTH = $this->_calcYearMonth limit $this->_limit offset $offset;")->queryAll();

        if (!empty($data)) {
            $fieldArray = array_keys($data[0]);
            $_offset    += 1;
            $countPerfMonth += count($data);
            \Yii::$app->db->createCommand()->batchInsert('AR_PERF_MONTH', $fieldArray, $data)->execute();
            $data = null;
            goto periodMonth;
        }
        CalcRecord::record($this->_periodNum,"【生成业绩单】业务系统，AR_PERF_MONTH表，插入".$countPerfMonth."条记录");
        $data = null;

        return true;
    }

    public function pullPerfPeriod(): bool
    {
        $db      = $this->_calc_db_name;
        $_offset = 0;
        $countPerfPeriod = 0;

        //        $pCalcMonth = date('Y-m-d', strtotime($formatOrderData['CREATED_AT']));
        $pCalcMonth = Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);

        period:
        $offset = $_offset * $this->_limit;
        //u.EMP_LV as LAST_EMP_LV,
        $data   = \Yii::$app->$db->createCommand("SELECT p.*,'$pCalcMonth' as P_CALC_MONTH ,u.DEC_LV as LAST_DEC_LV,
        ifnull(u.STATUS,0) as LAST_STATUS FROM AR_PERF_PERIOD as p LEFT JOIN AR_USER AS u ON p.user_id = u.id 
        where p.PERIOD_NUM = $this->_periodNum limit $this->_limit offset $offset;")->queryAll();

        if (!empty($data)) {
            $fieldArray = array_keys($data[0]);
            $_offset    += 1;
            $countPerfPeriod += count($data);
            \Yii::$app->db->createCommand()->batchInsert('AR_PERF_PERIOD', $fieldArray, $data)->execute();
            $data = null;
            goto period;
        }
        CalcRecord::record($this->_periodNum,"【生成业绩单】业务系统，AR_PERF_PERIOD表，插入".$countPerfPeriod."条记录");
        $data = null;

        return true;
    }


}
