<?php

class YpwCompanyInfo extends YpwBase
{
    /**
     * @param  string $keyword 搜索的关键字 公司名或者统一社会信用代码
     * @param  int    $forceUpdate 0:取数据库数据 1:从页面爬取
     * @method 获取企业信息
     * @author zhengweihua 
     * @copyright 2022-07-19
     */
    public function getCompanyInfo($keyword, $forceUpdate = 0)
    {

        if (empty($keyword)) return LibFc::ReturnData(true, []);

        $day = 1;

        $field = ['com_id,com_name,com_code,com_faren,com_status,com_status_remark,com_tel,com_addr,com_build,com_bdate,com_edate,com_jyfw,com_etime'];
        $where = sprintf(" and (com_name = '%s' or com_code = '%s')", LibFc::Escape($keyword), LibFc::Escape($keyword));
        $infoRes =  $this->Get('yp_compnay_info', $field, $where, true);

        if (empty($infoRes['data']) || $forceUpdate) {
            //爬爱企查、天眼查
            $htmlRes = $this->crawlHtml($keyword);
            $company = $htmlRes['data'];

            if (!empty($company['com_name'])) {

                $where = sprintf(" and com_name = '%s' ", LibFc::Escape($company['com_name']));
                $infoRes = $this->Get('yp_compnay_info', $field, $where, true);

                if (!empty($infoRes['data']['com_id']) ) {
                    $company['com_etime'] = time();
                    $where  = sprintf(" and com_id = %d", LibFc::Int($infoRes['data']['com_id']));
                    $res = $this->Set('yp_compnay_info', $company, $where);
                    $company['com_id'] = $infoRes['data']['com_id'];
                } else {
                    $company['com_atime'] = time();
                    $company['com_etime'] = time();
                    $res = $this->Add('yp_compnay_info', $company);
                    $company['com_id'] = $res['data'];
                }
                unset($company['com_html'], $company['com_atime'], $company['com_etime']);
                return LibFc::ReturnData(true, $company);
            }
            return LibFc::ReturnData(true, $company);
        }
        unset($infoRes['data']['com_etime']);
        return $infoRes;
    }

