import { Provide, Inject } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysAtlasEntity } from '../../entity/sys/atlas';
import { BaseSysLayersEntity } from '../../entity/sys/layers';
import { BaseSysRoleAtlasEntity } from '../../entity/sys/role_atlas';
import { BaseService } from '@cool-midway/core';
import { v1 as uuid } from 'uuid';
import { Context } from '@midwayjs/koa';

/**
 * 描述
 */
@Provide()
export class BaseSysAtlasService extends BaseService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(BaseSysAtlasEntity)
  baseSysAtlasEntity: Repository<BaseSysAtlasEntity>;

  @InjectEntityModel(BaseSysLayersEntity)
  baseSysLayersEntity: Repository<BaseSysLayersEntity>;

  @InjectEntityModel(BaseSysRoleAtlasEntity)
  baseSysRoleAtlasEntity: Repository<BaseSysRoleAtlasEntity>;

  async add(param) {
    const atlasId = uuid();
    param.layerList.map(e => {
      const entity = new BaseSysAtlasEntity();
      let cc = '';
      entity.atlasId = atlasId;
      entity.atlasName = param.atlasName;
      entity.atlasType = param.atlasType;
      // entity.isCheck = e.isCheck === undefined ? 3 : e.isCheck;
      if (e.isHide === '0') {
        cc += 'N';
      } else {
        cc += 'Y';
      }
      if (e.isExpand === '0') {
        cc += 'N';
      } else {
        cc += 'Y';
      }
      if (e.isCheck === undefined || e.isCheck === 3) {
        cc += 'N';
      } else {
        if (e.isCheck === 6) {
          cc += 'R';
        } else {
          cc += 'C';
        }
      }
      if (e.isInit === '0') {
        cc += 'N';
      } else {
        cc += 'Y';
      }
      // entity.isExpand = e.isExpand;
      // entity.isHide = e.isHide;
      // entity.isInit = e.isInit;
      entity.treeNode = cc;
      entity.opacity = e.opacity;
      entity.layerId = e.id;
      entity.orderNum = 0;
      this.baseSysAtlasEntity.save(entity);
    });

    return {
      id:
        param instanceof Array
          ? param.map(e => {
              return e.id;
            })
          : param.id,
    };
  }

  async update(param) {
    if (typeof param.layerList != 'string') {
      await this.baseSysAtlasEntity.delete({ atlasId: param.atlasId });

      param.layerList.map(e => {
        const entity = new BaseSysAtlasEntity();
        let cc = '';
        entity.atlasId = param.atlasId;
        entity.atlasName = param.atlasName;
        entity.atlasType = param.atlasType;
        // entity.isCheck = e.isCheck === undefined ? 3 : e.isCheck;
        if (e.isHide === '0' || e.isHide === undefined) {
          cc += 'N';
        } else {
          cc += 'Y';
        }
        if (e.isExpand === '0' || e.isExpand === undefined) {
          cc += 'N';
        } else {
          cc += 'Y';
        }
        if (e.isCheck === undefined || e.isCheck === 3) {
          cc += 'N';
        } else {
          if (e.isCheck === 6) {
            cc += 'R';
          } else {
            cc += 'C';
          }
        }
        if (e.isInit === '0' || e.isInit === undefined) {
          cc += 'N';
        } else {
          cc += 'Y';
        }
        // entity.isExpand = e.isExpand;
        // entity.isHide = e.isHide;
        // entity.isInit = e.isInit;
        entity.treeNode = cc;
        entity.opacity = e.opacity;
        entity.layerId = e.id;
        entity.orderNum = 0;
        this.baseSysAtlasEntity.save(entity);
      });
    }
  }

  async distinctList() {
    const roleIds = this.ctx.admin.roleIds;
    const isAdmin = this.ctx.admin.username === 'admin';
    return await this.nativeQuery(`
    select a.* from (SELECT
      distinct "atlasName","atlasId" id,"orderNum","atlasType"
    FROM
    map_atlas 
    ) a
    ${this.setSql(
      !isAdmin,
      'JOIN base_sys_role_atlas b on a."atlasId" = b."atlasId" AND b."roleId" = ANY ($1)',
      [roleIds]
    )}
    ORDER BY
        "orderNum" ASC`);
  }

  /**
   * 根据ID获得信息
   * @param id
   */
  public async info(id) {
    const info = await this.baseSysAtlasEntity.findOneBy({
      atlasId: id,
    });
    if (info) {
      // const atlas = await this.baseSysAtlasEntity.find({ atlasId: id });
      // const layerList = atlas.map(e => {
      //   return e.layerId + '';
      // });
      const layerList = id;
      return {
        ...info,
        layerList,
      };
    }
    return {};
  }

  async layerList(id) {
    const sql =
      `
    select * from map_layers l left join (select "layerId","atlasName","atlasId","atlasType",opacity,"treeNode",1 "pageCheck" from map_atlas
       WHERE "atlasId"='` +
      id +
      '\') a on l.id = a."layerId" ';
    return await this.nativeQuery(sql);
  }

  // async selectList(id) {
  //   return await this.baseSysAtlasEntity.find({ atlasId: id });
  // }

  async delete(ids) {
    if (ids instanceof Array) {
      ids.forEach(async id => {
        this.baseSysAtlasEntity.delete({ atlasId: id });
        this.baseSysRoleAtlasEntity.delete({ atlasId: id });
        // const atlas = await this.baseSysAtlasEntity.find({ atlasId: id });
        // atlas.map(e => {
        //   this.baseSysLayersEntity.delete({ id: e.layerId });
        // });
      });
    } else {
      ids.split(',').forEach(async id => {
        this.baseSysAtlasEntity.delete({ atlasId: id });
        this.baseSysRoleAtlasEntity.delete({ atlasId: id });
        // const atlas = await this.baseSysAtlasEntity.find({ atlasId: id });
        // atlas.map(e => {
        //   this.baseSysLayersEntity.delete({ id: e.layerId });
        // });
      });
    }
  }
}
