import { DataModel, transformArrayDataModel, transformDataModel } from '@imengyu/js-request-transform';
import { AppServerRequestModule } from '../RequestModules';
import dayjs from 'dayjs';
import { transformSomeToArray } from '../Utils';
import { GetContentListItem } from '../CommonContent';
import AppCofig from '@/common/config/AppCofig';

export class CommonInfo<T extends DataModel> extends DataModel<T> {

  constructor(classCreator?: (new () => T) | undefined, name: string = '基础信息') {
    super(classCreator, name);
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number', clientSideRequired: true },
      flag: { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
      type: { clientSide: 'number', serverSide: 'number' },
      keywords: { clientSide: 'splitCommaArray', serverSide: 'commaArrayMerge' },
      images: { clientSide: 'array', serverSide: 'array' },
      expandInfo: { serverSide: 'undefined' },
      region: { clientSide: 'number', serverSide: 'number' },
      progress: { clientSide: 'number', serverSide: 'number' },
      longitude: { clientSide: 'number', serverSide: 'number' },
      latitude: { clientSide: 'number', serverSide: 'number' },
    };
    this._beforeSolveClient = (data) => {
      if (!data.contentId && data.id)
        data.contentId = data.id;
    }
  }

  contentId = null as number|null;
  collectId = null as number|null;
  
  title = '' as string;
  region = null as number|null;
  image = null as string|null;
  imageDesc = '' as string|null;
  images = [] as string[];
  audio = '' as string|null;
  video = '' as string|null;
  flag = [] as string[];
  keywords = [] as string[];
  tags = '' as string;
  associationId = 0 as number;
  pid = 0 as number;
  content = '' as string|null;
}

export class IchInfo extends CommonInfo<IchInfo> {
  constructor() {
    super(IchInfo, "非遗项目信息");
    this._convertTable = {
      ...this._convertTable,
      lonlat: { serverSide: 'undefined' },
      batch: { clientSide: 'number', serverSide: 'string' },
      typicalImages: [
        { 
          clientSide: 'object', 
          clientSideChildDataModel: {
            convertTable: {},
          }, 
          serverSide: 'string' 
        },
        {
          clientSide: 'addDefaultValue',
          clientSideParam: {
            defaultValue: [],
          }
        },
      ],
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
      self.lonlat = [ self.longitude, self.latitude ];
      if (!self.intro && self.description)
        self.intro = self.description;
    };
    this._afterSolveClient = (data) => {
      data.longitude = this.lonlat[0];
      data.latitude = this.lonlat[1];
    };

    const _superBeforeSolveClient = this._beforeSolveClient;
    this._beforeSolveClient = (data) => {
      _superBeforeSolveClient?.(data);
      if (!this.expandInfo)
        this.expandInfo = new IchExpandInfo();
      this.expandInfo.batch = this.batch;
      this.expandInfo.region = this.region;
      this.expandInfo.image = this.image;
      this.expandInfo.level = this.level!;
      this.expandInfo.ichType = this.ichType!;
      this.expandInfo.contentId = this.contentId!;
      this.expandInfo.collectId = this.collectId!;

    };
  }

  lonlat = [] as (number|string)[];
  expandInfo : IchExpandInfo|null = new IchExpandInfo();

