# -*- 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 FROM power_iot.point WHERE mtid IN %s"
        pids = [re["pid"] for re in
                await mysql_u.fetchall(sql, (tuple(mtids),))]
        if not pids:
            log.error(f"no pids found, mtids:{mtids}")
            return False, "该装置已经被拆除"
        
        # start_time, now_ts
        sql = "SELECT start_time FROM change_meter_record " \
              "WHERE pid=%s ORDER BY start_time desc LIMIT 1;"
        start_ts = await mysql_u.fetch_value(sql, (pids[0],))
    
    now_ts = int(time.time())
    log.info(f"begin to demolish monitor:{mtids}, cid:{cid} sid:{sid} "
             f"start_time:{start_ts} now_ts:{now_ts}")
    
    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 change_meter_record: add new line with mid is null
            for pid in pids:
                sql = "INSERT INTO power_iot.change_meter_record " \
                      "(pid, start_time) VALUES (%s, %s);"
                await mysql_u.execute(sql, args=(pid, now_ts))
            
            # 3. update change_sensor_record: add new line with sid, field is null
            for lid in await _load_lids(mtids):
                sql = "INSERT INTO power_iot.change_sensor_record " \
                      "(location_id, start_time) VALUES (%s, %s);"
                await mysql_u.execute(sql, args=(lid, now_ts))
            
            # 4. update monitor_his_record
            for mtid in mtids:
                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))
