<?php
/**
 * 企业管理Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/04
 * Time: 11:50
 */

namespace JinDouYun\Model\Enterprise;

use Exception;
use Jindouyun\Cache\EnterpriseCache;
use Jindouyun\Cache\RoleAclCache;
use JinDouYun\Dao\Commission\DCommissionSetting;
use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Dao\Merchant\DMerchantApply;
use JinDouYun\Dao\Shop\DShop;
use JinDouYun\Dao\Shop\DShopBindStaff;
use JinDouYun\Dao\Shop\DShopClock;
use JinDouYun\Dao\Shop\DShopKey;
use JinDouYun\Dao\Shop\DShopRostering;
use JinDouYun\Dao\Shop\DShopSubscribe;
use JinDouYun\Model\Commission\MCommissionGrade;
use JinDouYun\Model\Department\MDepartment;
use JinDouYun\Model\Department\MRole;
use JinDouYun\Model\GoodsCategory\MGoodsCategory;
use JinDouYun\Model\GoodsManage\MGoodsBrand;
use JinDouYun\Model\Merchant\MMerchant;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Model\Shop\MShopRostering;
use JinDouYun\Model\Shop\MShopSubscribe;
use JinDouYun\Model\ShopPartner\MShopPartner;
use JinDouYun\Model\Stock\MWarehouse;
use JinDouYun\Model\System\MPaymentSetting;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Enterprise\DEnterprise;
use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
use JinDouYun\Model\SysAreaChina\MSysAreaChina;
use JinDouYun\Model\Department\MStaff;



class MEnterprise
{

    private $objDEnterprise;
    private $objDUserBindEnterprise;
    private $objDUserCenter;
    private $cutTable = 500000;

    public function __construct()
    {
        $this->objDUserCenter = new DUserCenter('default');
        $this->objDEnterprise = new DEnterprise('default');
        $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
    }

    /**
     * 分表
     * @param $id
     * @throws Exception
     */
    public function enterpriseSubTable()
    {
        //企业表不考虑分表
        $this->objDEnterprise->setTable('qianniao_enterprise_1');
//        $tableName = $this->objDEnterprise->getTableName('qianniao_enterprise_', $id, $this->cutTable);
//        $this->objDEnterprise->setTable($tableName);
    }

    /**
     * 生成appid
     * @param $userCenterId
     * @return array
     */
    public function createAppid($userCenterId)
    {
        $returnData = [];

        //1 + 时间戳转日期(1107)4位 + 用户id(2位) + 毫秒时间提取(4位)
        $appid = '1'.date('md').substr(strval($userCenterId+100),-2).substr(microtime(),2, 4);
        $returnData['appid'] = intval($appid);

        $returnData['appSecret'] = md5($returnData['appid'].'qiannaio');

        $returnData['token'] = md5(md5($returnData['appid'].$returnData['appSecret'].'qianniao'));

        return $returnData;
    }

    /**
     * 增
     */

    /**
     * 企业添加
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addEnterprise($params, $authorization)
    {
        //调用分表
        self::enterpriseSubTable();

        #777 查询商铺id 是否存在
        $params['createTime'] = $params['updateTime'];

        $params['expireTime'] = strtotime('+30 day');

        //增加加密字段
        $appidData = $this->createAppid($params['userCenterId']);
        $params = array_merge($params, $appidData);


        $enterpriseId = $this->objDEnterprise->insert($params);
        if($enterpriseId === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }

        //增加用户公司关系表
        $UserBindEnterpriseData = [
            'userCenterId' => $params['userCenterId'],
            'roleType' => StatusCode::$roleType['admin'],
            'enterpriseId' => $enterpriseId,
            'updateTime' => time(),
            'createTime' => time(),
        ];
        $dbResult = $this->objDUserBindEnterprise->insert($UserBindEnterpriseData);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }

        $returnData = [
            'enterpriseId' => $enterpriseId,
            'token' => $appidData['token'],
        ];

        //调用自动创建队列
        $data = [
            'userCenterId' => $params['userCenterId'],
            'enterpriseId' => $enterpriseId,
            'Authorization' => $authorization,
            'PROJECT_DOMAIN' => PROJECT_DOMAIN
        ];
        self::autoCreate($data, 'MEnterprise');

        return ResultWrapper::success( array_merge($params,$returnData) );
    }

    /**
     * 删
     */

