# -*- encoding: utf-8 -*-
# 项目：JDG-
# 模块名称：
# 描述：
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at  2019/8/8 - 5:33 PM

from odoo import fields, api, models
from odoo.exceptions import ValidationError

TYPE = [('official', u'公章'), ('legal', u'法人章'), ('financial', u'财务章'), ('contract', u'合同章')]


class Seal(models.Model):
    _name = 'jd.digital.signature.seal'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'公司印章'

    company_id = fields.Many2one('res.company', string=u'分公司', required=True, domain=[('org_type', '=', 'branch')],
                                 default=False)
    name = fields.Char(required=False)

    line_ids = fields.One2many('jd.digital.signature.seal.line', 'parent_id', string=u'印章列表')
    seal_number = fields.Char(string=u'印章编码', related='line_ids.number')

    @api.multi
    @api.depends('company_id')
    def name_get(self):
        """
        名称显示格式：[XXX]YYY
        """
        result = []
        for item in self:
            name = u'【%s】印章' % item.company_id.name
            result.append((item.id, name))
        return result

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        for item in self:
            item.hide_edit_button = item.state in ('enable', 'discard')

    @api.model
    def create(self, values):
        """
        获取自动编号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            values.update({
                'number': self.env['ir.sequence'].next_by_code(self._name)
            })
        return super(Seal, self).create(values)

    @api.multi
    @api.constrains('company_id')
    def check_company(self):
        """
        公司重复校验
        :return:
        """
        for item in self:
            rec = self.sudo().search(
                [('state', '!=', 'discard'), ('company_id', '=', item.company_id.id), ('id', '!=', item.id)])
            if rec:
                raise ValidationError(u'已存在非作废状态的【%s】公司印章' % item.company_id.name)

    @api.multi
    def verify_data(self):
        for item in self:
            # 是否存在已启用的数据
            rec = self.sudo().search([('state', '=', 'enable'), ('company_id', '=', item.company_id.id)])
            if rec:
                raise ValidationError(u'存在已启用的【%s】公司印章' % item.company_id.name)

            # 印章编码重复校验
            number_list = []
            for line in item.line_ids:
                if line.number in number_list:
                    raise ValidationError(u'印章列表的印章编码【%s】不允许重复，请重新设置' % line.number)
                else:
                    number_list.append(line.number)

            # 印章编码系统唯一
            line_model = self.env['jd.digital.signature.seal.line']
            line_recs = line_model.sudo().search(
                [('number', 'in', number_list), ('parent_id.state', '!=', 'discard'), ('parent_id', '!=', item.id)])
            if line_recs:
                tip = ''
                error = u'印章编码【%s】已被公司【%s】使用，请更换印章编码\r\n'
                for line in line_recs:
                    tip += error % (line.number, line.parent_id.company_id.name)
                raise ValidationError(tip)

    @api.multi
    def do_enable(self):
        for item in self:
            item.verify_data()
        return super(Seal, self).do_enable()


class SealLine(models.Model):
    _name = 'jd.digital.signature.seal.line'
    _description = u'印章列表'

    parent_id = fields.Many2one('jd.digital.signature.seal', string=u'公司印章', ondelete='cascade', required=True)
    type = fields.Selection(TYPE, string=u'印章类型', default='official', required=True)
    image = fields.Binary(string=u'印章图片', attachment=True)
    number = fields.Char(string=u'印章编码', required=True)
    password = fields.Char(string=u'印章密码', required=True)
    note = fields.Char(string=u'备注')

    @api.multi
    @api.depends('parent_id.company_id', 'type')
    def name_get(self):
        """
        名称显示格式：[XXX]YYY
        """
        result = []
        for item in self:
            name = u'【%s】%s' % (item.parent_id.company_id.name, dict(TYPE).get(item.type))
            result.append((item.id, name))
        return result
