# -*- coding: utf-8 -*-
# 项目: jdg-hd-node-farm
# Copyright 2018 JDG <www.yunside.com>
# Create by CC <chen.chen@yunside.com> at 2018/8/1


from odoo.osv import osv
import requests
from odoo import SUPERUSER_ID, fields, api
from odoo import api, models

from jd_address_make_pin_yin import pinyin_quan, pinyin_abbr, first_pinyin


def location_name_search(self, name='', args=None, operator='ilike',
                         limit=100):
    args = args or []
    context = self.env.context

    if context.get('country_id'):
        args.append(('country_id', '=', context.get('country_id')))
    if context.get('state_id'):
        args.append(('country_id', '=', context.get('state_id')))
    if context.get('city_id'):
        args.append(('country_id', '=', context.get('city_id')))
    if context.get('subdivide_id'):
        args.append(('subdivide_id', '=', context.get('subdivide_id')))
    if context.get('town_id'):
        args.append(('town_id', '=', context.get('town_id')))
    if context.get('estate_id'):
        args.append(('estate_id', '=', context.get('estate_id')))

    domain = []
    if name:
        domain = ['|', ('code', 'ilike', name), '|', ('simple_spelling', 'ilike', name), '|',
                  ('spelling', 'ilike', name), ('name', operator, name)]
    records = self.search(domain + args, limit=limit)
    return records.name_get()


def get_treed(parent_code):
    result = requests.get(
        'https://lsp.wuliu.taobao.com/locationservice/addr/output_address_town_array.do?l3=%s&lang=zh-S&_ksTS=1474945446794_15253&callback=jsonp15254' % parent_code)

    def callback(obj):
        pass

    eval(result.content)


class ResCountryStateArea(models.Model):
    _description = u"城市"
    _name = 'res.country.state.area'
    _order = 'a_z'
    country_id = fields.Many2one('res.country.state', u'省', required=True, ondelete='restrict')
    name = fields.Char(u'名称', size=64, required=True)
    code = fields.Char(u'编号', size=30)
    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_uniq', 'unique (name, country_id)', u'存在相同名称的城市，请检查'),
        ('name_code_uniq', 'unique(country_id, code)', u'存在相同编号的城市，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        vals['name'] = vals['name'].upper()
        new_id = super(ResCountryStateArea, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResCountryStateArea, self).write(vals)

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        return location_name_search(self, name, args, operator, limit)


class ResCountryStateAreaSubdivide(models.Model):
    _description = u"县/区"
    _name = 'res.country.state.area.subdivide'
    _order = 'a_z'

    country_id = fields.Many2one('res.country.state.area', u'市',
                                 required=True, ondelete='restrict')
    name = fields.Char(u'区域', size=64, required=True)
    code = fields.Char(u'编号', size=30)
    zip = fields.Char(u'邮编', size=20)
    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)
    town_ids = fields.One2many('res.country.state.area.subdivide.town', 'subdivide_id', string=u'关联乡镇')

    _sql_constraints = [
        ('name_uniq', 'unique (name, country_id)', u'存在相同名称的县/区，请检查'),
        ('name_code_uniq', 'unique(country_id, code)', u'存在相同编号的县/区，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):

        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals['name'], dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        vals['name'] = vals['name'].upper()
        new_id = super(ResCountryStateAreaSubdivide, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResCountryStateAreaSubdivide, self).write(vals)

    def get_street(self, parent_code):
        import simplejson

        result = requests.get(
            'https://lsp.wuliu.taobao.com/locationservice/addr/output_address_town_array.do?l3=%s' % parent_code)
        result = result.content[len('callback({') + 1:]
        result = result[:len(result) - 2]
        result = result[len('{success:true,result:'):]
        result = result[:len(result) - 1]
        result = result.replace("'", '"')
        result = simplejson.loads(result)
        street_list = []
        for item in result:
            code = item[0]
            name = item[1]
            street_list.append({
                'code': code,
                'name': name
            })
        return street_list


class ResCountryStateAreaSubdivideTown(models.Model):
    _description = u"乡镇/街道"
    _name = 'res.country.state.area.subdivide.town'
    _order = 'a_z'

    subdivide_id = fields.Many2one('res.country.state.area.subdivide', u'县/区',
                                   required=True, ondelete='restrict')
    name = fields.Char(u'名称', size=64, required=True)
    code = fields.Char(u'编号', size=30)
    zip = fields.Char(u'邮编', size=20)
    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_code_uniq', 'unique(subdivide_id, code)', u'存在相同编号的乡镇/街道，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):

        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals['name'], dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        vals['name'] = vals['name'].upper()
        new_id = super(ResCountryStateAreaSubdivideTown, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResCountryStateAreaSubdivideTown, self).write(vals)

    @api.model
    def default_get(self, fields):
        res = super(ResCountryStateAreaSubdivideTown, self).default_get(fields)
        if self.env.context.get('subdivide_id', None):
            subdivide_id = self.env.context.get('subdivide_id', None)
            res.update({'subdivide_id': subdivide_id})
        return res


class ResCountry(models.Model):
    _inherit = 'res.country'
    _order = 'a_z'

    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_uniq', 'unique (name)', u'存在相同名称的国家，请检查'),
        ('name_code_uniq', 'unique(code)', u'存在相同编号的国家，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals['name'], dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        new_id = super(ResCountry, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResCountry, self).write(vals)


class ResCountryState(models.Model):
    _inherit = 'res.country.state'
    _description = u'省份'
    _order = 'a_z'

    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_uniq', 'unique (name, country_id)', u'存在相同名称的省份，请检查'),
        ('name_code_uniq', 'unique(country_id, code)', u'存在相同编号的省份，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals['name'], dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        vals['name'] = vals['name'].upper()
        new_id = super(ResCountryState, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResCountryState, self).write(vals)


class ResAddressEstate(models.Model):
    _name = 'res.address.estate'
    _description = u"住宅区域/小区"

    town_id = fields.Many2one('res.country.state.area.subdivide.town', u'乡镇/街道',
                              required=True)
    name = fields.Char(u'名称', size=64, required=True)
    code = fields.Char(u'编号', size=30)
    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_uniq', 'unique (name, town_id)', u'存在相同名称的住宅区域/小区，请检查'),
        ('name_code_uniq', 'unique(town_id, code)', u'存在相同编号的住宅区域/小区，请检查')
    ]


    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):

        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals.get('name', ''), dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals.get('name'))[0][0]
        vals['spelling'] = pinyin_quan(vals.get('name'), sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals.get('name'))
        vals['name'] = vals['name'].upper()
        new_id = super(ResAddressEstate, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResAddressEstate, self).write(vals)

    @api.model
    def default_get(self, fields):
        res = super(ResAddressEstate, self).default_get(fields)
        if self.env.context.get('town_id', None):
            subdivide_id = self.env.context.get('town_id', None)
            res.update({'town_id': subdivide_id})
        return res


