<?php
/**
 * 计量单位
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2020/3/17
 * Time: 17:06
 */

namespace JinDouYun\Model\GoodsManage;


use JinDouYun\Controller\Common\Logger;
use JinDouYun\Dao\GoodsManage\DUnits;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MUnits
{
    private $onlineUserId;

    private $onlineEnterpriseId;

    private $objDUnits;

    /**
     * MUnits constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;

        $this->objDUnits = new DUnits('default');
        $this->objDUnits->setTable( 'qianniao_units_' . $onlineEnterpriseId);

        self::before();
    }


    /**
     * 添加计量单位
     *
     * @param $params
     * @return ResultWrapper
     */
    public function add($params)
    {
        $dbResult = $this->objDUnits->get_field('id', ['deleteStatus' => StatusCode::$standard, 'unitName' => $params['unitName']]);
        if ($dbResult === false) return ResultWrapper::fail($this->objDUnits->error(), ErrorCode::$dberror);
        if (!empty($dbResult)) return ResultWrapper::fail($params['unitName'] . '计量单位已存在', ErrorCode::$paramError);
        unset($dbResult);
        $dbResult = $this->objDUnits->insert($params);
        if ($dbResult === false) return ResultWrapper::fail($this->objDUnits->error(), ErrorCode::$dberror);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 删除计量单位
     *
     * @param $id
     * @return ResultWrapper
     */
    public function del($id)
    {
        $dbResult = $this->objDUnits->update(['deleteStatus'=>StatusCode::$delete],$id);
        if ($dbResult===false) return ResultWrapper::fail($this->objDUnits->error(),ErrorCode::$dberror);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 跟新启用/禁用状态
     *
     * @param $params
     * @return ResultWrapper
     */
    public function updateEnableStatus($params)
    {
        $dbResult = $this->objDUnits->update(['enableStatus' => $params['enableStatus']], $params['id']);
        if ($dbResult===false) return ResultWrapper::fail($this->objDUnits->error(),ErrorCode::$dberror);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 编辑计量单位
     *
     * @param $params
     * @return ResultWrapper
     */
    public function edit($params)
    {
        $dbResult = $this->objDUnits->get_field('id', ['deleteStatus' => StatusCode::$standard, 'unitName' => $params['unitName']]);
        if ($dbResult === false) return ResultWrapper::fail($this->objDUnits->error(), ErrorCode::$dberror);
        if (!empty($dbResult)) return ResultWrapper::fail($params['unitName'] . '计量单位已存在', ErrorCode::$paramError);
        unset($dbResult);
        $id = $params['id'];
        unset($params['id']);
        $dbResult = $this->objDUnits->update($params,$id);
        if ($dbResult === false) return ResultWrapper::fail($this->objDUnits->error(),ErrorCode::$dberror);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取单位列表
     *
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAll($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $selectParams['deleteStatus'] = StatusCode::$standard;
        if ($selectParams['enableStatus']==StatusCode::$delete){
            $selectParams['enableStatus']=StatusCode::$standard;
        }else{
            unset($selectParams['enableStatus']);
        }
        $dbResult = $this->objDUnits->select($selectParams, '*', 'createTime DESC', $limit, $offset);
        if ($dbResult === false) return ResultWrapper::fail($this->objDUnits->error(), ErrorCode::$dberror);
        $total = $this->objDUnits->count($selectParams);
        $return = [
            'data'  => $dbResult,
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * @return bool
     */
    private function before()
    {
        $sql = "SELECT a.title FROM qianniao_admin_setting as a
                LEFT JOIN qianniao_units_".$this->onlineEnterpriseId." as u 
                ON a.title = u.unitName 
                WHERE a.type= ". StatusCode::$adminSettingType['unit']." AND u.unitName IS NULL";
        $dbResult = $this->objDUnits->query($sql);
        if ($dbResult === false){
            Logger::logs(E_USER_ERROR,'查询单位失败',__CLASS__,__LINE__,$this->objDUnits->error());
            return false;
        }

        if (empty($dbResult)){
            return true;
        }

        $insert = [];
        foreach ($dbResult as $value){
            $insert[] = [
                'unitName' => $value['title'],
                'createTime' => time()
            ];
        }
        //写入数据
        $dbResult = $this->objDUnits->insert($insert,true);
        if ($dbResult === false){
            Logger::logs(E_USER_ERROR,'初始化单位失败',__CLASS__,__LINE__,$this->objDUnits->error());
            return false;
        }
        return true;
    }

}