import { CONVERTER_ADD_DEFAULT, DataModel, transformArrayDataModel, transformDataModel, type KeyValue } from '@imengyu/js-request-transform';
import { AppServerRequestModule } from '../RequestModules';
import { findAProp, transformSomeToArray } from '../Utils';
import { LoginResult } from '../auth/UserApi';
import AppCofig from '@/common/config/AppCofig';

export class VillageListItem extends DataModel<VillageListItem> {
  constructor() {
    super(VillageListItem, "活动列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
    }
    this._nameMapperServer = {
      name: 'villageName',
    };
    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;
      this.title = this.villageName
    }

  }

  id !: number;
  province = '' as string|null;
  city = '' as string|null;
  district = '' as string|null;
  township = '' as string|null;
  address = '';
  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[];
  villageName = '';
  title = '';
  volunteerName = '';
}
export class VolunteerRanklistItem extends DataModel<VolunteerRanklistItem> {
  constructor() {
    super(VolunteerRanklistItem, "活动列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      points: [{ clientSide: 'number', serverSide: 'number' }, { clientSide: CONVERTER_ADD_DEFAULT, clientSideParam: { defaultValue: 0 } }],
      level: [{ clientSide: 'number', serverSide: 'number' }, { clientSide: CONVERTER_ADD_DEFAULT, clientSideParam: { defaultValue: 0 } }],
    }
  }

  id !: number;
  name = '';
  mobile = '';
  points = 0;
  level = 0;
  typeText = '';
  sexText = '';
  statusText = '';
  image = '';
}
export class VolunteerInfo extends DataModel<VolunteerInfo> {
  constructor() {
    super(VolunteerInfo, "活动列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      points: [{ clientSide: 'number', serverSide: 'number' }, { clientSide: CONVERTER_ADD_DEFAULT, clientSideParam: { defaultValue: 0 } }],
      level: [{ clientSide: 'number', serverSide: 'number' }, { clientSide: CONVERTER_ADD_DEFAULT, clientSideParam: { defaultValue: 0 } }],
      collectModule: [
        { clientSide: 'splitCommaArray',serverSide: 'commaArrayMerge' },
        { clientSide: 'array', clientSideChildDataModel: 'number', serverSide: 'original' },
      ],
      birthday: { clientSide: 'date', serverSide: 'undefined' },
      catalogIds: [
        { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
        { clientSide: 'array', clientSideChildDataModel: 'number', serverSide: 'original' },
      ],
    }
  }

  static STATUS_APPROVED = 1;
  static STATUS_PENDING = 0;
  static STATUS_REJECTED = -1;

  id !: number;
  mainBodyId !: number;
  type = '';
  name = '';
  sex = 0;
  mobile = '';
  regionId = null as number|null;
  address = '';
  image = '';
  birthday = new Date();
  points = 0;
  level = 0;
  status = '';
  createdAt = '';
  updatedAt = '';
  typeText = '';
  sexText = '';
  statusText = '';
  catalogIds = [] as number[];
  collectModule = [] as number[];
  collectModuleText = '';
}

export class VillageClaimInfo extends DataModel<VillageClaimInfo> {
  constructor() {
    super(VillageClaimInfo, '村落认领');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      villageId: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      sex: { clientSide: 'number', serverSide: 'number' },
    };
  }

  villageId = 0;
  name = '';
  type = 'villager';
  mobile = '';
  address = '';
  claimReason = '';
  job = '';
  unit = '';
  sex = 3;
}

export class VillageMenuListItem extends DataModel<VillageMenuListItem> {
  constructor() {
    super(VillageMenuListItem, "村落菜单列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
    }
    this._nameMapperServer = {
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('At'))
        return {
          clientSide: 'date',
          serverSide: 'string',
        };
      return undefined;
    };

  }
  name = '';
  logo = '';
}
export class VillageCatalogListItem extends DataModel<VillageCatalogListItem> {
  constructor() {
    super(VillageCatalogListItem, "村落目录列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      childlist: [
        { clientSide: 'array', clientSideChildDataModel: VillageCatalogListItem, serverSide: 'undefined' },
      ],
    }
    this._nameMapperServer = {
    };
    this._afterSolveServer = () => {
      this.haschild = (this.childlist as any[]).length > 0;
      if (this.otherParams) {
        this.typeId = findAProp(this.otherParams, [
          { type: 'endWith', name: 'type' },
          { type: 'match', name: 'nature' },
          { type: 'match', name: 'cultural' },
          { type: 'selectAtLestOne' },
        ]);
      }
    }
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('At'))
        return {
          clientSide: 'date',
          serverSide: 'string',
        };
      return undefined;
    };

  }
  id !: number;
  name = '';
  title = '';
  icon = '';
  desc = '';
  pid = 0;
  collectModuleId = 0;
  collectModuleName = '';
  childlist = [] as VillageCatalogListItem[];
  villageName = '';
  spacer = '';
  haschild = false;
  typeId = -1;
  total = -1;
}