  id = 0 as number;
  modelId = 2;
  mainBodyColumnId = 0 as number;
  ztImage = '' as string|null;
  intro = '' as string;
  description = '' as string;
  heritage = null as number|null;
  level = null as number|null;
  ichType = null as number|null;
  batch = '' as string;
  longitude = '' as string;
  latitude = '' as string;
  mapX = '' as string|null;
  mapY = '' as string|null;
  unit = '' as string;
  address = '' as string|null;
  declarationRegion = '' as string;
  popularRegion = '' as string;
  approveTime = '' as string;
  typicalImages = [] as {
    form: string,
    mobile: string,
    desc: string,
    url: string,
  }[];
  thumbnail = '' as string;
  flagText = '' as string;
  typeText = '' as string;
  openStatusText = '' as string;
  statusText = '' as string;
  regionText = '' as string;
  levelText = '' as string;
  crTypeText = '' as string;
  ichTypeText = '' as string;
  claimStatusText = '' as string;
  isMultipleClaimsText = '' as string;
  batchText = '' as string;
  ichSiteTypeText = '' as string;

}
export class IchExpandInfo extends DataModel<IchExpandInfo> {
  constructor() {
    super(IchExpandInfo, "非遗项目信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      protectLevel: { clientSide: 'number', serverSide: 'string' },
      id: { clientSide: 'number', serverSide: 'undefined' },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
      if (key.endsWith('At')) {
        return {
          clientSide: 'date',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
    };
    this._afterSolveClient = (data) => {
    };
  }

  id = 0 as number;
  modelId = 2;
  userId = 0 as number;
  reviewId = 0 as number;
  originId = '' as string|null;
  contentId = 0 as number;
  name = '' as string;
  level = 0 as number;
  ichType = 0 as number;
  protectLevel = null as number|null;
  image = '' as string|null;
  images = [] as string[];
  otherNames = '' as string|null;
  history = false;
  existence = false;
  folkCulture = '' as string|null;
  culturalRelic = '' as string|null;
  description = '' as string|null;
  desc = '' as string;
  mapX = '' as string|null;
  mapY = '' as string|null;
  declarationRegion = '' as string|null;
  popularRegion = '' as string|null;
  createdAt = '' as string;
  updatedAt = '' as string;
  deletedAt = '' as string|null;
  progress = 0 as number;
  comment = '' as string;
  levelText = '' as string;
  ichTypeText = '' as string;
  protectLevelText = '' as string;
  progressText = '' as string;
}
export class InheritorInfo extends CommonInfo<InheritorInfo> {
  constructor() {
    super(InheritorInfo, "传承人信息");
    this._convertTable = {
      ...this._convertTable,
      gender: { clientSide: 'number', serverSide: 'string' },
      level: { clientSide: 'number', serverSide: 'string' },
      batch: { clientSide: 'number', serverSide: 'string' },
      typicalImages: [
        { 
          clientSide: 'object', 
          clientSideChildDataModel: {
            convertTable: {},
          }, 
          serverSide: 'string' 
        },
        {
          clientSide: 'addDefaultValue',
          clientSideParam: {
            defaultValue: [],
          },
          serverSide: 'original',
        },
      ],
      works: {
        clientSide: 'array',
        clientSideChildDataModel: InheritorWorkInfo,
        serverSide: 'array' 
      },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
  }

  expandInfo : InheritorExpandInfo|null = new InheritorExpandInfo();

  id = 0 as number;
  modelId = 7;
  mainBodyColumnId = 0 as number;
  alsoName = '' as string|null;
  nation = '' as string;
  dateBirth = '' as string;
  deathBirth = '' as string|null;
  unit = '' as string;
  content = '' as string|null;
  intro = '' as string;
  prize = '' as string;
  level = null as number|null;
  gender = 0 as number;
  batch = '' as string|null;
  typicalImages = [] as string[];
  progress = 0 as number;
  contentId = 0 as number;
  thumbnail = '' as string;
  flagText = '' as string;
  typeText = '' as string;
  openStatusText = '' as string;
  statusText = '' as string;
  regionText = '' as string;
  levelText = '' as string;
  crTypeText = '' as string;
  ichTypeText = '' as string;
  claimStatusText = '' as string;
  isMultipleClaimsText = '' as string;
  batchText = '' as string;
  ichSiteTypeText = '' as string;
  progressText = '' as string;
  works = [] as InheritorWorkInfo[];
}
export class InheritorExpandInfo extends DataModel<InheritorExpandInfo> {
  constructor() {
    super(InheritorExpandInfo, "非遗项目信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      gender: { clientSide: 'number', serverSide: 'string' },
      level: { clientSide: 'number', serverSide: 'string' },
      batch: { clientSide: 'number', serverSide: 'string' },
      photosJson: [
        { 
          clientSide: 'object', 
          clientSideChildDataModel: {
            convertTable: {},
          }, 
          serverSide: 'string' 
        },
        {
          clientSide: 'addDefaultValue',
          clientSideParam: {
            defaultValue: [],
          }
        },
      ],
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
    };
    this._afterSolveClient = (data) => {
    };
  }
  modelId = 7;
}
export class InheritorWorkInfo extends DataModel<InheritorWorkInfo> {
  constructor() {
    super(InheritorWorkInfo, "传承人作品");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      collectionTime: { clientSide: 'dayjs', serverSide: 'string' },
      type: { clientSide: 'number', serverSide: 'number' },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
      if (key.endsWith('At')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
    };
    this._afterSolveClient = (data) => {
    };
  }

  id = 0;
  modelId = 16;
  category = '';
  feature = '';
  otherName = '';
  creator = '';
  language = '';
  overview = '';
  ethnicGroup = '';
  creationEra = '';
  mainPerformer = '';
  otherPerformers = '';
  fullString = '';
  tune = '';
  development = '';
  spread = '';
  influence = '';
  collector = '';
  collectionTime = dayjs();
  collectionLocation = '';
}
export class SeminarInfo extends CommonInfo<SeminarInfo> {
  constructor() {
    super(SeminarInfo, "传习所信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      ...this._convertTable,
      lonlat: { serverSide: 'undefined' },
      visit: { clientSide: 'number' },
      ichSiteType: { clientSide: 'number', serverSide: 'number' },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
      self.lonlat = [ self.longitude, self.latitude ];
    };
    this._afterSolveClient = (data) => {
      data.longitude = this.lonlat[0];
      data.latitude = this.lonlat[1];
    };
  }

  lonlat = [] as (number|string)[];
  expandInfo : SeminarExpandInfo|null = new SeminarExpandInfo();

  id = 0 as number;
  modelId = 17;
  mainBodyColumnId = 0 as number;
  content = '' as string|null;
  mapX = '' as string|null;
  mapY = '' as string|null;
  longitude = '' as string|null;
  latitude = '' as string|null;
  address = '' as string;

  featuresType = null as number|null;
  contact = '' as string;
  ichSiteType = '' as string;
  flagText = '' as string;
  typeText = '' as string;
  openStatusText = '' as string;
  statusText = '' as string;
  regionText = '' as string;
  levelText = '' as string;
  crTypeText = '' as string;
  ichTypeText = '' as string;
  claimStatusText = '' as string;
  isMultipleClaimsText = '' as string;
  batchText = '' as string;
  ichSiteTypeText = '' as string;
}
export class SeminarExpandInfo extends DataModel<SeminarExpandInfo> {
  constructor() {
    super(SeminarExpandInfo, "非遗项目信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      lonlat: { serverSide: 'undefined' },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
      self.lonlat = [ self.longitude, self.latitude ];
    };
    this._afterSolveClient = (data) => {
      data.longitude = this.lonlat[0];
      data.latitude = this.lonlat[1];
    };
  }
  modelId = 17;
  lonlat = [] as (number|string)[];
}
export class PlanInfo extends DataModel<PlanInfo> {
  constructor() {
    super(PlanInfo, "五年计划");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      progress: { clientSide: 'number', serverSide: 'undefined' },
    };
    this._convertKeyType = (key, direction) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return {
          clientSide: 'string',
          serverSide: 'undefined',
        };
      }
    };
    this._afterSolveServer = (self) => {
    };
    this._afterSolveClient = (data) => {
    };
  }