class ResAddressBuilding(models.Model):
    _name = 'res.address.building'
    _description = u"楼房号/栋"

    estate_id = fields.Many2one('res.address.estate', u'住宅区域/小区',
                                required=True)
    name = fields.Char(u'名称', size=64, required=True)
    code = fields.Char(u'编号', size=30)
    a_z = fields.Char(u'首字母', size=1)
    simple_spelling = fields.Char(u'简拼', size=10)
    spelling = fields.Char(u'全拼', size=128)

    _sql_constraints = [
        ('name_uniq', 'unique (name, estate_id)', u'存在相同名称的楼房号/栋，请检查'),
        ('name_code_uniq', 'unique(estate_id, code)', u'存在相同编号的楼房号/栋，请检查')
    ]

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):

        return location_name_search(self, name, args, operator, limit)

    @api.model
    def create(self, vals):
        a_z = pinyin_abbr(vals['name'], dyz=False)[0][0]  # 输出("一些汉字",[全拼],[首字母])
        vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
        vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
        vals['simple_spelling'] = first_pinyin(vals['name'])
        vals['name'] = vals['name'].upper()
        new_id = super(ResAddressBuilding, self).create(vals)
        return new_id

    @api.multi
    def write(self, values):
        vals = dict(values)
        if vals.get('name', None):
            vals.update({'name': vals['name'].upper()})
            vals['a_z'] = pinyin_abbr(vals['name'])[0][0]
            vals['spelling'] = pinyin_quan(vals['name'], sep="", zhuyin=False, dyz=False)[0]
            vals['simple_spelling'] = first_pinyin(vals['name'])
        return super(ResAddressBuilding, self).write(vals)

    @api.model
    def default_get(self, fields):
        res = super(ResAddressBuilding, self).default_get(fields)
        if self.env.context.get('estate_id', None):
            subdivide_id = self.env.context.get('estate_id', False)
            res.update({'estate_id': subdivide_id})
        return res