export class VillageApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  async getClaimedVallageList(volunteerId?: string) {
    const res = await this.get('/village/village/getVillageList', '获取已认领村落', {
      village_volunteer_id: volunteerId,
    });
    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data), `村落`, true);
  }
  async getCanClaimVallageList() {
    const res = await this.get('/village/village/getClaimList', '可认领村落列表', {
      main_body_id: 2,
    });
    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data), `村落`, true);
  }
  async claimVallage(data: VillageClaimInfo) {
    return this.post('/village/village/addVillageClaim', '认领村落', data.toServerSide());
  }
  async getVallageList(level?: number, status?: number, region?: string) {
    const res = await this.get('/village/village/getList', '村落列表', {
      history_level: level,
      status,
      region: region,
    });
    return transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data), `村落`, true);
  }
  async getVolunteerInfo() {
    const res = await this.post<KeyValue>('/village/volunteer/getInfo', '获取志愿者信息', {}, undefined);
    return transformDataModel<VolunteerInfo>(VolunteerInfo, res.requireData());
  }
  async getVolunteerRanklist(category?: number) {
    const res = await this.post<any[]>('/village/volunteer/getRanklist', '志愿者排行榜', {
      category,
    });
    return transformArrayDataModel<VolunteerRanklistItem>(VolunteerRanklistItem, res.data ?? [], ``, true);
  }
  
  async addVolunteer(data: VolunteerInfo) {
    return this.post('/village/volunteer/add', '添加志愿者', data.toServerSide());
  }
  async updateVolunteer(data: VolunteerInfo) {
    console.log('updateVolunteer', data.toServerSide());
    return this.post('/village/volunteer/save', '更新志愿者', data.toServerSide());
  }
  async deleteVolunteer(id: number, villageId: number) {
    return this.post('/village/volunteer/del', '删除志愿者', {
      id,
      village_id: villageId,
    });
  }
  async shareAddVolunteer(data: VolunteerInfo) {
    const res = await this.post('/village/volunteer/shareAdd', '分享添加志愿者', data.toServerSide(), undefined, LoginResult);
    return res.data as LoginResult;
  }
  async bindVolunteer(data: {
    account: string,
    password: string
  }) {
    const res = await this.post('/village/volunteer/bindVolunteer', '绑定志愿者', data, undefined, LoginResult);
    return res.data as LoginResult;
  }
  async bindWechat(data: { code: string }) {
    return this.post('/village/volunteer/bindWechat', '绑定微信', {
      code: data.code,
      appid: AppCofig.appId
    });
  }

  async getVolunteerInfoByIdAdmin(id: number) {
    const res = await this.post('/village/volunteer/info', '管理员获取志愿者信息', {
      id,
    }, undefined, VolunteerInfo);
    return res.data as VolunteerInfo;
  }
  async getVolunteerInfoById(id: number) {
    const res = await this.post('/village/volunteer/getInfo', '通过ID获取志愿者信息', {
      id,
    }, undefined, VolunteerInfo);
    return res.data as VolunteerInfo;
  }
  async getVillageVolunteerList(villageId?: number, status?: number) {
    const res = await this.post('/village/volunteer/getList', '获取志愿者列表', {
      village_id: villageId,
      status,
    });
    return transformArrayDataModel<VolunteerInfo>(VolunteerInfo, res.data || [], ``, true);
  }
  async reviewVillageVolunteer(villageId: number, volunteerId: number, status: number) {
    return this.post('/village/village/claimReview', '审核志愿者', {
      village_id: villageId,
      village_volunteer_id: volunteerId,
      status,
    });
  }

  async getCollectModuleList() {
    const res = await this.get<KeyValue>('/village/volunteer/getCollectModuleList', '获取采集版块列表', {});
    const result = [] as {
      value: string,
      label: string,
    }[];
    const data = res.data ?? {};
    for (const key in data) {
      result.push({
        value: key,
        label: data[key] as string,
      });
    }
    return result;
  }

  async getCollectModuleMap() {
    const res = await this.post<any[]>('/village/volunteer/getCollectModuleList', '采集板块列表', {});
    const map = new Map<string, number>();
    if (!res.data || typeof res.data !== 'object') 
      return map;
    for (const key in res.data || []) {
      if (typeof res.data[key] !== 'string')
        throw new Error(`采集板块列表键值对值不是字符串: ${key} -> ${res.data[key]}`);
      if (isNaN(Number(key)))
        throw new Error(`采集板块列表键值对键不是数字: ${key}`);
      map.set(res.data[key], Number(key));
    }
    return map;
  }

  async getCatalogList(villageId?: number, volunteerId?: number, pid?: number) {
    const res = await this.get<any[]>('/village/village/getCatalogList', '村落目录列表', {
      village_id: villageId,
      village_volunteer_id: volunteerId,
      pid: pid === 0 ? undefined : pid,
    });
    return transformArrayDataModel<VillageCatalogListItem>(VillageCatalogListItem, res.data ?? [], `村落目录列表`, true);
  }
  async getVillageMenuList(id: number) {
    const res = await this.get<any[]>('/village/menu/getList', '村落菜单列表', {
      village_id: id,
    });
    return transformArrayDataModel<VillageMenuListItem>(VillageMenuListItem, res.data ?? [], `村落菜单`, true);
  }

}

export default new VillageApi();