  id = 0 as number;
  ichId = 0 as number;
  name = '' as string;
  investment = 0 as number;
  desc = '' as string;
  target = '' as string;
  unit = 0 as number;
  department = 0 as number;
  userId = 0 as number;
  progress = 0 as number;
  createdAt = '' as string;
  updatedAt = '' as string;
  ichName = '' as string;
  progressText = '' as string;
}
export class InheritorAccountInfo extends DataModel<InheritorAccountInfo> {
  constructor() {
    super(InheritorAccountInfo, "传承人账号信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      username: { clientSide: 'string', clientSideRequired: true },
      password: { clientSide: 'string', clientSideRequired: true },
    };
  }

  id = 0 as number;
  username = '' as string;
  password = '' as string;
  nickname = '' as string;
}
export class InheritorSubmitInfo extends DataModel<InheritorSubmitInfo> {
  constructor() {
    super(InheritorSubmitInfo, "传承人采集数据信息");
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      progress: { clientSide: 'number', serverSide: 'undefined' },
    };
  }

  id = 0 as number;
  title = '' as string;
  userId = 0 as number;
  nickname = '' as string;
  logintime = '' as string;
  updatedAt = '' as string;
  collectTotal = 0 as number;
  progress = 0 as number;
}

export class InheritorContentApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  async getBaseInfo<T extends DataModel>(id: number|undefined, newDataModel: new () => T, contentId?: number) {
    return (await this.post('/ich/inheritor/baseInfo', '基础表信息', {
      model_id: new newDataModel().modelId,
      id,
      content_id: contentId,
    }, undefined, newDataModel)).data as T;
  }
  /**
   * 项目五年计划
   * @param ichId 项目ID：传承人只返回绑定项目的计划
   * @param progress 审核进度：-1=不通过，0=待审核，1=已通过
   * @returns 
   */
  async getPlanList(ichId: number, progress?: number) {
    return transformArrayDataModel<PlanInfo>(
      PlanInfo,
      (await this.post('/ich/inheritor/plans', '获取计划列表', {
        ich_id: ichId,
        progress,
      })).data2.data,
      "data2"
    );
  }
  async saveBaseInfo<T extends DataModel>(dataModel: T) {
    return (await this.post('/ich/inheritor/saveBase', '基础内容表采集（非遗，传承人，传习所）', dataModel.toServerSide()));
  }
  async getExpandInfo<T extends DataModel>(id: number|undefined, newDataModel: new () => T) : Promise<T | null> {
    return this.post('/ich/inheritor/expandInfo', '扩展表信息', {
      model_id: new newDataModel().modelId,
      id,
    }, undefined).then((res) => {
      if (!res.data2) 
        return null;
      return transformDataModel(newDataModel, res.data2) as T;
    })
  }
  async saveExpandInfo<T extends DataModel>(dataModel: T) {
    return (await this.post('/ich/inheritor/saveExpand', '扩展内容表采集（非遗，传承人，传习所）', dataModel.toServerSide()));
  }
  async saveWorkInfo(dataModel: InheritorWorkInfo) {
    return (await this.post('/ich/inheritor/saveWork', '保存传承人作品信息', {
      ...dataModel.toServerSide(),
    }));
  }
  async savePlanInfo(dataModel: PlanInfo) {
    return (await this.post('/ich/inheritor/savePlans', '保存项目五年计划', dataModel.toServerSide()));
  }

  async getCollectListInfo<T extends DataModel>(dataModel: new () => T, id: number) {
    return this.post('/ich/inheritor/collectInfo', '获取采集记录详情', {
      model_id: new dataModel().modelId,
      id,
    }, undefined).then((res) => {
      return transformDataModel(dataModel, res.data2);
    })
  }
  /**
   * 获取采集列表
   * @param data 
   * @returns 
   */
  async getCollectList<T extends DataModel>(dataModel: new () => T, data: {
    /**
     * 采集类型
     * * content 基础
     * * ich 扩展
     */
    collectType: 'content'|'ich',
    /**
     * 提交用户ID
     */
    userId?: number,
    /**
     * 进度:-1=审核失败,0=待审核,1=审核通过
     */
    progress?: number,
    /**
     * 审核人用户ID
     */
    reviewId?: number,
    /**
     * 原基础表记录ID
     */
    contentId?: number,
    page?: number,
    pageSize?: number,
  }) {
    return this.post('/ich/inheritor/collectList', '获取采集列表', {
      collect_type: data.collectType,
      model_id: new dataModel().modelId,
      user_id: data.userId,
      progress: data.progress,
      review_id: data.reviewId,
      content_id: data.contentId,
      page: data.page,
      pageSize: data.pageSize,
    }, undefined).then((res) => {
      return {
        data: transformArrayDataModel<T>(dataModel, transformSomeToArray(res.data2.data), 'data2'),
        total: res.data2.total,
      }
    })
  }

  async getInheritorAccountInfo(contentId: number) {
    return this.post('/ich/inheritor/getAccount', '获取传承人账号信息', {
      content_id: contentId,
    }, undefined).then((res) => {
      const arr = transformSomeToArray(res.data2);
      if (arr.length === 0)
        return null;
      return transformDataModel(InheritorAccountInfo, arr[0]);
    })
  }
  async getInheritorSubmtList(modelId: number) {
    return this.post('/ich/inheritor/list', '获取传承人采集数据列表', {
      model_id: modelId
    }, undefined).then((res) => {
      return transformArrayDataModel<InheritorSubmitInfo>(InheritorSubmitInfo, transformSomeToArray(res.data2), 'data2');
    })
  }  

  async getIchSeminarInfo(data: {
    ichId?: number,
    page?: number,
    pageSize?: number,
    keywords?: string,
  }) {
    return this.post('/ich/inheritor/sites', '获取传习所列表', {
      ich_id: data.ichId,
      page: data.page,
      pageSize: data.pageSize,
      keywords: data.keywords,
    }, undefined).then((res) => {
      return transformArrayDataModel<SeminarInfo>(SeminarInfo, transformSomeToArray(res.data2), 'data2');
    })
  }
  async getIchWorksInfo(data: {
    ichId: number,
    page?: number,
    pageSize?: number,
  }) {
    return this.post('/ich/inheritor/works', '获取项目作品列表', {
      ich_id: data.ichId,
      page: data.page,
      pageSize: data.pageSize,
    }, undefined).then((res) => {
      return transformArrayDataModel<InheritorWorkInfo>(InheritorWorkInfo, res.data2.data, 'data2');
    })
  }
  async getIchWorksDetail(id: number) {
    return this.post('/ich/inheritor/info', '获取项目作品详情', {
      id,
      model_id: 16,
    }, undefined).then((res) => {
      return transformDataModel<InheritorWorkInfo>(InheritorWorkInfo, res.data2);
    })
  }

  async getIchInfo(id: number|undefined) {
    return await this.getBaseInfo(id, IchInfo);
  }
  async getInheritorInfo(id: number|undefined) {
    return await this.getBaseInfo(id, InheritorInfo);
  }
  async getSeminarInfo(id: number|undefined) {
    return await this.getBaseInfo(undefined, SeminarInfo, id);
  }
  async getIchExpandInfo(id: number|undefined) {
    return await this.getExpandInfo(id, IchExpandInfo);
  }
  async getInheritorExpandInfo(id: number|undefined) {
    return await this.getExpandInfo(id, InheritorExpandInfo);
  }
  async getSeminarExpandInfo(id: number|undefined) {
    return await this.getExpandInfo(id, SeminarExpandInfo);
  }  
  async bindWechat(data: { code: string }) {
    return this.post('/village/volunteer/bindWechat', '绑定微信', {
      code: data.code,
      appid: AppCofig.appId
    });
  }
}

export default new InheritorContentApi();
