import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysDepartmentEntity } from '../../base/entity/sys/department';
import { BasicdataIotEntity } from '../entity/iot';
import { BaseSysPermsService } from '../../base/service/sys/perms';
import { BaseSysParamService } from '../../base/service/sys/param';
import * as _ from 'lodash';

/**
 * 数据源定义信息服务
 */
@Provide()
export class BasicdataIotService extends BaseService {
  @InjectEntityModel(BasicdataIotEntity)
  basicdataIotEntity: Repository<BasicdataIotEntity>;

  @InjectEntityModel(BaseSysDepartmentEntity)
  baseSysDepartmentEntity: Repository<BaseSysDepartmentEntity>;

  @Inject()
  baseSysParamService: BaseSysParamService;

  @Inject()
  baseSysPermsService: BaseSysPermsService;

  @Inject()
  ctx;


  /**
   * 获得部门菜单
   */
  async list() {
    const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
      this.ctx.admin.userId
    );
    // 过滤部门权限
    const sql = `
        (
            SELECT 
                a.id AS a_id,
                a.tenantId AS a_tenantId,
                a.name AS a_name,
                a.parentId AS a_parentId,
                a.orderNum AS a_orderNum
            FROM base_sys_department a 
            WHERE 1=1 
                ${this.setSql(
                  this.ctx.admin.username !== 'admin',
                  `and (a.departmentId in (?) `,
                  [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]]
                )}             
        )
        UNION ALL
        (
            SELECT 
                b.businessId AS a_id,
                a.tenantId AS a_tenantId,
                b.businessName AS a_name,
                b.departmentId AS a_parentId,
                a.orderNum AS a_orderNum
            FROM t_basicdata_site b
            LEFT JOIN base_sys_department a ON b.departmentId = a.id
        )
        ORDER BY a_orderNum ASC`;
    const result = await this.nativeQuery(sql);
    return result;    
  }

  /**
   * 监控设备查询
   */
  async getYsDevices(businessId: string) {
    // 修复原先key、secret取值颠倒bug + 增加await
    const ys7_appKey: string = await this.baseSysParamService.dataByKey('ys7.appKey');
    // departmentId 是数字，尝试转换；转换失败赋值 null
    const deptId = /^\d+$/.test(businessId) ? Number(businessId) : null;
    const qb = this.basicdataIotEntity.createQueryBuilder('a')
      .select([
        'a.id',
        'a.iotCode',
        'a.iotName',
        'a.iotTypeCode',
        'a.businessType',
        'a.businessId',
        'a.departmentId',
        'a.iotKey',
        'a.iotSecret',
        'a.iotChanel',
        'a.installLocation',
        'a.protocol'
      ])
      .where('a.iotTypeCode IN (:...typeIds)', {
        typeIds: ['萤石云固定监控', '萤石云车载监控'],
      });
    if (deptId !== null) {
      qb.andWhere('(a.businessId = :businessId OR a.departmentId = :deptId)', {
        businessId,
        deptId
      });
    } else {
      qb.andWhere('a.businessId = :businessId', { businessId });
    }
    const result = await qb.orderBy('a.iotName', 'ASC').getMany();
    const deviceList = result.map(item => {
      return {
        ...item,
        iotKey: ys7_appKey
      };
    });
    return deviceList;
  }


}