    /**
     * 企业删除
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function deleteEnterprise($params)
    {
        //#777 校验公司id数据是否属于该用户id下的公司
        //调用分表
        self::enterpriseSubTable();
        $updateData = [
                'deleteStatus' => StatusCode::$delete,
                'updateTime' => time(),
            ];
        $dbResult = $this->objDEnterprise->update($updateData, ['id' => $params['enterpriseId']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }
        //删除用户企业关联表里的数据
        $dbReturn = $this->objDUserBindEnterprise->delete(['userCenterId' => $params['userCenterId'], 'enterpriseId' => $params['enterpriseId']]);
        if($dbReturn === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 改
     */

    /**
     * 企业修改
     * @param $updateData
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateEnterprise($updateData, $params)
    {
        //#777 校验公司id数据是否属于该用户id下的公司
        //调用分表
        self::enterpriseSubTable();
        unset($updateData['userCenterId']);
        $updateData['updateTime'] = time();
        $dbResult = $this->objDEnterprise->update($updateData, $params);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 用户修改密码
     * @param $params
     * @param $where
     * @return ResultWrapper
     */
    public function updateUserCenterData($params, $where)
    {
        $dbResult = $this->objDUserCenter->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::fail('用户信息为空', ErrorCode::$dberror);
        }
        $userCenterData = $dbResult;
        unset($dbResult);

        if(password_verify($params['oldPassword'], $userCenterData['password']) === false){
            return ResultWrapper::fail('旧密码错误', ErrorCode::$paramError);
        }

