<?php
/**
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2021/4/28
 * Time: 3:54 PM
 */

namespace Jindouyun\Controller\Common;

use JinDouYun\Cache\SysAreaChinaCache;

use Jindouyun\Model\Customer\MCustomer;
use Jindouyun\Model\Goods\MQuickGoods;
use Jindouyun\Model\GoodsCategory\MGoodsCategory;
use JinDouYun\Model\Commission\MCommissionBusinessman;

use Jindouyun\Dao\Customer\DCustomer;
use Jindouyun\Dao\Goods\DGoods;
use Mall\Framework\Core\StatusCode;

class XinHongTai
{
    /**
     * 导入客户数据
     */
    public function customer()
    {
        $objSysAreaChinaCache = new SysAreaChinaCache();
        $objDCustomer = new DCustomer('old');
        $objMCustomer = new MCustomer(1, 1);

        // 查询会员表获取客户信息
        $sql = 'select count(*) as total from ims_ewei_shop_member';
        $result = $objDCustomer->query($sql);

        // 查询会员表获取客户信息
        $sql = 'select id,mobile,realname,nickname,isblack,avatar,content,createtime,province,city,area,openid from ims_ewei_shop_member where id < 2 order by id DESC';
        $result = $objDCustomer->query($sql);

        foreach ($result as $key => $value){
            $customerData = [
                'id'     => $value['id'],
                'mobile' => ($value['mobile']) ? : time().substr(microtime(),2,1),
                'name'   => (!empty($value['realname'])) ? $value['realname'] : $value['nickname'],
                'type'   => 3, // 默认散户
                'enableStatus' => ($value['isblack']) ? 4 : 5, // 老系统黑名单 新系统禁用
                'avatar' => $value['avatar'],
                'remark' => $value['content'],
                'createTime' => $value['createtime'],
                'provinceCode' => $objSysAreaChinaCache->getCodeByName($value['province']),
                'cityCode' => $objSysAreaChinaCache->getCodeByName($value['city']),
                'districtCode' => ($value['area']) ? $objSysAreaChinaCache->getCodeByName($value['area']) : 0,

                'contact' => [],
            ];

            // 查询收货地址
            $sql = 'select * from ims_ewei_shop_member_address where deleted = 0 and openid = '.$value['openid'].' order by id DESC limit 1 ';
            $result = $objDCustomer->query($sql);
            if(!empty($result)){
                $customerData['name'] = $result[0]['realname'];
                $customerData['mobile'] = $result[0][''];
                $customerData['provinceCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['province']);
                $customerData['cityCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['city']);
                $customerData['districtCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['area']);
                $customerData['address'] =  $result[0]['address'];

                $customerData['contact']['name'] = $result[0]['realname'];
                $customerData['contact']['mobile'] = $result[0][''];
                $customerData['contact']['provinceCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['province']);
                $customerData['contact']['cityCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['city']);
                $customerData['contact']['districtCode'] = $objSysAreaChinaCache->getCodeByName($result[0]['area']);
                $customerData['contact']['address'] =  $result[0]['address'];
            }

            $result = $objMCustomer->addCustomer($customerData);
            if(!$result->isSuccess()){
                echo $result->getData();
                exit();
            }
            echo $value['id'].'迁移客户数据完成'.PHP_EOL;
            //sleep(1);
        }
    }

    /**
     * 迁移分销关系
     */
    public function commission()
    {
        $objDCustomer = new DCustomer('old');
        $objMCommissionBusinessman = new MCommissionBusinessman(1, 1);

        // 查询会员表获取客户信息
        $sql = 'select id,mobile,realname,nickname,isblack,avatar,content,createtime,province,city,area,openid,agentid from ims_ewei_shop_member where id > 16168 order by id asc';
        $result = $objDCustomer->query($sql);

        $objDCustomer = new DCustomer('default');
        foreach ($result as $key => $value){
            // 没有推荐人不做处理
            if($value['agentid'] == 0){
                continue;
            }

            // 上级客户信息
            $sql = 'select * from qianniao_customer_1 where id = '.$value['agentid'];
            $customerData = $objDCustomer->query($sql);
            if($customerData === false){
                echo $objDCustomer->error().PHP_EOL;
                exit();
            }
            if(empty($customerData)){
                echo $value['agentid'].'获取上级代理信息为空'.PHP_EOL;
                continue;
            }

            echo $value['agentid'].'准备创建分销商'.PHP_EOL;
            // 先把推荐人申请成为分销商
            $businessman = [
                'customerId' => $value['agentid'],
                'gradeId' => 1,
                'grade'   => 0,
            ];
            $result = $objMCommissionBusinessman->addBusinessman($businessman);
            if(!$result->isSuccess()){
                if($result->getData() != '该客户已经是分销商'){
                    echo $result->getData().PHP_EOL;
                    exit();
                }else{
                    echo $result->getData().PHP_EOL;
                }
            }
            echo $value['agentid'].'成为分销商成功'.PHP_EOL;


            // 要绑定客户信息
            $sql = 'select * from qianniao_customer_1 where id = '.$value['id'];
            $customerData = $objDCustomer->query($sql);
            if($customerData === false){
                echo $objDCustomer->error().PHP_EOL;
                exit();
            }
            if(empty($customerData)){
                echo $value['agentid'].'获取绑定客户信息为空'.PHP_EOL;
                continue;
            }

            // 绑定当前用户和分销商的关系
            $data = [
                'businessmanId' => $value['agentid'],
                'source' => 1,
            ];
            $objMCommissionBusinessman = new MCommissionBusinessman(1,  $customerData[0]['userCenterId']);
            $result = $objMCommissionBusinessman->relationshipBusinessman($data);
            if(!$result->isSuccess()){
                echo $result->getData().PHP_EOL;
                exit();
            }
            echo $value['agentid'].' 创建分销商成功,'.$value['id'].' 和分销商绑定关系完成'.PHP_EOL;
        }
    }

    /**
     * 分类
     */
    public function category()
    {
        $objDGoods = new DGoods('old');
        $objMGoodsCategory = new MGoodsCategory(1,1);


        // 查询商品表获取商品信息
        $sql = 'select *  from ims_ewei_shop_category';
        $result = $objDGoods->query($sql);

        foreach ($result as $key => $value){
            $categoryData = [
                'title' => $value['name'],
                'sort'  => $value['displayorder'],
                'images' => 'https://xinhongtai168.com/attachment/'.$value['advimg'],
            ];
            $result = $objMGoodsCategory->addCategory($categoryData);
            if(!$result->isSuccess()){
                echo $result->getData();
                exit();
            }

            echo $value['id'].'迁移商品分类数据完成'.PHP_EOL;
        }
    }

    /**
     * 商品资料
     */
    public function goods()
    {
        $objDGoods = new DGoods('old');
        $objMQuickGoods = new MQuickGoods(1,1);

        // 查询商品表获取商品信息
        $sql = 'select id,title,cates,thumb_url,thumb,marketprice,productprice,content,subtitle,keywords,displayorder,status from ims_ewei_shop_goods where id < 1435  order by id desc ';
        $result = $objDGoods->query($sql);

        foreach ($result as $key => $value){
            // 处理商品分类
            $cates = explode(',', $value['cates']);
            $categoryId = array_shift($cates);
            $assistCategoryId = 0;
            $assistCategoryPath = [];
            if(!empty($cates)){
                $assistCategoryId = implode(',', $cates);
                $assistCategoryPath = $cates;
            }

            // 处理图片
            $thumb_url = ($value['thumb_url']) ? unserialize($value['thumb_url']) : [];
            $thumb = ($value['thumb']) ? [$value['thumb']] : [];
            $image = array_merge($thumb,$thumb_url);
            if(!empty($image)){
                foreach ($image as $k => $v){
                    $image[$k] = 'https://xinhongtai168.com/attachment/'.$v;
                }
            }

            $goodsData = [
                'createUserName' => '老系统迁移',
                'merchantId' => 0,
                'specGroup' => json_encode([]),
                'notArea'  => json_encode(''),
                'link'  => '',
                'barCode' => '',
                'expireTime' => 0,
                'brandId' => 0,
                'title' => $value['title'],
                'categoryId' => ($categoryId) ? $categoryId : 0,
                'categoryPath' => $categoryId,
                'assistCategoryId' => $assistCategoryId,
                'assistCategoryPath' => json_encode($assistCategoryPath),
                'images' => json_encode($image),
                'shopId' => 1,
                'shopName' => '鑫弘泰食品商城',
                'specType' => 1,
                'specMultiple' => [
                    [
                        'barCode' => '',
                        'weight' => '',
                        'isDefault' => 5,
                        'unitId' => 1,
                        'unitName' => '件',
                        'isMaster' => 5,
                        'conversion' => '0.00',
                        'specImage' => '',
                        'specGroup' => [],
                        'salePrice' =>[
                            'conversion' => '0.00',
                            'unitName' => '件',
                            'unitId' => 1,
                            'isMaster' => 5,
                            'deleteStatus' => 4,
                            'enabledLadder' => 0,
                            'salePriceAreaType' => 1,
                            'salePrice' => $value['marketprice'],
                            'ladderPrice' => [],
                            'marketPrice' => $value['productprice'],
                            'setNum' => 1,
                        ],
                        'customerTypePrice' => [],
                        'customerPrice' => []
                    ]
                ],
                'isStore' => false,
                'description' => $value['content'],
                'describe' => $value['subtitle'],
                'tag' => $value['keywords'],
                'sort' => $value['displayorder'],
                'enableStatus' => ($value['status']) ? StatusCode::$standard : StatusCode::$delete,
                'noSalesShop'  => '',
            ];

            $result = $objMQuickGoods->addBasicAndPublishGoods($goodsData);
            if(!$result->isSuccess()){
                echo $result->getData();
                exit();
            }
            echo $value['id'].'商品数据完成'.PHP_EOL;
        }
    }
}