    /**
     * @param  string $keyword 搜索的关键字 公司名或者统一社会信用代码
     * @method 爬天眼查网页内容
     * @author zhengweihua 
     * @copyright 2022-07-19
     */
    protected function crawlHtml($keyword)
    {
        //天眼查
        $url = 'https://www.tianyancha.com/search';
        $data = [
            'key' => $keyword
        ];
        $content = $this->curlGet($url, $data);
        //公司链接
        $hrefLink = '';
        //获取页面下公司列表
        preg_match("/<script id=\"__NEXT_DATA__\" type=\"application\/json\">({.*})<\/script>/is", $content, $jsonMatches);
        $data =  json_decode($jsonMatches[1], true);
        $companyList =  $data['props']['pageProps']['dehydratedState']['queries'][0]['state']['data']['data'];
        $companyArr =  $companyList['companyList']??[];

        if(empty($companyArr)) return LibFc::ReturnData(true, ['error' => '查不到该企业信息' . $keyword]);
        $companynum =  count($companyArr);
        if ($companynum>=1) 
        {
            $haspreg = 0;
            $error =  $companynum >1?'多企业：':'信息不完全匹配：';
            $error .= implode(',',array_map('strip_tags',array_column($companyArr,'name')));
            foreach ($companyArr as $companyItem) 
            {
                $prekey = '';
                //公司名
                if (preg_match("/[\x7f-\xff]/", $keyword)) 
                {
                    $prekey =  strip_tags($companyItem['name']);
                }
               
                if(preg_match("/^[a-z\d]+$/i",$keyword))
                {    //社会信用代码
                    $prekey =   $companyItem['creditCode'] ?$companyItem['creditCode']: ($companyItem['regNumber']?$companyItem['regNumber']:'');
                }
                if ($prekey == $keyword) 
                {
                    $hrefLink = 'https://www.tianyancha.com/company/'.$companyItem['id'];
                    $haspreg = 1;
                    break;
        
                }
                
            }
            if (empty($haspreg)) return LibFc::ReturnData(true, ['error' => $error]);
        } 
        

        if (empty($hrefLink)) return LibFc::ReturnData(true, ['error' => '匹配链接失败' . $keyword]);

        $contentDetail =  $this->curlGet($hrefLink);
        //匹配详情页里的json
        preg_match("/<script id=\"__NEXT_DATA__\" type=\"application\/json\">({.*})<\/script>/is", $contentDetail, $jsonMatches);
        if (empty($jsonMatches[1])) return LibFc::ReturnData(true, ['error' => '匹配内容失败' . $keyword]);
        $data =  json_decode($jsonMatches[1], true);
        $company =  $data['props']['pageProps']['dehydratedState']['queries'][0]['state']['data']['data'];

        $statusArr = ['开业' => 1, '在业' => 1, '存续' => 1, '注销' => -1, '吊销' => -1];
        $com_edate =  $company['toTime'] ? date('Y-m-d', $company['toTime'] / 1000) : '无固定期限';
        $retdata = [
            'com_name' => $company['name'],
            'com_code' => $company['creditCode'] ?$company['creditCode']: ($company['regNumber']?$company['regNumber']:''),
            'com_faren' => $company['legalPersonName'],
            'com_status' => $statusArr[$company['regStatus']] ?? 0,
            'com_status_remark' => $company['tagList'][0]['layer'] ?? '',
            'com_tel' => $company['phoneNumber'],
            'com_addr' => $company['taxAddress'],
            'com_build' => date('Y-m-d', $company['estiblishTime'] / 1000),
            'com_bdate' => date('Y-m-d', $company['fromTime'] / 1000),
            'com_edate' => $com_edate,
            'com_jyfw' => $company['businessScope'],
            'com_html' => $contentDetail
        ];
        return LibFc::ReturnData(true, $retdata);
    }

