# coding:utf-8
from __future__ import unicode_literals
import datetime
import json
import requests
from rpc.tool.error_code import gen, CODES


class Jike(object):

    def __init__(self, url, user, jike_hash, userid):
        self.url = url
        self.user = user
        self.hash = jike_hash
        self.userid = userid

    def get_jike_jump_url(self, amt=None, tnr=None):
        """
        :param amt: 贷款金额，单位元
        :param tnr: 贷款期限，单位月
        :param app_id: 订单号
        :return:
        """
        if not (amt and tnr):
            gen(CODES.PARAMS_INVALID)

        url = "{0}/refer/{1}/{2}/GX0300/{3}/_/_/_?amt={4}&tm={5}".format(self.url, self.user, self.hash, self.userid, amt, tnr)
        return url

    def get_jike_order_stage_status(self, app_ids=[]):
        """
        查询订单信息，jike GX0304接口
        :param app_ids: 订单号列表，最多10个
        :return:
        """
        if not app_ids:
            gen(CODES.PARAMS_INVALID)

        url = "{jike_url}/apis/{gm}/{hash}/GX0304/json".format(jike_url=self.url, gm=self.user, hash=self.hash)
        data = {
            'MERCHANT_ID': self.user,
            'TXN_CODE': 'GX0304',
            'TIME_STAMP': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'HASH_CODE': self.hash,
            'DATA': {
                'APP_ID': app_ids,
            },
        }

        r = requests.post(url, data=json.dumps(data))
        text = json.loads(r.text)
        if text.get('ERROR_CODE', None):
            gen(CODES.GET_ORDER_INFO_FAILED)
        data = text['DATA']
        total = data['TOTAL']
        res = data['RESULT']
        if not total:
            gen(CODES.GET_ORDER_INFO_FAILED)

        return res[0]['APP_STATUS']

    def get_rerund_info(self, app_id=''):
        """
        查询订单还款信息，jike GX0309接口
        :param app_id:
        :return:
        """
        if not app_id:
            gen(CODES.PARAMS_INVALID)

        url = "{jike_url}/apis/{gm}/{hash}/GX0309/json".format(jike_url=self.url, gm=self.user, hash=self.hash)
        data = {
            'MERCHANT_ID': self.user,
            'TXN_CODE': 'GX0309',
            'TIME_STAMP': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'HASH_CODE': self.hash,
            'DATA': {
                'APP_ID': app_id,
            },
        }

        r = requests.post(url, data=json.dumps(data))
        text = json.loads(r.text)
        if text.get('ERROR_CODE', None):
            gen(CODES.GET_JIKE_ORDER_INFO_FAILED)

        data = text['DATA']
        res = data['RESULT']
        total_num = data.get('N_TENOR_APPLIED', 0)
        left_num = data.get('C_CUR_PERD_NO', 0)
        result = {
            'desc': data.get('MTD_DESC', ''),
            'user_name': data.get('C_NAME_CN', ''),
            'app_id': data.get('APP_ID', ''),
            'total_num': total_num,
            'left_num': left_num,
            'finished_num': str(int(total_num) - int(left_num)),
            'apply_date': data.get('D_APP_CREATE', ''),
            'total_money': data.get('LOAN_AMT', 0),
            'left_money': data.get('N_CUR_LAST_AMT', 0),
            'first_refund_date': res[0].get('DUE_DT', '') if res else '',
        }
        return result

    def get_appid_by_order_id(self, order_id=''):
        """
        根据美购订单号获取jike APP_ID，jike GX0304接口
        :param order_id:
        :return:
        """
        if not order_id:
            gen(CODES.PARAMS_INVALID)

        url = "{jike_url}/apis/{gm}/{hash}/GX0304/json".format(jike_url=self.url, gm=self.user, hash=self.hash)
        data = {
            'MERCHANT_ID': self.user,
            'TXN_CODE': 'GX0304',
            'TIME_STAMP': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'HASH_CODE': self.hash,
            'DATA': {
                'ORDER_ID': order_id,
            },
        }

        r = requests.post(url, data=json.dumps(data))
        text = json.loads(r.text)
        if text.get('ERROR_CODE', None):
            gen(CODES.GET_ORDER_INFO_FAILED)

        data = text['DATA']
        total = data['TOTAL']
        res = data['RESULT']
        if not total:
            gen(CODES.GET_ORDER_INFO_FAILED)

        return res[0]['APP_ID']

    def get_jike_info_by_order_ids(self, order_ids=''):
        """
        查询订单信息，jike GX0304接口
        :param order_ids: 订单号列表，最多10个
        :return:
        """
        if not order_ids:
            gen(CODES.PARAMS_INVALID)

        url = "{jike_url}/apis/{gm}/{hash}/GX0304/json".format(jike_url=self.url, gm=self.user, hash=self.hash)
        data = {
            'MERCHANT_ID': self.user,
            'TXN_CODE': 'GX0304',
            'TIME_STAMP': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'HASH_CODE': self.hash,
            'DATA': {
                'ORDER_ID': order_ids,
            },
        }

        r = requests.post(url, data=json.dumps(data))
        text = json.loads(r.text)
        if text.get('ERROR_CODE', None):
            gen(CODES.GET_ORDER_INFO_FAILED)
        data = text['DATA']
        total = data['TOTAL']
        res = data['RESULT']
        if not total:
            gen(CODES.GET_ORDER_INFO_FAILED)

        result = {'total': total, 'result': res}
        return result