class BaseAddress(models.AbstractModel):
    _name = 'jd.base.address'
    _description = u"标准地址"

    country_id = fields.Many2one('res.country', u'国家', default=lambda self: self._get_default_country())
    state_id = fields.Many2one('res.country.state', string=u'省份', ondelete='restrict')
    city_id = fields.Many2one('res.country.state.area', u'城市', ondelete='restrict')
    subdivide_id = fields.Many2one('res.country.state.area.subdivide', u'区县', ondelete='restrict')
    town_id = fields.Many2one('res.country.state.area.subdivide.town', string=u'乡镇', ondelete='restrict')
    estate_id = fields.Many2one('res.address.estate', string=u'住宅区域\小区')
    building_id = fields.Many2one('res.address.building', string=u'楼房号/栋')
    street = fields.Char(string=u'详细地址')
    zip = fields.Char(string=u'邮政编码')
    home_address = fields.Char(string=u'完整地址', readonly=True, compute='_compute_home_address', store=True)

    def _get_default_country(self):
        country = self.env['res.country'].search([('code', '=', 'CN')], limit=1)
        if country:
            return country.id

        return None

    @api.multi
    @api.depends('country_id', 'state_id', 'city_id', 'subdivide_id', 'town_id', 'street')
    def _compute_home_address(self):

        for item in self:
            home_address = ''
            item = item.sudo()
            if item.country_id:
                home_address += (' ' + item.country_id.name)
            if item.state_id:
                home_address += (' ' + item.state_id.name)
            if item.city_id:
                home_address += (' ' + item.city_id.name)
            if item.subdivide_id:
                home_address += (' ' + item.subdivide_id.name)
            if item.town_id:
                home_address += (' ' + item.town_id.name)
            if item.street:
                home_address += (' ' + item.street)

            item.home_address = home_address

    @api.multi
    @api.onchange('state_id')
    def onchange_state(self):
        for item in self:

            if item.state_id:

                item.country_id = item.state_id.country_id.id

                if item.city_id.country_id.id != item.state_id.id:
                    item.city_id = None

                if item.subdivide_id.country_id.id != item.city_id.id:
                    item.subdivide_id = None

                if item.town_id.subdivide_id.id != item.subdivide_id.id:
                    item.town_id = None

                return {'domain': {
                    'country_id': [('id', '=', item.state_id.country_id.id)],
                    'city_id': [('country_id', '=', item.state_id.id)]
                }}
            else:
                item.city_id = None
                item.subdivide_id = None
                item.town_id = None
                return {'domain': {
                    'country_id': [],
                    'city_id': [('id', '=', 0)]
                }}

    @api.multi
    @api.onchange('city_id')
    def onchange_area(self):
        for item in self:

            if item.city_id:

                item.state_id = item.city_id.country_id.id
                item.country_id = item.state_id.country_id.id

                if item.subdivide_id.country_id.id != item.city_id.id:
                    item.subdivide_id = None

                if item.town_id.subdivide_id.id != item.subdivide_id.id:
                    item.town_id = None

                return {'domain': {
                    'country_id': [('id', '=', item.city_id.country_id.country_id.id)],
                    'state_id': [('id', '=', item.city_id.country_id.id)],
                    'subdivide_id': [('country_id', '=', item.city_id.id)]
                }}
            else:
                item.subdivide_id = None
                item.town_id = None
                return {'domain': {
                    'country_id': [],
                    'state_id': [],
                    'subdivide_id': [('id', '=', 0)]
                }}

    @api.multi
    @api.onchange('subdivide_id')
    def onchange_subdivide(self):
        for item in self:

            if item.subdivide_id:

                item.city_id = item.subdivide_id.country_id.id
                item.state_id = item.city_id.country_id.id
                item.country_id = item.state_id.country_id.id

                if item.town_id.subdivide_id.id != item.subdivide_id.id:
                    item.town_id = None

                return {'domain': {
                    'country_id': [('id', '=', item.subdivide_id.country_id.country_id.country_id.id)],
                    'state_id': [('country_id', '=', item.subdivide_id.country_id.country_id.id)],
                    'city_id': [('id', '=', item.subdivide_id.country_id.id)],
                    'town_id': [('subdivide_id', '=', item.subdivide_id.id)],
                }}
            else:
                item.town_id = None
                return {'domain': {
                    'country_id': [],
                    'state_id': [],
                    'city_id': [],
                    'town_id': [],
                }}

    @api.multi
    @api.onchange('town_id')
    def onchange_town(self):
        for item in self:
            if item.town_id:

                item.subdivide_id = item.town_id.subdivide_id.id
                item.city_id = item.subdivide_id.country_id.id
                item.state_id = item.city_id.country_id.id
                item.country_id = item.state_id.country_id.id

                return {'domain': {
                    'country_id': [
                        ('id', '=', item.town_id.subdivide_id.country_id.country_id.country_id.id)],
                    'state_id': [('id', '=', item.state_id.id)],
                    'city_id': [('id', '=', item.town_id.subdivide_id.country_id.id)],
                    'subdivide_id': [('id', '=', item.town_id.subdivide_id.id)],
                }}
            else:
                return {'domain': {
                    'country_id': [],
                    'state_id': [],
                    'city_id': [],
                    'subdivide_id': [],
                }}

