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

export class CategoryListItem extends DataModel<CategoryListItem> {
  constructor() {
    super(CategoryListItem, "分类列表");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      pid: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      haschild: { clientSide: 'boolean', serverSide: 'number' },
    }
  }

  id !: number;
  pid !: number;
  title = '';
  status = 'normal';
  weight = 0;
  spacer = '';
  haschild = false;
  children?: CategoryListItem[];
}
export class CommonInfoModel extends DataModel<CommonInfoModel> {
  constructor() {
    super(CommonInfoModel, "信息详情");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },

    },
    this._afterSolveServer = () => {
      if (this.province && this.city && this.district) {
        this.cityAddress = [this.province as string, this.city as string, this.district as string];
      }
    };
    this._afterSolveClient = (data) => {
      if (this.cityAddress) {
        data.province = this.cityAddress[0];
        data.city = this.cityAddress[1];
        data.district = this.cityAddress[2];
      }
    };
  }
  id !: number;
  cityAddress?: string[];

}

export class VillageEnvInfo extends DataModel<VillageEnvInfo> {
  constructor() {
    super(VillageEnvInfo, "地理信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      landforms: [
        { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
        { clientSide: 'arrayInt', serverSide: 'original' },
      ],
    },
    this._afterSolveServer = () => {
      if (this.longitude && this.latitude) {
        this.lonlat = [this.longitude as number, this.latitude as number];
      }
    };
    this._afterSolveClient = (data) => {
      if (this.lonlat) {
        data.longitude = this.lonlat[0];
        data.latitude = this.lonlat[1];
      }
    };
  }
  id !: number;
  lonlat?: number[];
  landforms = [] as string[];
}
export class VillageListItem extends DataModel<VillageListItem> {
  constructor() {
    super(VillageListItem, "村庄信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
    },
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('At'))
        return {
          clientSide: 'date',
          serverSide: 'string',
        };
      return undefined;
    };
    this._afterSolveServer = () => {
      if (!this.title) {
        if (this.name) this.title = this.name as string;
        if (typeof this.content === 'object' && (this.content as any)?.title) this.title = (this.content as any).title as string;
        if (this.content) this.title = this.content as string;
        if (this.structure) this.title = this.structure as string;
        if (this.wisdom) this.title = this.wisdom as string;
      }
      if (!this.image) {
        if (this.distribution) this.image = this.distribution as string;
      }
    };
  }
  id !: number;
  createdAt = new Date();
  updatedAt = new Date();
  title = '';
  image = '';
}
export class VillageBulidingInfo extends DataModel<VillageBulidingInfo> {
  constructor() {
    super(VillageBulidingInfo, "历史建筑信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
    }
    const commaArrayKeys = [
      'purpose','floorType','wallType','roofForm','bearingType',
    ]
    this._convertKeyType = (key, direction) => {
      if (commaArrayKeys.includes(key))
        return [
          { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
          { clientSide: 'arrayInt', serverSide: 'original' },
        ];
      return undefined;
    };
  }
  id !: number;
}

export class VillageInfoApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  /**
   * 获取分类列表
   * @param type 根级类型：1=区域、2=级别、3=文物类型、4=非遗类型、42=事件类型
   * @param withself 是否返回包含自己：true=是，false=否 ，默认false
   * @returns 
   */
  async getCategoryList(
    type?: number,
    withself?: boolean,
  ) {
    return (this.get('/village/village/getVillageList', '获取分类列表', {
      type,
      is_tree: false,
      withself,
    }))
      .then(res => transformArrayDataModel<CategoryListItem>(CategoryListItem, res.data2, `获取分类列表`, true))
      .catch(e => { throw e });
  }
  /**
   * 用于获取某一个分类需要用的子级
   * @param pid 父级
   * @returns 
   */
  async getCategoryChildList(pid?: number) {
    return (this.get('/content/category/getCategoryOnlyChildList', '获取分类子级列表', {
      pid,
    }))
      .then(res => transformArrayDataModel<CategoryListItem>(
        CategoryListItem, 
        transformSomeToArray(res.data2), 
        `获取分类列表`, 
        true
      ))
      .catch(e => { throw e });
  }

  async getInfo<T extends DataModel>(
    sub: string,
    subId: number,
    villageId: number,
    villageVolunteerId: number,
    id?: number,
    modelClassCreator: (new () => T) = CommonInfoModel as any
  ) {
    return (await this.post(`/village/${sub}/getInfo`, {
      type: subId,
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
      id,
    }, '获取信息详情', undefined, modelClassCreator)).data as T
  }
  async getList<T extends DataModel = VillageListItem>(
    sub: string,
    subId: number|undefined,
    subKey: string|undefined,
    villageId: number,
    villageVolunteerId: number,
    modelClassCreator: (new () => T) = VillageListItem as any 
  ) {
    return (this.post(`/village/${sub}/getList`, {
      [subKey ? subKey : 'type']: subId,
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
    }, '获取信息详情'))
      .then(res => transformArrayDataModel<T>(modelClassCreator, res.data2, `获取分类列表`, true))
      .catch(e => { throw e });
  }
  async updateInfo<T extends DataModel>(
    sub: string,
    villageId: number,
    villageVolunteerId: number,
    data: T,
  ) {
    return (await this.post(`/village/${sub}/save`, {
      sub,
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
      ...data.toServerSide(),
    }, '更新信息详情'));
  }
}

export default new VillageInfoApi();
