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 { DataFieldEntity } from '../../entity/sys/data_field';

/**
 * 系统用户
 */
@Provide()
export class BaseSysFieldService extends BaseService {
  @InjectEntityModel(DataFieldEntity)
  dataFieldEntity: Repository<DataFieldEntity>;

  @Inject()
  baseSysPermsService: BaseSysPermsService;

  @Inject()
  ctx;

  /**
   * 分页查询
   * @param query
   */
  async page(query) {
    const { keyWord, status, tableIds = [] } = query;
    const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
      this.ctx.admin.userId
    ); // 部门权限
    const sql = `
        SELECT
            a.*,
            b.name as "tableName"
        FROM
        config_data_field a
            LEFT JOIN config_data_table b ON a."tableId" = b.id
        WHERE 1 = 1
            ${this.setSql(!_.isEmpty(tableIds), 'and a."tableId" = ANY ($1)', [
              tableIds,
            ])}
            ${this.setSql(
              keyWord,
              !_.isEmpty(tableIds)
                ? 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(tableIds)
                ? status !== undefined
                  ? keyWord !== undefined
                    ? 'and a."tableId" = ANY ($5)'
                    : 'and a."tableId" = ANY ($3)'
                  : keyWord !== undefined
                  ? 'and a."tableId" = ANY ($4)'
                  : 'and a."tableId" = ANY ($2)'
                : status !== undefined
                ? keyWord !== undefined
                  ? 'and a."tableId" = ANY ($4)'
                  : 'and a."tableId" = ANY ($2)'
                : keyWord !== undefined
                ? 'and a."tableId" = ANY ($3)'
                : 'and a."tableId" = 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.dataFieldEntity.findOneBy({
      name: param.name,
      tableId: param.tableId,
    });
    if (!_.isEmpty(exists)) {
      throw new CoolCommException('字段名已经存在~');
    }
    await this.dataFieldEntity.save(param);
    return param.id;
  }

  async disList(tableId) {
    const exists = await this.dataFieldEntity.findBy({
      tableId: tableId,
    });
    return exists;
  }
}
