# encoding:utf-8
import json
import traceback
from tablestore import TermQuery, BoolQuery, Condition, Row, OTSServiceError, OTSClientError, ColumnsToGet, SearchQuery, \
    ColumnReturnType

from BaseDataMaintenance.common.Utils import getRow_ots, log
from BaseDataMaintenance.model.ots.BaseModel import BaseModel
from datetime import datetime

approval_project_uuid = 'uuid'
approval_project_docids = 'docids'
approval_project_area = 'area'
approval_project_province = 'province'
approval_project_city = 'city'
approval_project_district = 'district'
approval_project_source_stage = 'source_stage'
approval_project_source_type = 'source_type'
approval_project_approval_items = 'approval_items'
approval_project_approval_result = 'approval_result'
approval_project_approver = 'approver'
approval_project_construct_company = 'construct_company'
approval_project_construct_company_code = 'construct_company_code'
approval_project_construction_scale = 'construction_scale'
approval_project_declare_company = 'declare_company'
approval_project_doc_nums = 'doc_nums'
approval_project_evaluation_agency = 'evaluation_agency'
approval_project_legal_person = 'legal_person'
approval_project_phone = 'phone'
approval_project_pro_type = 'pro_type'
approval_project_properties = 'properties'
approval_project_time_declare = 'time_declare'
approval_project_year_limit = 'year_limit'
approval_project_compilation_unit = 'compilation_unit'
approval_project_publisher = 'publisher'
approval_project_time_approval = 'time_approval'
approval_project_moneysource = 'moneysource'
approval_project_project_addr = 'project_addr'
approval_project_project_name = 'project_name'
approval_project_time_commencement = 'time_commencement'
approval_project_time_completion = 'time_completion'
approval_project_time_release = 'time_release'
approval_project_env_invest = 'env_invest'
approval_project_proportion = 'proportion'
approval_project_length = 'length'
approval_project_use_area = 'use_area'
approval_project_construct_company_province = 'construct_company_province'
approval_project_construct_company_city = 'construct_company_city'
approval_project_construct_company_district = 'construct_company_district'
approval_project_money_use = 'money_use'
approval_project_declare_type = 'declare_type'
approval_project_page_time = 'page_time'
approval_project_doctitle = 'doctitle'
approval_project_project_codes = 'project_codes'
approval_project_total_tenderee_money = 'total_tenderee_money'
approval_project_total_tenderee_money_unit = 'total_tenderee_money_unit'
approval_project_status = 'status'
approval_project_update_time = 'update_time'


class approval_project(BaseModel):
    def __init__(self, _dict):
        for k, v in _dict.items():
            self.setValue(k, v, True)
        self.table_name = "approval_project"

    def getPrimary_keys(self):
        return ["uuid"]

    def getAttribute_turple(self):
        _list = []
        for _key in self.getAttribute_keys():
            if _key == "all_columns":
                continue
            _v = self.getProperties().get(_key)
            if _v is not None:
                if isinstance(_v, list):
                    _v = json.dumps(_v)
                _list.append((_key, _v))
        return _list

    def update_row(self, ots_client, retrytimes=3, delete=0):
        primary_key = self.getPrimaryKey_turple()
        update_of_attribute_columns = {
            'PUT': self.getAttribute_turple()
        }
        row = Row(primary_key, update_of_attribute_columns)
        condition = Condition('IGNORE')
        for i in range(retrytimes):
            try:
                if self.exists_row(ots_client) and delete:
                    self.delete_row(ots_client)
                consumed, return_row = ots_client.update_row(self.table_name, row, condition)
                return True
            # 客户端异常，一般为参数错误或者网络异常。
            except OTSClientError as e:
                traceback.print_exc()
                log("update row failed, http_status:%s, error_message:%s" % (
                    str(e.get_http_status()), e.get_error_message()))
                # raise e
            # 服务端异常，一般为参数错误或者流控错误。
            except OTSServiceError as e:
                traceback.print_exc()
                log("update row failed, http_status:%s, error_code:%s, error_message:%s, request_id:%s" % (
                    str(e.get_http_status()), e.get_error_code(), e.get_error_message(), e.get_request_id()))
                # raise e
            except Exception as e:
                traceback.print_exc()
                pass
                # raise e
        return False
        # log ('update succeed, consume %s write cu.' % consumed.write)

    def update_project(self, ots_client):
        current_time = datetime.now()
        current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')

        # 判断是否已存在docids重复的，都更改status为404，更新时间
        merge_uuids = self.__dict__.get('merge_uuids')
        old_uuid = None
        if len(merge_uuids) > 0:
            old_uuid = merge_uuids[0]
            for uuid in merge_uuids:
                _dict = {
                    'uuid': uuid,
                    'update_time': current_time,
                    'status': 404,
                }
                delete_project = approval_project(_dict)
                delete_project.update_row(ots_client)

        # 复用uuid
        if old_uuid is not None:
            print('old_uuid', old_uuid)
            self.setProperties('uuid', old_uuid)
        self.setValue('update_time', current_time)
        self.setValue('status', 1)
        self.__dict__.pop('merge_uuids')
        self.update_row(ots_client)


if __name__ == "__main__":
    value_list = [['abc', 1], ['ab', 1]]
    value_list.sort(key=lambda x: (x[1], len(x[0])))
    print(value_list)
