import { CONVERTER_ADD_DEFAULT, DataModel, transformArrayDataModel } from '@imengyu/js-request-transform';
import { AppServerRequestModule } from '../RequestModules';
import { findAProp, 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 },
    }
    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 = null as number|null;
  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' },
      birthday: { clientSide: 'date', serverSide: 'undefined' },
    }
  }

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

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 },
    }
    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' },
        ]);
      }
    }
    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 = '';
  villageName = '';
  spacer = '';
  haschild = false;
  typeId = -1;
}

export class VillageApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  async getClaimedVallageList(volunteerId?: string) {
    return (this.get('/village/village/getVillageList', '获取已认领村落', {
      village_volunteer_id: volunteerId,
    })) 
      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
      .catch(e => { throw e });
  }
  async getCanClaimVallageList() {
    return (this.get('/village/village/getClaimList', '可认领村落列表', {
      main_body_id: 2,
    })) 
      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
      .catch(e => { throw e });
  }
  async claimVallage(data: any) {
    return (this.post('/village/village/addVillageClaim', {
      ...data
    }, '认领村落')) ;
  }
  async getVallageList(level?: number, status?: number) {
    return (this.get('/village/village/getList', '村落列表', {
      history_level: level,
      status,
    })) 
      .then(res => transformArrayDataModel<VillageListItem>(VillageListItem, transformSomeToArray(res.data2), `村落`, true))
      .catch(e => { throw e });
  }
  async getVolunteerInfo() {
    return (await this.post('/village/volunteer/getInfo', {
    }, '获取志愿者信息', undefined, VolunteerInfo)).data as VolunteerInfo
  }
  async getVolunteerRanklist(category?: number) {
    return (this.post('/village/volunteer/getRanklist', {
      category,
    }, '志愿者排行榜')) 
      .then(res => transformArrayDataModel<VolunteerRanklistItem>(VolunteerRanklistItem, res.data2, ``, true))
      .catch(e => { throw e });
  }
  
  async addVolunteer(data: VolunteerInfo) {
    return (this.post('/village/volunteer/add', data.toServerSide(), '添加志愿者')) ;
  }
  async updateVolunteer(data: VolunteerInfo) {
    return (this.post('/village/volunteer/update', data.toServerSide(), '更新志愿者')) ;
  }
  async getVolunteerInfoById(id: number) {
    return (await this.post('/village/volunteer/getInfo', {
    }, '获取志愿者信息', undefined, VolunteerInfo)).data as VolunteerInfo
  }
  async getVillageVolunteerList(villageId?: number) {
    return (this.post('/village/volunteer/getList', {
      village_id: villageId,
    }, '获取志愿者列表')) 
      .then(res => transformArrayDataModel<VolunteerInfo>(VolunteerInfo, res.data2 || [], ``, true))
      .catch(e => { throw e });
  }
  async getCollectModuleList() {
    return (this.get('/village/volunteer/getCollectModuleList', '获取采集版块列表', {
    })) 
      .then(res => {
        const result = [] as {
          value: string,
          label: string,
        }[];
        for (const key in res.data2) {
          result.push({
            value: key,
            label: res.data2[key],
          })
        }
        return result;
      })
      .catch(e => { throw e });
  }

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

  async getCatalogList(villageId?: number, pid?: number) {
    return (this.get('/village/village/getCatalogList', '村落目录列表', {
      village_id: villageId,
      pid: pid === 0 ? undefined : pid,
    })) 
      .then(res => transformArrayDataModel<VillageCatalogListItem>(VillageCatalogListItem, res.data2, `村落目录列表`, true))
      .catch(e => { throw e });
  }
  async getVillageMenuList(id: number) {
    return (this.get('/village/menu/getList', '村落菜单列表', {
      village_id: id,
    })) 
      .then(res => transformArrayDataModel<VillageMenuListItem>(VillageMenuListItem, res.data2, `村落菜单`, true))
      .catch(e => { throw e });
  }

}

export default new VillageApi();
