import { DataModel, transformArrayDataModel } from '@imengyu/js-request-transform';
import { AppServerRequestModule } from '../RequestModules';
import CommonContent from '../CommonContent';

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' },
      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 },
      keywords: { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
    },
    this._blackList.toServer.push(
      'updatedAt', 'createdAt', 'deletedAt',
    );
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('At'))
        return {
          clientSide: 'date',
          serverSide: 'string',
        };
      return undefined;
    };
    this._afterSolveServer = () => {
      if (this.province && this.city && this.district) {
        this.cityAddress = [this.province as string, this.city as string, this.district as string];
      }
      if (!this.title && this.name)
        this.title = this.name;
    };
    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[];
  title = '';
  desc = '';
  image = '';
  images = [] as string[];
  content = '';
  villageId = 0;
  villageVolunteerId = 0;
  villageName = '';
  villageVolunteerName = '';
  contentId = 0;
  name = '';
  type = 0;
  audio = '';
  video = '';
  archives = '';
  annex = [] as string[];
  keywords = [] as string[];
  createdAt = new Date();
  updatedAt = new Date();
  publishAt = new Date();
}

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' },
      ],
      villageType: { clientSide: 'number', serverSide: 'number' },
    },
    this._blackList.toServer.push(
      'updatedAt', 'createdAt', 'deletedAt',
    );
    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._blackList.toServer.push(
      'updatedAt', 'createdAt', 'deletedAt',
    );
    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 = '';
  desc = '';
  image = '';
}
export class VillageBulidingInfo extends DataModel<VillageBulidingInfo> {
  constructor() {
    super(VillageBulidingInfo, "历史建筑信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
    }
    this._blackList.toServer.push(
      'updatedAt', 'createdAt', 'deletedAt',
    );
    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 
   */
  getCategoryList(
    type?: number,
    withself?: boolean,
  ) {
    return CommonContent.getCategoryList(type, withself);
  }
  /**
   * 用于获取某一个分类需要用的子级
   * @param pid 父级
   * @returns 
   */
  getCategoryChildList(pid?: number) {
    return CommonContent.getCategoryChildList(pid);
  }

  async getInfo<T extends DataModel>(
    collectModuleId: number|undefined,
    subType: string,
    subId: number|undefined,
    subKey: string|undefined,
    villageId: number,
    villageVolunteerId: number,
    id?: number, 
    modelClassCreator: (new () => T) = CommonInfoModel as any
  ) {
    if (subType === 'overview') {
      return (await this.post(`/village/${subType}/getInfo`, {
        type: subId,
        village_id: villageId,
        village_volunteer_id: villageVolunteerId,
        id,
      }, '获取村落概况', undefined, modelClassCreator)).data as T
    } else {
      return (await this.post(`/village/collect/info`, {
        collect_module_id: collectModuleId,
        id,
      }, '通用获取信息详情', undefined, modelClassCreator)).data as T
    }
  }
  async getList<T extends DataModel = VillageListItem>(
    collectModuleId: number|undefined,
    subType: string,
    subId: number|undefined,
    subKey: string|undefined,
    villageId: number,
    villageVolunteerId: number,
    modelClassCreator: (new () => T) = VillageListItem as any 
  ) {
    return (this.post(`/village/collect/list`, {
      collect_module_id: collectModuleId,
      [subKey ? subKey : 'type']: subId,
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
    }, '获取信息详情'))
      .then(res => transformArrayDataModel<T>(modelClassCreator, (res.data2.data || res.data2) ?? [], `获取分类列表`, true))
      .catch(e => { throw e });
  }

  async getListForDiscover(page: number, pageSize: number, keywords?: string) {
    return (this.post(`/village/collect/list`, {
      page,
      page_size: pageSize,
      keywords,
      status: 4,
    }, '获取信息详情'))
      .then(res => ({
        total: res.data2.total as number,
        list: transformArrayDataModel<CommonInfoModel>(CommonInfoModel, (res.data2.data || res.data2) ?? [], `获取分类列表`, true)
      }))
      .catch(e => { throw e });
  }
  async getInfoForDiscover(id: number) {
    return (await this.post(`/village/collect/info`, {
      id,
      status: 4,
    }, '通用获取信息详情', undefined, CommonInfoModel)).data as CommonInfoModel
  }

  async updateInfo<T extends DataModel>(
    collectModuleId: number|undefined,
    subType: string,
    subKey: string,
    subId: number,
    villageId: number,
    villageVolunteerId: number,
    data: T,
  ) {
    if (subType === 'overview') {
      return (await this.post(`/village/${subType}/save`, {
        subType,
        village_id: villageId,
        village_volunteer_id: villageVolunteerId,
        ...data.toServerSide(),
      }, '更新信息详情'));
    } else {
      return (await this.post(`/village/collect/save`, {
        collect_module_id: collectModuleId,
        [subKey||'type']: subId,
        village_id: villageId,
        village_volunteer_id: villageVolunteerId,
        ...data.toServerSide(),
      }, '通用更新信息详情'));
    }
  }
}

export default new VillageInfoApi();
