# -*- coding:utf-8 -*-
"""
data：2021/8/4 16:42

装置拆除：需要更新如下表：已兼容一分三情况
monitor：update demolished=1
change_meter_record：add new record with mid is NULL
change_sensor_record：add new record with sid, field is NULL
monitor_his_record：update demolished=1、demolished_ts
"""
import time
from asyncio import get_event_loop
from pot_libs.mysql_util.mysql_trans_util import MysqlUtil
from pot_libs.logger import log


async def _load_lids(mtids):
    sql = "SELECT id FROM power_iot.location WHERE mtid IN %s"
    async with MysqlUtil() as mysql_u:
        return [re["id"] for re in
                await mysql_u.fetchall(sql, (tuple(mtids),))]


async def dev_demolish(cid, sid):
    async with MysqlUtil() as mysql_u:
        # check monitor state
        sql = "SELECT mtid FROM power_iot.monitor " \
              "WHERE cid=%s AND sid=%s AND demolished=0"
        mtids = [re["mtid"] for re in await mysql_u.fetchall(sql, (cid, sid))]
        if not mtids:
            log.error(f"no monitor to demolish found, cid:{cid} sid:{sid}")
            return False, "该装置已经被拆除"
        
        sql = "SELECT pid,mtid FROM power_iot.point WHERE mtid IN %s"
        mtid_pid_list = await mysql_u.fetchall(sql, (tuple(mtids),)) or []
        mtid_pid_map = {re["mtid"]: re["pid"] for re in mtid_pid_list}
        if not mtid_pid_map:
            log.error(f"no mtid_pid_map found, mtids:{mtids}")
            return False, "该装置已经被拆除"
    
    now_ts = int(time.time())
    
    async with MysqlUtil() as mysql_u:
        try:
            # 1. update monitor
            sql = "UPDATE power_iot.monitor SET demolished=1 " \
                  "WHERE cid=%s AND sid=%s;"
            await mysql_u.execute(sql, args=(cid, sid))
            
            # 2. update monitor_his_record
            for mtid in mtids:
                # get install time
                record_sql = "select max(install_ts) install_ts from  " \
                             "power_iot.monitor_his_record " \
                             "WHERE mtid=%s AND sid=%s"
                start_ts = await mysql_u.fetch_value(record_sql,
                                                     (mtid, sid))
                if not start_ts:
                    sql = "SELECT create_time FROM point WHERE pid=%s;"
                    start_ts = await mysql_u.fetch_value(sql, (
                        mtid_pid_map.get(mtid),))
                log.info(
                    f"begin to demolish monitor:{mtid}, cid:{cid} sid:{sid} "
                    f"start_time:{start_ts} now_ts:{now_ts}")
                sql = "UPDATE power_iot.monitor_his_record " \
                      "SET demolished=1, demolished_ts=%s " \
                      "WHERE mtid=%s AND sid=%s AND install_ts=%s;"
                await mysql_u.execute(sql, (now_ts, mtid, sid, start_ts))
        except Exception as e:
            log.error(f"device demolish fail e:{e}")
            await mysql_u.rollback()
            return False, "装置拆除异常"
        else:
            await mysql_u.commit()
    
    log.info(f"finish demolish monitor:{mtids}, cid:{cid} sid:{sid} "
             f"start_time:{start_ts} now_ts:{now_ts}")
    
    return True, "操作成功"


if __name__ == '__main__':
    cid = 108
    sid = 'A1911000153'
    get_event_loop().run_until_complete(dev_demolish(cid, sid))
