# -*- coding: utf-8 -*-

from time import time
from common import BaseHandler


import re,urllib2,urllib
#import logging
try:
    import json
except:
    import simplejson as json

###############

result_str = '''<a href=".*?reg_bus_ent_id=(.*?)&flag_cer=0"><u>(.*?)</u></a></td><td style="text-align:center"  width="10%"   >(.*?)</td><td style="text-align:center"  width="18%"   >(.*?)</td><td style="text-align:center"  width="10%"   >(\d+-\d\d-\d\d)</td><td style="text-align:center"  width="10%"   >(.*?)</td></tr>'''
#result_str = '''<td style="text-align:center"  width="25%"   ><a href="(.*?)"><u>(.*?)</u></a></td><td style="text-align:center"  width="10%"   >(.*?)</td><td style="text-align:center"  width="18%"   >(.*?)</td><td style="text-align:center"  width="10%"   >(\d+-\d\d-\d\d)</td><td style="text-align:center"  width="10%"   >(.*?)</td></tr>'''
detail_str = '''<td class="td02" .*? td>(.*?)</td>'''
result_obj = re.compile(result_str,  re.DOTALL)
detail_obj = re.compile(detail_str,  re.DOTALL)


def bjqs(type = 0,qStr = '搜狐'):
    result = []
    headers = {
        'User-Agent':"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3",
        'Referer':r'http://qyxy.baic.gov.cn/zhcx/zhcxAction!list.dhtml?op=cx',
        'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7'
    }

    qStr = qStr.encode('utf-8')

    postdata=urllib.urlencode({
        'zhcxModel.cer_no':'',
        'zhcxModel.corp_rpt':'',
        'zhcxModel.dom':'',
        'zhcxModel.lic_reg_no':'',
        'zhcxModel.ent_name':qStr
    })

    url = 'http://qyxy.baic.gov.cn/zhcx/zhcxAction!list.dhtml?op=cx'
    req = urllib2.Request(
        url = url,
        data = postdata,
        headers = headers
    )

    try:
        rsp = urllib2.urlopen(req).read().replace('\n','').replace('\r','').replace('\t','')
        matched_objs = result_obj.findall(rsp)
        if len(matched_objs):
            #print len(matched_objs)
            for obj in matched_objs:
                mydict = {}
                #print obj
                durl,comp,regno,faren,regdate,status = obj
                mydict['durl']    = durl
                mydict['comp']    = comp
                mydict['regno']   = regno
                mydict['faren']   = faren
                mydict['regdate'] = regdate
                mydict['status']  = status
                result.append(mydict)
            #print result
            return result
        else:
            return None
    except:
        return None

def detail(url = 'http://qyxy.baic.gov.cn/kscx/kscxAction!view.dhtml?kscxModel.reg_bus_ent_id=4459AD78BB3341B488C6FF735E1FB638&flag_cer=0'):
    result = []
    headers = {
        'User-Agent':"http://qyxy.baic.gov.cn/kscx/kscxAction!view.dhtml?kscxModel.reg_bus_ent_id=4459AD78BB3341B488C6FF735E1FB638&flag_cer=0",
        'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7'
    }
    req = urllib2.Request(
        url = url,
        headers = headers
    )

    rsp = urllib2.urlopen(req).read().replace('\n','').replace('\r','').replace('\t','')
    try:
        matched_objs = detail_obj.findall(rsp)
        if len(matched_objs):
            mydict = {}
            regno,type,cclass,comp,faren,area,born,money,begin,end,rego,status,addr,scope,scope2,year,pstatus = matched_objs
            mydict['type']    = type
            mydict['comp']    = comp
            mydict['regno']   = regno
            mydict['faren']   = faren
            mydict['area']    = area
            mydict['born']    = born
            mydict['money']   = money.replace(' ','')
            mydict['begin']   = begin.replace(' ','').replace('&nbsp;','')
            mydict['end']     = end.replace(' ','')
            mydict['rego']    = rego
            mydict['status']  = status
            mydict['addr']    = addr
            mydict['scope']   = scope
            mydict['year']    = year
            mydict['pstatus'] = pstatus
            result.append(mydict)
            #print result
            return result
    except:
        pass
    return None



#########################################################################################################
class Index(BaseHandler):
    def get(self):
        self.write("Hello SAE")

class NotFoundPage(BaseHandler):
    def get(self):
        self.set_status(404)
        self.write("404: Not found")

class FetchBJQS(BaseHandler):
    def get(self, type = '', qStr = ''):
        flag = True
        if type == '' or qStr == '':
            flag = False
        try:
            type = int(type)
        except:
            flag = False

        if flag:
            #url.encode('utf-8')
            self.set_header('Content-Type','application/json')
            rsp = bjqs(type,qStr)
            if rsp:
                rspd = {'status': 200}
                rspd['company'] = rsp
                rspd['msg'] = 'ok'
            else:
                rspd = {'status': 500}
                rspd['company'] = ''
                rspd['msg'] = 'fail'
            self.write(json.dumps(rspd))
        else:
            self.write('')

class FetchBJQSDetail(BaseHandler):
    def get(self, reg_bus_ent_id = ''):
        flag = True
        if reg_bus_ent_id == '':
            flag = False

        if flag:
            self.set_header('Content-Type','application/json')
            url = 'http://qyxy.baic.gov.cn/kscx/kscxAction!view.dhtml?kscxModel.reg_bus_ent_id=%s&flag_cer=0' % (str(reg_bus_ent_id))
            rsp = detail(url)
            if rsp:
                rspd = {'status': 200}
                rspd['detail'] = rsp
                rspd['msg'] = 'ok'
            else:
                rspd = {'status': 500}
                rspd['detail'] = ''
                rspd['msg'] = 'fail'
            self.write(json.dumps(rspd))
        else:
            self.write('')

########
urls = [
    (r"/", Index),
    (r"/api/(\d+)/(.*)$", FetchBJQS),
    (r"/api/d/(.*)", FetchBJQSDetail),
    (r".*", NotFoundPage)
]
