import { DataModel, transformArrayDataModel, transformDataModel, type KeyValue } 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' },
      culturalType: { clientSide: 'number', serverSide: 'number' },
      productType: { clientSide: 'number', serverSide: 'number' },
      type: { clientSide: 'number', serverSide: 'number' },
      nature: { clientSide: 'number', serverSide: 'number' },
      folkCultureType: { clientSide: 'number', serverSide: 'number' },
      landforms: [
        { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
        { clientSide: 'arrayInt', serverSide: 'original' },
      ],
      villageType: { clientSide: 'number', serverSide: 'number' },
    },
    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;
      if (this.longitude && this.latitude) {
        this.lonlat = [this.longitude as number, this.latitude as number];
      }
    };
    this._afterSolveClient = (data) => {
      if (this.cityAddress) {
        data.province = this.cityAddress[0];
        data.city = this.cityAddress[1];
        data.district = this.cityAddress[2];
      }
      if (this.lonlat) {
        data.longitude = this.lonlat[0];
        data.latitude = this.lonlat[1];
      }
    };
  }

  /**
   * 审核不通过
   */
  static STATUS_REJECT = -1;
  /**
   * 草稿
   */
  static STATUS_DRAFT = 0;
  /**
   * 待审核
   */
  static STATUS_AUDIT = 1;
  /**
   * 审核通过
   */
  static STATUS_PASS = 2;
  /**
   * 专家评估
   */
  static STATUS_EXPERT = 3;
  /**
   * 终审
   */ 
  static STATUS_FINAL = 4;

  id !: number;
  cityAddress?: string[];
  title = '';
  desc = '';
  image = '';
  images = [] as string[];
  content = '';
  catalogId = 0;
  collectModuleId = 0;
  villageId = 0;
  villageVolunteerId = 0;
  villageName = '';
  villageVolunteerName = '';
  contentId = 0;
  name = '';
  type = 1;
  audio = '';
  video = '';
  archives = '';
  annex = [] as string[];
  keywords = [] as string[];
  createdAt = new Date();
  updatedAt = new Date();
  publishAt = new Date();
  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 pid 父级
   * @returns 
   */
  getCategoryChildList(pid?: number) {
    return CommonContent.getCategoryChildList(pid);
  }

  getOverview(
    villageId: number,
    villageVolunteerId: number,
  ) {
    return (this.post<KeyValue>(`/village/overview/getInfo`, '获取村社概览', {
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
    }))
      .then(res => transformDataModel(CommonInfoModel, res.requireData()))
      .catch(e => { throw e });
  }

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

  async getListForDiscover(page: number, pageSize: number, keywords?: string) {
    return (this.post<{
      total: number,
      data: any[],
    }>(`/village/collect/list`, '获取信息详情', {
      page,
      page_size: pageSize,
      keywords,
      status: 4,
    }))
      .then(res => ({
        total: res.data?.total as number ?? 0,
        list: transformArrayDataModel<CommonInfoModel>(CommonInfoModel, res.data?.data ?? [], `获取分类列表`, 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 deleteInfo(id: number) {
    return (await this.post(`/village/collect/del`, '删除信息详情', {
      id,
    }, undefined, CommonInfoModel)).data as CommonInfoModel
  }
  async updateInfo<T extends DataModel>(
    collectModuleId: number|undefined,
    subType: string,
    subKey: string,
    subId: number,
    villageId: number,
    villageVolunteerId: number,
    catalogId: number|undefined,
    data: T,
  ) {
    const res : Record<string, any> = {
      ...data.toServerSide(),
      collect_module_id: collectModuleId,
      village_id: villageId,
      village_volunteer_id: villageVolunteerId,
      catalog_id: catalogId,
    };
    if (subKey)
      res[subKey] = subId;
    return (await this.post(`/village/collect/save`, '通用更新信息详情', res));
  }
}

export default new VillageInfoApi();