        $updateData = [
            'password' => password_hash($params['newPassword'], PASSWORD_DEFAULT ),
            'updateTime' => time(),
        ];
        $dbResult = $this->objDUserCenter->update($updateData, $where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 查出当前登录用户下的企业列表
     * @param $userCenterId
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllEnterprise($userCenterId, $source = 1)
    {
        if(empty($userCenterId)){
            return ResultWrapper::fail('userCenterId参数为空', ErrorCode::$paramError);
        }

        switch ($source){
            case 1://管理员,员工
                $roleType = StatusCode::$roleType['admin'] . "," .StatusCode::$roleType['staff'];
                break;
            case 2://供应商
                $roleType = StatusCode::$roleType['supplier'];
                break;
            case 3://商户
                $roleType = StatusCode::$roleType['merchant'];
                break;
            default:
                return ResultWrapper::fail('获取企业列表source参数错误', ErrorCode::$paramError);
        }
        //企业表不考虑分表
        $this->objDEnterprise->setTable('qianniao_enterprise_1');
        $sql = "select b.userCenterId,b.enterpriseId,b.roleType,b.shopId,e.enterpriseName,e.logo,e.appid,e.token,e.expireTime,e.createTime,e.scope,e.isoem from " . $this->objDUserBindEnterprise->get_Table() . " b left join " . $this->objDEnterprise->get_Table() . " e on b.enterpriseId = e.id where b.userCenterId = ".$userCenterId." and b.roleType in (".$roleType.") and e.deleteStatus = " . StatusCode::$standard . " order by e.expireTime desc";
        $bindData = $this->objDUserBindEnterprise->query($sql);
        if ($bindData === false) {
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        $return = [];
        $objDMerchantApply = new DMerchantApply();
        foreach($bindData as $value){
            $value['merchantData'] = [];
            switch ($value['roleType']){
                case StatusCode::$roleType['admin']:
                    //管理员
                    $value['isInEnterprise'] = StatusCode::$standard;
                    break;
                case StatusCode::$roleType['staff']:
                    //员工
                    if(empty($value['shopId'])){
                        $value['isInEnterprise'] = StatusCode::$standard;
                    }
                    break;
                case StatusCode::$roleType['merchant']:
                    //商户
                    $value['isInEnterprise'] = StatusCode::$delete;
                    //查询商户数据
                    $where =
                        [
                            'userCenterId' => $value['userCenterId'],
                            'enterpriseId' => $value['enterpriseId'],
                            'deleteStatus' => StatusCode::$standard,
                            'auditStatus' => StatusCode::$auditStatus['auditPass'],
                        ];
                    $dbResult = $objDMerchantApply->get($where, 'id,`name`,`desc`,category,contactName,contactMobile,expireTime,enabledStatus');
                    if($dbResult === false){
                        return ResultWrapper::fail($objDMerchantApply->error(), ErrorCode::$dberror);
                    }
                   
                    if($dbResult['enabledStatus'] == StatusCode::$delete){
                        return ResultWrapper::fail('该商户已禁用', ErrorCode::$accountfail);
                    }
                    $value['merchantData'] = $dbResult;
                    unset($dbResult);
                    break;
                default:
                    $value['isInEnterprise'] = StatusCode::$delete;
                    break;
            }
            if(!isset($return[$value['enterpriseId']])){
                $value['roleType'] = [$value['roleType']];
                $return[$value['enterpriseId']] = $value;
            }else{
                $return[$value['enterpriseId']]['roleType'][] = $value['roleType'];
            }
        }
        return ResultWrapper::success(self::format(array_values($return)));
    }

    /**
     * 企业详情
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getEnterpriseInfo($params)
    {
        //调用分表
        self::enterpriseSubTable();

        $dbResult = $this->objDEnterprise->get(['id' => $params['enterpriseId']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }else{
            $objMSysAreaChina = new MSysAreaChina();
            if (isset($dbResult['provinceCode']) && isset($dbResult['cityCode']) && isset($dbResult['districtCode'])) {
                $areaName = $objMSysAreaChina->getNameByCode([
                    $dbResult['provinceCode'],
                    $dbResult['cityCode'],
                    $dbResult['districtCode']
                ]);
                $dbResult['area']['provinceName'] = isset($areaName[$dbResult['provinceCode']]) ? $areaName[$dbResult['provinceCode']] : '';
                $dbResult['area']['cityName'] = isset($areaName[$dbResult['cityCode']]) ? $areaName[$dbResult['cityCode']] : '';
                $dbResult['area']['districtName'] = isset($areaName[$dbResult['districtCode']]) ? $areaName[$dbResult['districtCode']] : '';
                $dbResult['area']['address'] = $dbResult['address'];
            }
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 根据企业id获取企业数据
     * @param $enterpriseId
     * @return ResultWrapper
     * @throws Exception
     */
    public function getEnterpriseDataByEnterpriseId($enterpriseId)
    {
        //调用分表
        self::enterpriseSubTable();
        $dbResult = $this->objDEnterprise->get(['id' => $enterpriseId, 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 根据用户id获取企业信息
     * @param $userId
     * @return array|bool|ResultWrapper
     * @throws Exception
     */
    public function getEnterpriseByUserId($userId)
    {
        //调用分表
        self::enterpriseSubTable();
        $sql = "select e.token,b.roleType from qianniao_user_bind_enterprise b LEFT JOIN ".$this->objDEnterprise->get_Table()." e on b.enterpriseId = e.id where b.userCenterId = ".$userId;
        $bindData = $this->objDUserBindEnterprise->query($sql);
        if($bindData === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($bindData);
    }

    /**
     * 根据企业id获取企业的管理员信息
     * @param $enterpriseId
     * @param array $userCenterId
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAdminsByEnterpriseId($enterpriseId, $userCenterId = [])
    {
        empty($enterpriseId) && ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        $whereSql = '';
        if(!empty($userCenterId) && $userCenterId != false){
            if(is_array($userCenterId)){
                if(count($userCenterId) == 1){
                    $whereSql .= ' AND u.id in('. array_shift($userCenterId).')';
                }else{
                    $whereSql .= ' AND u.id in('.implode(',', $userCenterId).')';
                }
            }else{
                $whereSql .= ' AND u.id in('.$userCenterId.')';
            }
        }
        $sql = 'SELECT b.*,u.mobile AS userMobile FROM qianniao_user_bind_enterprise b LEFT JOIN qianniao_user_center u ON b.userCenterId = u.id  WHERE b.enterpriseId = '.$enterpriseId.' AND b.roleType BETWEEN '.StatusCode::$roleType['admin'].' AND '.StatusCode::$roleType['staff'].' AND u.deleteStatus ='.StatusCode::$standard.$whereSql;
        $dbResult = $this->objDUserBindEnterprise->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }

        $createAdminId = 0;
        foreach($dbResult as &$value){
            if($value['roleType'] == StatusCode::$roleType['admin']){
                if(!$createAdminId){
                    //企业创建者NAME
                    //调用分表
                    $createAdminId = $value['userCenterId'];
                    self::enterpriseSubTable();
                    $enterpriseDbResult = $this->objDEnterprise->get(['id' => $enterpriseId, 'userCenterId' => $createAdminId], 'contact');
                    if($enterpriseDbResult === false){
                        return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
                    }
                    if(empty($enterpriseDbResult)){
                        return ResultWrapper::fail('企业信息查询失败', ErrorCode::$paramError);
                    }
                    $value['name'] = $enterpriseDbResult['contact'];
                }else{
                    return ResultWrapper::fail('角色id错误', ErrorCode::$paramError);//一个企业不可能有多个创建者
                }
            }else{
                $value['name'] = '';
                $userCenterIds[] = $value['userCenterId'];
            }
        }
        unset($value);
        if(empty($userCenterIds)){
            return ResultWrapper::success($dbResult);
        }
        //职工name
        $objMStaff = new MStaff($enterpriseId);
        $modelResult = $objMStaff->getStaffByUserCenterIds($userCenterIds);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $staffData = $modelResult->getData();
        $newStaffData = [];
        if(!empty($staffData)){
            foreach ($staffData as $key => $value){
                $newStaffData[$value['userCenterId']] = $value;
            }
        }

        foreach($dbResult as $key => $value){
           if(isset($newStaffData[$value['userCenterId']])){
               $dbResult[$key]['name'] = $newStaffData[$value['userCenterId']]['staffName'];
           }else if($value['roleType'] == StatusCode::$roleType['staff']){
               unset($dbResult[$key]);
           }
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 格式化企业列表数据 过期状态
     * @param $data
     * @return mixed
     */
    public function format($data)
    {
        $objEnterpriseCache = new EnterpriseCache();
        foreach($data as &$v){
            $v['expireStatus'] = true;
            if($v['expireTime'] > time()){
                $v['expireStatus'] = false;
            }
            //映射redis缓存里的企业生产日期设置
            $cacheResult = $objEnterpriseCache->getEnterpriseData($v['enterpriseId'], 'shelfLifeSetUp');
            $v['shelfLifeSetUp'] = $cacheResult ? $cacheResult : StatusCode::$delete;
        }
        return $data;
    }

    /**
     * 根据用户token获取用户信息(无用)
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getStaffByToken($params)
    {
        //调用分表
        self::enterpriseSubTable();
        //1.查询是否有角色绑定
        $where = [
            'enterpriseId' => $params['enterpriseId'],
//            'shopId' => $params['shopId'],
            'userCenterId' => $params['userCenterId'],
        ];

        $dbResult = $this->objDUserBindEnterprise->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        $bind = $dbResult;
        unset($dbResult);
        $returnData = [
            'staffId' => '',
            'name' => '',
            'userCenterId' => $params['userCenterId']
        ];
        if(empty($bind)){
            return ResultWrapper::success($returnData);
        }
        if($bind['roleType'] == StatusCode::$roleType['merchant']){
            //商户
            $objMMerchant = new MMerchant($params['enterpriseId'], false);
            $modelResult = $objMMerchant->getMerchantData(['id' => $bind['merchantId']]);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $merchant = $modelResult->getData();
            unset($modelResult);
            $returnData['name'] = $merchant['contactName'];
        }else{
            //员工
            $objMStaff = new MStaff($params['enterpriseId']);
            $modelResult = $objMStaff->getStaffData(['userCenterId' => $params['userCenterId'], 'deleteStatus' => StatusCode::$standard]);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $staff = $modelResult->getData();
            unset($modelResult);
            if(empty($staff)){
                return ResultWrapper::success($returnData);
            }
            $returnData['staffId'] = $staff['id'];
            $returnData['name'] = $staff['staffName'];
        }
        return ResultWrapper::success($returnData);
    }

    /**
     * 判断用户id是否是某企业下的
     * @param $userCenterId
     * @param $enterpriseId
     * @param bool $roleType
     * @return ResultWrapper
     */
    public function isUserCenterBindEnterprise($userCenterId, $enterpriseId, $roleType = false)
    {
        $where = [
            'userCenterId' => $userCenterId,
            'enterpriseId' => $enterpriseId,
        ];
        $roleType && $where['roleType'] = $roleType;
        $dbResult = $this->objDUserBindEnterprise->select($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::fail('账号不存在', ErrorCode::$paramError);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 自动创建
     * @param $data
     * @param $className
     */
    protected static function autoCreate($data, $className)
    {
        $i = 1;
        do {
            $postData = [
                'topicName'         => 'MyJob',
                'topicClass'        => "Jobs\Model\MTopic\Enterprise\\".$className,
                'topicMethon'       => 'autoCreate',
                'topicMethonParams' => [
                    'data' => $data
                ],
            ];
            $url = QIANNIAO_QUEUE . '/CAddJob/add';
            $result = request($url, $postData);
            $i++;
        } while ($result['httpcode'] != 200 && $i <= 3);
    }

    /**
     * 创建企业自动创建数据
     * @param $userCenterId
     * @param $enterpriseId
     * @return ResultWrapper
     * @throws Exception
     */
    public function autoCreateData($userCenterId, $enterpriseId)
    {
        self::enterpriseSubTable();

        //查询企业数据
        $dbResult = $this->objDEnterprise->get(['id'=> $enterpriseId]);

        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }
        $enterpriseData = $dbResult;
        unset($dbResult);

        //新建合伙人
//        $objMShopPartner = new MShopPartner($enterpriseId, $userCenterId);
//        $insertShopPartnerData = [
//            "logo"         => $enterpriseData['logo'],
//            "name"         => $enterpriseData['enterpriseName'],//合伙名称
//            "model"        => 1,
//            "provinceCode" => $enterpriseData['provinceCode'],//省编码
//            "cityCode"     => $enterpriseData['cityCode'],//市编码
//            "districtCode" => $enterpriseData['districtCode'],//区编码
//            "address"      => $enterpriseData['address'], //详细地址
//            "userCenterId" => $userCenterId,//负责人id
//            "userName"     => $enterpriseData['contact'],//负责人名称
//            "mobile"       => $enterpriseData['mobile'], //负责人电话
//            "enterpriseId" => $enterpriseId,
//            'updateTime'   => time(),
//            'createTime'   => time(),
//        ];
//        $modelResult = $objMShopPartner->addShopPartner($insertShopPartnerData);
//        if(!$modelResult->isSuccess()){
//            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
//        }
//        $shopPartnerId = $modelResult->getData();
//        unset($modelResult);


        //新建仓库
        $objMWarehouse = new MWarehouse($enterpriseId);
        $insertWarehouseData = [
            "warehouseName" => '默认仓库',
            "contactName" => $enterpriseData['contact'],
            "contactMobile" => $enterpriseData['mobile'],
            "provinceCode" => $enterpriseData['provinceCode'],
            "cityCode" => $enterpriseData['cityCode'],
            "districtCode" => $enterpriseData['districtCode'],
            "contactAddress" =>  $enterpriseData['address'],
            "costType" => 1,
            "deleteStatus" => StatusCode::$standard,
            "enableStatus" => StatusCode::$standard,
            'updateTime' => time(),
            'createTime' => time(),
        ];
        $modelResult = $objMWarehouse->addWarehouse($insertWarehouseData);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $warehouseId = $modelResult->getData();
        unset($modelResult);
        //新建商铺
        $objMShop = new MShop($enterpriseId, $userCenterId);

        $insertShopData = [
            'logo'           => $enterpriseData['logo'],//logo
            'shopType'       => 1,//商铺类型
            'isMaster'       => 5,//自动创建
            'costType'       => 1,//成本计算方式 1移动加权 2个别计价
            'name'           => '默认门店',//名称
            'warehouseId'    => $warehouseId,
            'openTime'       => '{"end": "", "start": "", "isAllDay": 1}',//营业时间
            'contactName'    => $enterpriseData['contact'],//联系人
            'mobile'         => $enterpriseData['mobile'],//联系电话
//            'shopPartnerId'  => $shopPartnerId,//合伙人Id
            "provinceCode"   => $enterpriseData['provinceCode'],//省编码
            "cityCode"       => $enterpriseData['cityCode'],//市编码
            "districtCode"   => $enterpriseData['districtCode'],//区编码6
            "address"        => $enterpriseData['address'], //详细地址
            'salesArea'      => '["0-0-0"]',
            'deleteStatus'   => StatusCode::$standard,
            'enableStatus'   => StatusCode::$standard,
            'createTime'     => time(),
            'updateTime'     => time(),
        ];
        $modelResult = $objMShop->addShop($insertShopData);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $shopId = $modelResult->getData();
        unset($modelResult);
        //新建分类
        $objMGoodsCategory = new MGoodsCategory($userCenterId, $enterpriseId);
        $insertGoodsCategory = [
            'sort'       => 0,//排序
            'title'      => '默认分类',//分类名称
            'adImage'    => $enterpriseData['logo'],//广告图片
            'images'     => $enterpriseData['logo'],//图片
            'link'       => '',//分类链路
            'pid'        => 0,
            'enableStatus' => StatusCode::$standard
        ];
        $modelResult = $objMGoodsCategory->addCategory($insertGoodsCategory);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(),$modelResult->getErrorCode());
        }
        $goodsCategoryId = $modelResult->getData();
        unset($modelResult);

        //新建品牌
        $objMGoodsBrand = new MGoodsBrand($userCenterId,$enterpriseId);
        $insertGoodsBrand = [
            'title'         => '默认品牌',//名称
            'images'        => $enterpriseData['logo'],//图片
            'enableStatus'  =>  StatusCode::$standard,
            'createTime'    => time(),
            'updateTime'    => time(),
        ];
        $modelResult = $objMGoodsBrand->addBrand($insertGoodsBrand);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(),$modelResult->getErrorCode());
        }
        $goodsBrandId = $modelResult->getData();
        unset($modelResult);

        //新建部门
        $objMDepartment = new MDepartment($enterpriseId);

        $insertDepartment = [
            "departmentName" => '总裁办',
            "pid" => 0,
            "order" => 0,
            "desc" => '',
            "extend" => [],
            "updateTime" => time(),
        ];
        $insertDepartment['extend']['departmentPidPath'] = '';
        $insertDepartment['extend'] = json_encode($insertDepartment['extend']);

        $modelResult = $objMDepartment->addDepartment($insertDepartment);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $departmentId = $modelResult->getData();
        unset($modelResult);

        //新建岗位
        $objMRole = new MRole($enterpriseId);
        $insertRole = [
            "roleName" => '总裁',
            "isAdministrator" => 5,
            "pid" => 0,
            "updateTime" => time(),
            "acl" => null,
        ];

        $insertRole['acl'] = !empty($insertRole['acl']) ? json_encode($insertRole['acl']) : NULL;

        $modelResult = $objMRole->addRole($insertRole);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $roleId = $modelResult->getData();
        unset($modelResult);

        //添加职工
        $insertStaff = [
            "userCenterId" => $userCenterId, // int(10) DEFAULT NULL COMMENT '用户中心id',
            "departmentId" => $departmentId, //int(10) DEFAULT NULL COMMENT '部门id',
            "staffName" => $enterpriseData['contact'], //varchar(30) DEFAULT NULL COMMENT '员工姓名',
            "roleId" => $roleId, //int(10) DEFAULT NULL COMMENT '角色id',
            "mobile" => $enterpriseData['mobile'], //varchar(11) DEFAULT NULL COMMENT '手机号',
            "deleteStatus" => StatusCode::$standard, //tinyint(3) NOT NULL DEFAULT '5' COMMENT '删除状态 4:删除 5:正常',
            "createTime" => time(), //int(10) DEFAULT NULL COMMENT '创建时间',
            "updateTime" => time(), //int(10) DEFAULT NULL COMMENT '修改时间',
            "extend" => '{"rolePidPath": "1", "departmentPidPath": "1"}',
            "dataField" => '{"shopIds": [], "staffIds": [], "dataField": 3, "shopNames": [], "staffNames": []}', //json DEFAULT NULL COMMENT '数据域',
        ];
        $objDStaff = new DStaff();
        $objDStaff->setTable($objDStaff->get_Table().'_'.$enterpriseId);
        $dbResult = $objDStaff->insert($insertStaff);
        if($dbResult === false){
            return ResultWrapper::fail($objDStaff->error, ErrorCode::$dberror);
        }
        $staffId = $dbResult;
        unset($dbResult);
        // 添加排班表
        $objMShopRostering = new DShopRostering();
        $objMShopRostering->setTable($objMShopRostering->get_Table().'_'.$enterpriseId);
        //添加预约表
        $objMShopSubscribe = new DShopSubscribe();
        $objMShopSubscribe->setTable($objMShopSubscribe->get_Table().'_'.$enterpriseId);

        //添加打卡记录表
//        $objDShopClock = new DShopClock();
//        $objDShopClock->setTable($objDShopClock->get_Table().'_'.$enterpriseId);

        //添加默认支付方式
        $objMPaymentSetting = new MPaymentSetting($userCenterId, $enterpriseId);
        $updateEnable['id'] = 3;
        $updateEnable['enableStatus'] = StatusCode::$standard;
        $modelResult = $objMPaymentSetting->updateEnableStatus($updateEnable);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        unset($modelResult);

        $objDCommissionSetting = new DCommissionSetting();
        $objDCommissionSetting->setTable('qianniao_commission_setting');
        //自动新增分销
        $commissionSettingDate = [
            'enterpriseId'=>$enterpriseId,
            'self'=>StatusCode::$delete
        ];
        $insert = $objDCommissionSetting->insert($commissionSettingDate);
        if($insert === false){
            return ResultWrapper::fail($objDCommissionSetting->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success('自动创建成功');

    }
    /**
     * 通过企业toke获取企业id
     * @param string $token 企业token
     * @return ResultWrapper
     */
    public function getEnterpriseIdByToken($token)
    {
        $this->objDEnterprise->setTable('qianniao_enterprise_1');
        $dbResult =  $this->objDEnterprise->get_field('id', ['token'=>$token]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success(0);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 列表
     * @param $where
     * @return mixed
     */
    public function list($where)
    {
        $where['deleteStatus'] = 5;
        $where['iosAuditStatus'] = 5;
        $this->objDEnterprise->setTable('qianniao_enterprise_1');
        $dbResult = $this->objDEnterprise->select($where, '*', 'id DESC');
        $count = $this->objDEnterprise->count($where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }

        $return = [
            'data' => $dbResult,
            'total' => $count,
        ];

        if($return === false){
            return ResultWrapper::fail($this->objDEnterprise->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($return);
        }
    }

}