import { DataModel, transformArrayDataModel, transformDataModel, type KeyValue } from '@imengyu/js-request-transform';
import { AppServerRequestModule } from '../RequestModules';
import { transformSomeToArray } from '../Utils';

export class VillageListItem extends DataModel<VillageListItem> {
  constructor() {
    super(VillageListItem, "活动列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      isLight: { clientSide: 'boolean' },
      rank: { clientSide: 'number', serverSide: 'number' },
      volunteerCount: { clientSide: 'number', serverSide: 'number' },
      followCount: { clientSide: 'number', serverSide: 'number' },
      collectCount: { clientSide: 'number', serverSide: 'number' },
      light: { clientSide: 'number', serverSide: 'number' },
      lightTotal: { clientSide: 'number', serverSide: 'number' },
      fruitOutput: { clientSide: 'number', serverSide: 'number' },
      fruitRemain: { clientSide: 'number', serverSide: 'number' },
      fruitToday: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'number' },
    }
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('At'))
        return {
          clientSide: 'date',
          serverSide: 'string',
        };
      return undefined;
    };
    this._afterSolveServer = () => {
      this.address = 
        (this.province || '') + 
        (this.city || '') + 
        (this.district || '') + 
        (this.township || '');
      if (this.images && this.images && this.images.length > 0  ) {
        this.image = this.images[0]
      }
      this.thumbnail = this.image;
    }

  }

  id !: number;
  province = '' as string|null;
  city = '' as string|null;
  district = '' as string|null;
  township = '' as string|null;
  address = '';
  isLight = false;
  isLightText = '';
  lightValue = Math.random();
  villageVolunteerId = null as number|null;
  villageId !:number;
  claimReason = '';
  status = '';
  statusText = '';
  createdAt = null as Date|null;
  updatedAt = null as Date|null;
  deleteAt = null as Date|null;
  image = '';
  thumbnail = '';
  images = [] as string[];
  name = '';
  title = '';rank = 0;
  volunteerCount = 0;
  followCount = 0;
  collectCount = 0;
  light = 0;
  lightTotal = 0;
  fruitOutput = 0;
  fruitRemain = 0;
  fruitToday = 0;
  level = 0;
  volunteerName = '';
}

export class PostMessage extends DataModel<PostMessage> {
  constructor() {
    super(PostMessage, "微信贴图");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      title: { clientSide: 'string', serverSide: 'string' },
      images: { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
      sendTime: { clientSide: 'date', serverSide: 'string' },
    }
    this._afterSolveServer = () => {
      if (!this.images) {
        this.images = [];
      }
      if (this.image && this.images?.length == 0) {
        this.images = [ this.image ];
      }
    }
  }

  id !: number;
  title = '';
  content = '';
  images = [] as string[];
  image = '';
  nickName = '';
  avatar = '';
  likeCount = 0;
  shareCount = 0;
  sendTime = new Date();
}

export class LightVillageApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  /**
   * 志愿者排行榜
   * POST /village/volunteer/getRanklist
   */
  async getVolunteerRankList(params?: {
    /** 地区（区域内所有村社） */
    region_id?: number;
    /** 数量：显示前几名（默认10） */
    num?: number;
    /** 村社ID */
    village_id?: number;
  }) {
    const res = await this.post<{
      id: number;
      name: string;
      mobile: string;
      points: number;
      level: number;
      type: string;
      type_text?: string;
      sex_text?: string;
      status_text?: string;
      image?: string;
    }[]>('/village/volunteer/getRanklist', '志愿者排行榜', params);
    return res.requireData();
  }

  /**
   * 村社排行榜
   * POST /village/village/getRanklist
   */
  async getVillageRankList(params?: {
    /** 地区（区域内所有村社） */
    region_id?: number;
    /** 数量：显示前几名（默认10） */
    num?: number;
    /** 点亮状态:0=未点亮,1=已点亮 */
    is_light?: number;
  }) {
    const res = await this.post<{
      id: number;
      name: string;
      points: number;
      region: number;
      status?: string;
      is_light: number | string;
      status_text?: string;
      region_text?: string;
      is_light_text?: string;
      image?: string;
    }[]>('/village/village/getRanklist', '村社排行榜', params);
    return res.requireData();
  }

  async getVillageList(level?: number, region?: number, status?: number, page?: number, pageSize?: number) {
    const res = await this.get<{
      data: any[],
      total: number,
    }>('/village/village/list', '乡源村落列表', {
      history_level: level,
      status,
      region: region,
      page: page,
      pageSize: pageSize,
    });
    return {
      total: res.requireData().total,
      list: transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.requireData().data), `村落`, true)
    }
  }
  
  async getVillageDetails(id: number) {
    const res = await this.get<VillageListItem>('/village/village/getInfo', '村社详情', {
      id: id,
    }, VillageListItem);
    return res.requireData();
  }

  async getIpAddress() {
    const res = await this.get<{
      address: string,
      address_detail:{
        adcode: string,
        city: string,
        city_code: number,
        district: string,
        province: string,
        street: string,
        street_number: string,
      },
      point: {
        x: string,
        y: string,
      },
    }>('/village/volunteer/getIpArea', '获取IP地址');
    return res.requireData();
  }

  async getMessages(page: number, pageSize: number, search?:{
    keywords?: string;
    villageId?: number;
    userId?: number;
  }) {
    const res = await this.get<{
      data: KeyValue[],
      total: number,
    }>('/village/collect/wechatContentList', '获取微信贴图列表', {
      page,
      pageSize,
      keywords: search?.keywords,
      village_id: search?.villageId,
      user_id: search?.userId,
    });
    const data = res.requireData();
    return {
      list: transformArrayDataModel<PostMessage>(PostMessage, transformSomeToArray(data.data), '微信贴图列表', true),
      total: data.total,
    };
  }

  async getMessageDetails(id: number) {
    const res = await this.get<KeyValue>('/village/collect/wechatContentDetail', '获取微信贴图详情', {
      id: id,
    });
    return transformDataModel<PostMessage>(PostMessage, res.requireData());
  }

  async publishMessage(params: PostMessage) {
    return await this.post<KeyValue>('/village/collect/wechatContentSave', '发布微信贴图', params.toServerSide());
  }

  async updateVillageGallery(id: number, images: string[]) {
    return await this.post<KeyValue>('/village/village/save', '更新村社相册', {
      id: id,
      images: images,
    });
  }
}


export default new LightVillageApi();
