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' },
      region: { clientSide: 'number', serverSide: 'number' },
      rank: { clientSide: 'number', serverSide: 'number' },
      volunteerCount: { clientSide: 'number', serverSide: 'number' },
      followCount: { clientSide: 'number', serverSide: 'number' },
      collectCount: { clientSide: 'number', serverSide: 'number' },
      villageType: { clientSide: 'number', serverSide: 'number' },
      altitude: { clientSide: 'number', serverSide: 'number' },
      longitude: { clientSide: 'number', serverSide: 'number' },
      latitude: { clientSide: 'number', serverSide: 'number' },
      age: { clientSide: 'number', serverSide: 'number' },
      area: { clientSide: 'number', serverSide: 'number' },
      villageArea: { clientSide: 'number', serverSide: 'number' },
      traditionalBuildings: { clientSide: 'number', serverSide: 'number' },
      ichLevel: { clientSide: 'number', serverSide: 'number' },
      historyLevel: { clientSide: 'number', serverSide: 'number' },
      touristLevel: { clientSide: 'number', serverSide: 'number' },
      isFeaturedVillage: { clientSide: 'number', serverSide: 'number' },
      registeredPopulationYear: { clientSide: 'number', serverSide: 'number' },
      registeredPopulation: { clientSide: 'number', serverSide: 'number' },
      permanentPopulationYear: { clientSide: 'number', serverSide: 'number' },
      permanentPopulation: { clientSide: 'number', serverSide: 'number' },
      personalAnnualIncomeYear: { clientSide: 'number', serverSide: 'number' },
      villageAnnualIncomeYear: { clientSide: 'number', serverSide: 'number' },
      points: { 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' },
      weight: { clientSide: 'number', serverSide: 'number' },
      vipLevel: { clientSide: 'number', serverSide: 'number' },
      overviewId: { clientSide: 'number', serverSide: 'number' },
      myOverviewId: { clientSide: 'number', serverSide: 'number' },
      treeLight: { clientSide: 'number', serverSide: 'number' },
      nextTreeLight: { clientSide: 'number', serverSide: 'number' },
      nextTreeLevel: { clientSide: 'number', serverSide: 'number' },
      imageLimit: { clientSide: 'number', serverSide: 'number' },
      storageLimit: { clientSide: 'number', serverSide: 'number' },
      managerLimit: { 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;
      if (!this.name && this.villageName)
        this.name = this.villageName as string;
      if (this.villageId)
        this.id = this.villageId;
    }

  }

  id !: number;
  /** 地区 */
  region = 0;
  /** 省份/省级行政区 */
  province = '' as string|null;
  /** 城市/地级行政区 */
  city = '' as string|null;
  /** 区县/县级行政区 */
  district = '' as string|null;
  /** 乡镇/乡级行政区 */
  township = '' as string|null;
  /** 拼接地址（客户端计算） */
  address = '';
  /** 村落编码 */
  code = '' as string|null;
  /** 是否点亮 */
  isLight = false;
  isLightText = '';
  lightValue = Math.random();
  villageVolunteerId = null as number|null;
  villageId !:number;
  claimReason = '';
  /** 状态: 0=完善中, 1=已归档 */
  status = '';
  statusText = '';
  createdAt = null as Date|null;
  updatedAt = null as Date|null;
  deleteAt = null as Date|null;
  /** 录入时间 */
  enterAt = null as Date|null;
  /** 封面图 */
  image = '';
  thumbnail = '';
  /** 村落形象照片 */
  images = [] as string[];
  /** 村落名称 */
  name = '';
  title = '';
  /** 排名 */
  rank = 0;
  /** 乡源人数 */
  volunteerCount = 0;
  /** 关注人数 */
  followCount = 0;
  /** 采集投稿数 */
  collectCount = 0;
  /** 积分 */
  points = 0;
  /** 可用乡源光 */
  light = 0;
  /** 累计乡源光 */
  lightTotal = 0;
  /** 可产果数 */
  fruitOutput = 0;
  /** 可拾取果数 */
  fruitRemain = 0;
  /** 今日产果数 */
  fruitToday = 0;
  /** 等级 */
  level = 0;
  /** 权重 */
  weight = 0;
  volunteerName = '';
  /** 经度 */
  longitude = 0;
  /** 纬度 */
  latitude = 0;
  /** 村落类型 */
  villageType = 0;
  /** 海拔（米） */
  altitude = null as number|null;
  /** 地形地貌特征（多选） */
  landforms = '' as string|null;
  /** 村落形成年代 */
  age = null as number|null;
  /** 村域面积（平方公里） */
  area = null as number|null;
  /** 村庄占地面积（亩） */
  villageArea = null as number|null;
  /** 传统建筑数量 */
  traditionalBuildings = null as number|null;
  /** 非遗最高级别 */
  ichLevel = null as number|null;
  /** 列入历史文化名村级别 */
  historyLevel = null as number|null;
  /** 列入特色景观旅游名村级别 */
  touristLevel = null as number|null;
  /** 列入少数民族特色村寨试点示范: 0=否, 1=是 */
  isFeaturedVillage = 0;
  /** 其他认定级别 */
  other = '' as string|null;
  /** 主要民族 */
  nationlity = '' as string|null;
  /** 户籍人口年份 */
  registeredPopulationYear = null as number|null;
  /** 户籍人口 */
  registeredPopulation = null as number|null;
  /** 常住人口年份 */
  permanentPopulationYear = null as number|null;
  /** 常住人口 */
  permanentPopulation = null as number|null;
  /** 人均年收入年份 */
  personalAnnualIncomeYear = null as number|null;
  /** 人均年收入（万元） */
  personalAnnualIncome = '' as string|null;
  /** 集体年收入年份 */
  villageAnnualIncomeYear = null as number|null;
  /** 集体年收入（万元） */
  villageAnnualIncome = '' as string|null;
  /** 突出价值 */
  prominent = '' as string|null;
  /** 主要产业_农业 */
  agriculture = '' as string|null;
  /** 主要产业_其他农业 */
  otherAgriculture = '' as string|null;
  /** 主要产业_林业 */
  forestry = '' as string|null;
  /** 主要产业_畜牧业 */
  animal = '' as string|null;
  /** 主要产业_渔业 */
  fishing = '' as string|null;
  /** 主要产业_制造业（含手工） */
  manufacturing = '' as string|null;
  /** 主要产业_建筑业 */
  construction = '' as string|null;
  /** 主要产业_批发和零售业 */
  retail = '' as string|null;
  /** 主要产业_服务业 */
  service = '' as string|null;
  /** 主要产业_其他服务业 */
  otherService = '' as string|null;
  /** 主要产业_其他 */
  otherIndustries = '' as string|null;
  /** 来源 */
  source = '' as string|null;
  /** 图片说明 */
  imageDesc = '' as string|null;
  /** 组图描述 */
  imagesDesc = [] as string[];
  /** 音频 */
  audio = '' as string|null;
  /** 视频 */
  video = '' as string|null;
  /** 数字档案 */
  archives = '' as string|null;
  /** 其他附件 */
  annex = '' as string|null;
  /** 标志 */
  flag = '';
  /** 关键字 */
  keywords = '';
  /** 联系人 */
  contact = '' as string|null;
  /** 联系电话 */
  mobile = '' as string|null;
  /** 跳转链接 */
  url = '' as string|null;
  /** VIP等级 */
  vipLevel = 0;
  /** 概况最新ID */
  overviewId = null as number|null;
  /** 当前志愿者概况ID */
  myOverviewId = null as number|null;
  /** 当前等级树名称 */
  treeName = '';
  /** 当前等级树图片 */
  treeImage = '';
  /** 当前等级所需乡源光 */
  treeLight = 0;
  /** 下一级等级树名称 */
  nextTreeName = '';
  /** 下一级所需乡源光 */
  nextTreeLight = 0;
  /** 下一级 */
  nextTreeLevel = 0;
  /** 图片上传最大数量限制 */
  imageLimit = 0;
  /** 存储内存限制(MB) */
  storageLimit = 0;
  /** 可设置管理人员数量 */
  managerLimit = 0;
}

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(data: {
    level?: number, 
    region?: number, 
    status?: number, 
    page?: number, 
    pageSize?: number,
    keyword?: string,
  }) {
    const res = await this.get<{
      data: any[],
      total: number,
    }>('/village/village/list', '乡源村落列表', {
      history_level: data.level,
      status: data.status,
      region: data.region,
      page: data.page,
      pageSize: data.pageSize,
      keyword: data.keyword,
    });
    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();