    protected function  curlGet($url, $data = [], $header = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55");
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_ACCEPT_ENCODING, "gzip, deflate, br");
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }

        $cookie_file = './cookies.txt';
        curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_file); 
        curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file); 

        $result = curl_exec($curl);
        if(!$result){
          $errormsgf =  curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    /**
     * @method 根据Xpath获取页面内容
     * @param  [string] $html 页面内容
     * @param  [string] $path xpath
     * @param  int    $tag 1:带标签 2:不带标签 其他获取attr内容 例如 href
     * @author zhengweihua 
     * @copyright 2022-07-19
     */
    protected function getHtmlDataByXpath($html, $path, $tag = 1)
    {

        $dom = new \DOMDocument();
        @$dom->loadHTML("" . $html); // 从一个字符串加载HTML并设置UTF8编码
        $dom->normalize(); // 使该HTML规范化
        $xpath = new \DOMXPath($dom); //用DOMXpath加载DOM，用于查询
        $contents = $xpath->query($path); // 获取所有内容
        $data = [];
        foreach ($contents as $value) {
            if ($tag == 1) {
                $data[] = $value->nodeValue; // 获取不带标签内容
            } elseif ($tag == 2) {
                $data[] = $dom->saveHtml($value);  // 获取带标签内容
            } else {
                $data[] = $value->attributes->getNamedItem($tag)->nodeValue; // 获取attr内容
            }
        }
        if (count($data) == 1) {
            $data = $data[0];
        }
        return $data;
    }

    /**
     * @param  string $keyword 企业名或者统一社会信用代码
     * @method 爱企查
     * @author zhengweihua 
     * @copyright 2022-07-19
     */
    protected function aiqicha($keyword)
    {
        // 处理get数据
        $url = 'https://aiqicha.baidu.com/m/advanceFilterAjax';
        $data = [
            't'=>0,
            'p'=>1,
            's'=>2,
            'o'=>0,
            'q' => $keyword,
        ];
        $header = array(
            'Refer'=>sprintf('https://aiqicha.baidu.com/m/s?q='.$keyword)
        );
        $result =  $this->curlGet($url, $data, $header);

        preg_match("/window.pageData = (({.*});)/is", $result, $matches);
        if (empty($matches['2'])) return LibFc::ReturnData(false, '获取数据失败');
        $result  = json_decode($matches[2], true);

        if ($matches[2]['result']['totalNum'] != 1) return LibFc::ReturnData(false, '公司数据不唯一');
        $resultList  = $matches[2]['result']['resultList'];
        if (empty($resultList)) return LibFc::ReturnData(false, '获取数据失败');
        $pid = $resultList[0]['pid'];
    }


    public function getCompanyName($link)
    {   
        $retdata = [
            'com_name' => '',
            'com_code'=>''
        ];
        if(stripos($link,'aiqicha.baidu.com')!==false){
          
            if (preg_match('/company_detail_([0-9]+)/', $link, $matches)) {
                $numberPart = $matches[1]; // 数字部分
                // $link = 'https://aiqicha.baidu.com/m/headInfoV2Ajax?pid='.$numberPart;
                // $referer = 'https://aiqicha.baidu.com/m/detail?pid='.$numberPart.'&from=s';
                $referer = $link;
                $link = 'https://aiqicha.baidu.com/detail/basicAllDataAjax?pid='.$numberPart;
            }
            $headerArr = array(
                'Accept: application/json, text/plain, */*',
                'Accept-Encoding: gzip, deflate, br',
                'Accept-Language: zh-CN,zh;q=0.9',
                'api-version:0',
                'auth-type:PAAS',
                'client-version:0',
                'connection:keep-alive',
                'Referer:'.$referer,
                'Cookie:_j47_ka8_=57; _s53_d91_=0e079516d640ccbdeb31d792b45f2eb61cdd1da67455dfc723ae15bd7c93347bf2d3ab08eda8311c04f3ce987118d0ec5251cd012f300253bc32ed06b7d1c082e8411b8530b3f54a9529fe034c49c5e98d0e22a0ee27f5a8907eda3fcc53d9641e6004dab7332293eca6dd4b7fe170c78b28e6c7513f83f559a5fc0b8a9324f1072f0f984cc3f456ca72873ed53c556395cca04a69188419cfee7bcf219d268c96a9fe1e5fd27e52a62d083061eb90bd6d9fdb8e80c524ac970159f26ef3a54b6de666f960de26f88c0cc6c76bf22d40; _y18_s21_=f056e449; BIDUPSID=65A5A0CBBC853D99F0635FD742500DFF; PSTM=1701408602; BDUSS=FHb01GYjhIOWppeXFVQW4yTEJMNlFMTGg0MUQ3WnBwR3czRXNVRkJSUDMtNVJsSVFBQUFBJCQAAAAAAAAAAAEAAACSoCYrvs3Ltc7SyfrBywAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPdubWX3bm1lVH; BAIDUID=65A5A0CBBC853D99F0635FD742500DFF:SL=0:NR=10:FG=1; BDPPN=d2ea963aa36b1224c03916b09bdf3360; log_guid=78172b0c83649dc43c4da1d05ff3a01d; BDUSS_BFESS=FHb01GYjhIOWppeXFVQW4yTEJMNlFMTGg0MUQ3WnBwR3czRXNVRkJSUDMtNVJsSVFBQUFBJCQAAAAAAAAAAAEAAACSoCYrvs3Ltc7SyfrBywAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPdubWX3bm1lVH; MCITY=-257%3A; H_PS_PSSID=60448_60359_60599_60663_60678_60699_60573; BAIDUID_BFESS=65A5A0CBBC853D99F0635FD742500DFF:SL=0:NR=10:FG=1; BAIDU_WISE_UID=wapp_1725067176571_750; __bid_n=191a1292bdc115288b71ff; H_WISE_SIDS_BFESS=60448_60359_60599_60623_60663_60678; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_WISE_SIDS=60448_60359_60599_60663_60678_60699_60573; arialoadData=false; login_type=passport; _t4z_qc8_=xlTM-TogKuTwl2qGfcz7%2A6WvenIVeMz3Pwmd; _j47_ka8_=57; log_chanel=s; BA_HECTOR=0h25a5010l8ga40lak0h8h808ou4qu1jdb4ae1v; ZFY=UPxjrF25oqvu6hZXSmEl2oiHcSBcMbnBxdvDWrqEWsk:C; Hm_lvt_ad52b306e1ae4557f5d3534cce8f8bbf=1725266958,1725325562; HMACCOUNT=7CF72AA8B69CD2FC; log_first_time=1725325562134; _fb537_=xlTM-TogKuTw5%2A0W8HSoM8Cem1qX3xkHno6PdCvj7Zaemd; ab172532520=87f0c24068c275ef5e2e2f5e17113a0b1725325571383; Hm_lpvt_ad52b306e1ae4557f5d3534cce8f8bbf=1725325572; ab_sr=1.0.1_NzllNGM2YTBjMTJkNzgzMThmNjg5MDdmM2E4ZjVlNWM4YTk2YTFhZGM4YTZlM2MwZDAxNDgxYTFkZmFjNjVhY2ZkNWExYTU1MWQ4ZDNlNzg1MGM1NWE0MDVkNjg4MzAyMDQzYTA4ZTZmNGQ4MDBjNjRjMDQxNmU5NTUzNTc1MDFhNDQzNzExM2FhNWQ3YTMxYzI3MTdiMzgxNzViNTMxYQ==; _s53_d91_=0e079516d640ccbdeb31d792b45f2eb61cdd1da67455dfc723ae15bd7c93347bf2d3ab08eda8311c04f3ce987118d0ecb4894a6b2c6d6a8de1111352778619d364907c3182776b5fd1a5bb76293b15dcfa673d5fdaa67e9eab6a7280a4f8b19e5035d4053be5d76fd2a721aeec7bf3174034f18f8ab95911b89c93a57cb3d581e4f1abfb5dec941a69213a8b230347bc2ab71941e5ab6dbad204789d2b648b56e13fd96c1d9fbe9d2b5d07f827f59fe941316227795c7b0343aa24a04698a5b08f034e300448bb24bd6d1aecb9b42e88; _y18_s21_=6755bb9e; fromPath=/;'
            );
            $html =  $this->curlGet($link,[],$headerArr);
            if(!$html){
                return LibFc::ReturnData(false,'页面获取失败');
            }
            $dataArray = json_decode($html, true);
            $retdata = [
                'com_name'=>$dataArray['data']['basicData']['entName'],
                'com_code'=>$dataArray['data']['basicData']['unifiedCode'],

                'email'=>$dataArray['data']['basicData']['email'],
                'website'=>$dataArray['data']['basicData']['website'],
                'mainWord'=>'',
                'telephone'=>$dataArray['data']['basicData']['telephone'],
              
                'faren'=>$dataArray['data']['basicData']['legalPerson'],
                'openStatus'=>$dataArray['data']['basicData']['openStatus'],
                'startDate'=>$dataArray['data']['basicData']['startDate'],
                'district'=>$dataArray['data']['basicData']['district'],
                'regCapital'=>$dataArray['data']['basicData']['regCapital'],
                'actualCapital'=>$dataArray['data']['basicData']['paidinCapital'],
                'entType'=>$dataArray['data']['basicData']['entType'],
                'industry'=>$dataArray['data']['basicData']['industry'],
                'businessNum'=>$dataArray['data']['basicData']['licenseNumber'],
                'orgNo'=>$dataArray['data']['basicData']['orgNo'],
                'taxNo'=>$dataArray['data']['basicData']['taxNo'],
                'openTime'=>$dataArray['data']['basicData']['openTime'],
                'hezhunDate'=>$dataArray['data']['basicData']['annualDate'],
                'authority'=>$dataArray['data']['basicData']['authority'],
                'insuranceNum'=>$dataArray['data']['basicData']['insuranceInfo']['insuranceNum']??'-',
                'regAddr'=>$dataArray['data']['basicData']['regAddr'],
                'scope'=>$dataArray['data']['basicData']['scope'],
            ];
            $html =  $this->curlGet($referer,[],$headerArr);
            if ($html && preg_match('/window\.pageData\s*=\s*(\{.*?\});/', $html, $matches)) {
              
                $jsonData = $matches[1];
                $dataArray = json_decode($jsonData, true);
  
                $retdata['email']=$dataArray['result']['email'];
                $retdata['website']=$dataArray['result']['website'];
                $retdata['mainWord']=implode(',',$dataArray['result']['mainWord']);
                $retdata['telephone']=$dataArray['result']['telephone'];
                
            }

        }elseif (stripos($link,'tianyancha.com')!==false) {
    
            //preg_match('/company\/(\d+)/', $link, $matches);

            // if (!empty($matches[1])) {
            //     $link = 'https://m.tianyancha.com/company/'.$matches[1].'?isnew=0';
            // }
            $header = [
                'Accept-Language: zh-CN,zh;q=0.9',
                'connection:keep-alive',
                'Referer:'.$link,
                'Cookie:jsid=SEO-BING-ALL-SY-000001; TYCID=2bf1a4d0690e11efad1e253e81b8952a; ssuid=2279338670; _ga=GA1.2.1747462657.1725269512; _gid=GA1.2.971202190.1725269512; CUID=0b71ee83d1a42ae7db3c70d51811933d; HWWAFSESID=6058717b59f22a5d552; HWWAFSESTIME=1725328408867; csrfToken=MTzlfaJd5vkBoOvHV3Ol7gb8; bannerFlag=true; Hm_lvt_e92c8d65d92d534b0fc290df538b4758=1725269523,1725328414; HMACCOUNT=7CF72AA8B69CD2FC; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22333967602%22%2C%22first_id%22%3A%22191b21385fec2-0c5c5b4d9b9108-4c657b58-2073600-191b21385ffc1e%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkxYjIxMzg1ZmVjMi0wYzVjNWI0ZDliOTEwOC00YzY1N2I1OC0yMDczNjAwLTE5MWIyMTM4NWZmYzFlIiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiMzMzOTY3NjAyIn0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22333967602%22%7D%2C%22%24device_id%22%3A%22191b21385fec2-0c5c5b4d9b9108-4c657b58-2073600-191b21385ffc1e%22%7D; tyc-user-phone=%255B%252218946503410%2522%255D; tyc-user-info={%22state%22:%220%22%2C%22vipManager%22:%220%22%2C%22mobile%22:%2218946503410%22%2C%22userId%22:%22333967602%22}; tyc-user-info-save-time=1725330390896; auth_token=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODk0NjUwMzQxMCIsImlhdCI6MTcyNTMzMDM5MSwiZXhwIjoxNzI3OTIyMzkxfQ.bJCKPvhdFYAwAzfFjOuyW2M9lq-00nbHZ5nHN1Q0t9moi61KwOLbIlGpGTftncrw26JAqo6O6AaByw0nZdwyuQ; searchSessionId=1725343601.95814108; Hm_lpvt_e92c8d65d92d534b0fc290df538b4758=1725343606',
            ];
            $contentDetail =  $this->curlGet($link,[],$header);
            //匹配详情页里的json
            preg_match("/<script id=\"__NEXT_DATA__\" type=\"application\/json\">({.*})<\/script>/is", $contentDetail, $jsonMatches);
            if (empty($jsonMatches[1])) return LibFc::ReturnData(true, ['error' => '匹配内容失败']);
            $data =  json_decode($jsonMatches[1], true);
            $company =  $data['props']['pageProps']['dehydratedState']['queries'][0]['state']['data']['data'];
    
            $retdata = [
                'com_name' => $company['name'],
                'com_code' => $company['creditCode'] ?$company['creditCode']: ($company['regNumber']?$company['regNumber']:''),
                'email'=> implode(',',$company['emailList']),
                'website'=>$company['websiteList'],
                'mainWord'=>'',
                'telephone'=>$company['phoneNumber'],
                'faren'=>$company['legalPersonName'],
                'openStatus'=>$company['regStatus'],
                'startDate'=>date('Y-m-d',$company['fromTime']/1000),
                'district'=>$company['district'],
                'regCapital'=>$company['regCapitalAmount'].$company['regCapitalAmountUnit'],
                'actualCapital'=>$company['actualCapital'],
                'entType'=>$company['companyOrgType'],
                'industry'=>$company['industry'],
                'businessNum'=>$company['regNumber'],
                'orgNo'=>$company['orgNumber'],
                'taxNo'=>$company['taxNumber'],
                'openTime'=>date('Y-m-d',$company['fromTime']/1000).'-'.date('Y-m-d',$company['toTime']/1000),
                'hezhunDate'=>'',
                'authority'=>$company['regInstitute'],
                'insuranceNum'=>'',
                'regAddr'=>$company['regLocation'],
                'scope'=>$company['businessScope'],
            ];
        }
		if($retdata['regAddr']){
			$OthPct = new OthPct();
			$res = $OthPct->formatAddrInfo($retdata['regAddr'], '', 0);
			$retdata['addrinfo'] = $res['data'];
		}
		if($retdata['email'] == '-') $retdata['email'] = '';
		if($retdata['website'] == '-') $retdata['website'] = '';
		if($retdata['telephone'] == '-') $retdata['telephone'] = '';
        return LibFc::ReturnData(true,$retdata);
    }
	
	//天眼查接口更新公司信息
	public function companyByApi($word)
	{
		$comid = 0;
		$cachetime = strtotime('-24 months');
		$word = LibFc::Escape($word);
		if(strlen($word) < 2) return LibFc::ReturnData(true, $comid);
		$whereArr = [
			sprintf(" and (com_name='%s' or com_name_en='%s' or com_credit_code='%s')", $word, $word, $word),
			sprintf(" and (com_alias='%s' or com_name_olds like ';%s;')", $word, $word),
		];
		foreach($whereArr as $where){
			$res = $this->get('company_info', ['com_id', 'com_etime'], $where);
			$comArr = $res['data'];
			if($comArr) break;
		}
		if(count($comArr) == 1 && $comArr[0]['com_etime'] > $cachetime || in_array($comArr[0]['com_regstatus'], ['注销', '吊销'])){
			$comid = $comArr[0]['com_id'];
		}else{
			$orgArr = $this->tycApi('ic/baseinfo/normal?keyword='.urlencode($word));
			if($orgArr['result']){
				$fields = [
					'alias'=>'com_alias',//简称                              
					'creditCode'=>'com_credit_code',//统一社会信用代码            
					'regStatus'=>'com_regstatus',//企业状态                        
					'name'=>'com_name',//公司名称                        
					'property3'=>'com_name_en',//公司名称英文                  
					'historyNames'=>'com_name_olds',//曾用名                           
					'isMicroEnt'=>'com_ismicroent',//是否是小微企业 0不是 1是  
					'type'=>'com_type',//法人类型，1个人 2公司      
					'companyOrgType'=>'com_orgtype',//企业类型                        
					'bondNum'=>'com_bond_num',//股票号                           
					'bondName'=>'com_bond_name',//股票名                           
					'legalPersonName'=>'com_legal_person',//法人姓名                        
					'businessScope'=>'com_business',//经营范围                        
					'industry'=>'com_industry',//行业                              
					'estiblishTime'=>'com_estiblish_time',//成立日期                        
					'fromTime'=>'com_from_time',//经营开始时间                  
					'toTime'=>'com_to_time',//经营结束时间                  
					'cancelDate'=>'com_cancel_date',//注销日期                  
					'socialStaffNum'=>'com_social_staff',//参保人数                       
					'city'=>'com_city',//市                                 
					'district'=>'com_distric',//区                                         
					'regLocation'=>'com_location',//注册地址                        
					'regCapital'=>'com_capital',//注册资本                                               
					'regCapitalCurrency'=>'com_currency',//注册资本币种                  
					'regNumber'=>'com_regnum',//工商注册号                  
					'staffNumRange'=>'com_staff',//人员规模                
					'tags'=>'com_tags',//标签                              
					'percentileScore'=>'com_score',//万分制 企业评分                                         
					'id'=>'com_from_id',//来源ID                            
					'updateTimes'=>'com_from_update',//来源的更新时间  
				];
				$addArr = [];
				foreach($fields as $of=>$nf){
					if(isset($orgArr['result'][$of])){
						$val = $orgArr['result'][$of];
						if(in_array($nf, ['com_ismicroent', 'com_type', 'com_social_staff', 'com_score', 'com_from_id'])){
							$val = (int) $val;
						}else if(in_array($nf, ['com_estiblish_time', 'com_from_time', 'com_to_time', 'com_cancel_date', 'com_from_update'])){
							$val = $val? $val / 1000: 0;
						}else{
							if($val === null) $val = '';
							if($val && $nf == 'com_name_olds')
								$val = ';'.trim($val, ';').';';
						}
						$addArr[$nf] = $val;
					}
				}
				
				if($addArr['com_name'] && $addArr['com_credit_code']){
					$OthPct = new OthPct();
					$txt = $addArr['com_distric']? $addArr['com_city'].$addArr['com_distric']: $addArr['com_location'];
					$res = $OthPct->formatAddrInfo($txt, '', 0);
					$addArr['com_province'] = $res['data']['pcts'][0]? $res['data']['pcts'][0]: '';
					$addArr['com_pct_ids'] = $res['data']['pctids']? implode(',', $res['data']['pctids']): '';
					$addArr['com_from'] = '天眼查';
					$addArr['com_etime'] = time();
					$com_keyword = [$addArr['com_credit_code'], $addArr['com_name']];
					if($addArr['com_alias']) $com_keyword[] = $addArr['com_alias'];
					if($addArr['com_name_en']) $com_keyword[] = $addArr['com_name_en'];
					$addArr['com_keyword'] = ';'.implode(';', array_unique($com_keyword)).';'.$addArr['com_name_olds'];
					$addArr['com_orgdata'] = json_encode($orgArr, JSON_UNESCAPED_UNICODE);
					$res = $this->get('company_info', ['com_id'], sprintf(" and com_credit_code='%s'", LibFc::Escape($addArr['com_credit_code'])), true);
					if(!empty($res['data'])){
						$comid = $res['data']['com_id'];
						$this->set('company_info', $addArr, sprintf(" and com_id=%d", $comid));
					}else{
						$addArr['com_atime'] = time();
						$res = $this->add('company_info', $addArr);
						$comid = $res['data'];
					}
				}/*else{
					return LibFc::ReturnData(false, '公司名称或者统一社会信用代码异常'.$orgdata);
				}*/
			}
		}
		return LibFc::ReturnData(true, $comid);
	}

	/**
	      天眼查接口
     * @param $uri /open/后的URI
     * @method 爬天眼查网页内容
     */
	public function tycApi($uri)
	{
		$url = 'http://open.api.tianyancha.com/services/open/'.$uri;
		$curl = curl_init();
		$header = ["Authorization: ".mvc::$cfg['TIANYANCHA']];
		curl_setopt($curl, CURLOPT_URL, $url); 
		curl_setopt($curl, CURLOPT_HEADER, 0); 
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		$orgdata = curl_exec($curl); 
		curl_close($curl);
		$orgArr = json_decode($orgdata, true);
		return $orgArr;
	}
}