import { Inject, Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { Repository } from 'typeorm';
import { BaseSysPermsService } from './perms';
import * as _ from 'lodash';
import { DataTableEntity } from '../../entity/sys/data_table';

/**
 * 系统用户
 */
@Provide()
export class BaseSysTableService extends BaseService {
  @InjectEntityModel(DataTableEntity)
  dataTableEntity: Repository<DataTableEntity>;

  @Inject()
  baseSysPermsService: BaseSysPermsService;

  @Inject()
  ctx;

  /**
   * 分页查询
   * @param query
   */
  async page(query) {
    const { keyWord, status, sourceIds = [] } = query;
    const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
      this.ctx.admin.userId
    ); // 部门权限
    const sql = `
        SELECT
            a.*,
            b.name as "dataSourceName"
        FROM
        config_data_table a
            LEFT JOIN config_data_source b ON a."sourceId" = b.id
        WHERE 1 = 1
            ${this.setSql(
              !_.isEmpty(sourceIds),
              'and a."sourceId" = ANY ($1)',
              [sourceIds]
            )}
            ${this.setSql(
              keyWord,
              !_.isEmpty(sourceIds)
                ? status !== undefined
                  ? 'and (a.name LIKE $3 or a.description LIKE $4)'
                  : 'and (a.name LIKE $2 or a.description LIKE $3)'
                : status !== undefined
                ? 'and (a.name LIKE $2 or a.description LIKE $3)'
                : 'and (a.name LIKE $1 or a.description LIKE $2)',
              [`%${keyWord}%`, `%${keyWord}%`]
            )}
            ${this.setSql(
              this.ctx.admin.username !== 'admin',
              !_.isEmpty(sourceIds)
                ? status !== undefined
                  ? keyWord !== undefined
                    ? 'and a."sourceId" = ANY ($5)'
                    : 'and a."sourceId" = ANY ($3)'
                  : keyWord !== undefined
                  ? 'and a."sourceId" = ANY ($4)'
                  : 'and a."sourceId" = ANY ($2)'
                : status !== undefined
                ? keyWord !== undefined
                  ? 'and a."sourceId" = ANY ($4)'
                  : 'and a."sourceId" = ANY ($2)'
                : keyWord !== undefined
                ? 'and a."sourceId" = ANY ($3)'
                : 'and a."sourceId" = ANY ($1)',

              [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]]
            )}
        GROUP BY a.id,b.name
        `;
    return this.sqlRenderPage(sql, query);
  }

  /**
   * 新增
   * @param param
   */
  async add(param) {
    const exists = await this.dataTableEntity.findOneBy({
      name: param.name,
    });
    if (!_.isEmpty(exists)) {
      throw new CoolCommException('表名已经存在~');
    }
    await this.dataTableEntity.save(param);
    return param.id;
  }
}
