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

/**
 * 自查评估 / 传承协议相关接口（ShowDoc）
 * @see https://www.showdoc.com.cn/minnanCE/11559060626966335 列表
 * @see https://www.showdoc.com.cn/minnanCE/11559060626887140 传承协议编辑
 * @see https://www.showdoc.com.cn/minnanCE/11559060626966336 评估表编辑/新增
 * @see https://www.showdoc.com.cn/minnanCE/11559060626966337 详情
 */

/** 计分点项（getCheckItems） */
export class CheckItemInfo extends DataModel<CheckItemInfo> {
  constructor() {
    super(CheckItemInfo, '自查计分项目');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      pid: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'number' },
      points: { clientSide: 'number', serverSide: 'number' },
      isTitle: { clientSide: 'boolean', serverSide: 'number' },
      isMulitCheck: { clientSide: 'boolean', serverSide: 'number' },
    };
  }

  id = 0 as number;
  pid = 0 as number;
  name = '' as string;
  level = 0 as number;
  points = 0 as number;
  isTitle = false;
  isMulitCheck = false;
  /** 1=单选,2=多选,3=次数 */
  checkType = 0 as number;
  children: CheckItemInfo[] = [];
}

/** 自查评估表列表行 */
export class SelfAssessmentListRow extends DataModel<SelfAssessmentListRow> {
  constructor() {
    super(SelfAssessmentListRow, '自查评估表列表项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      userId: { clientSide: 'number', serverSide: 'number' },
      year: { clientSide: 'number', serverSide: 'number' },
      weigh: { clientSide: 'number', serverSide: 'number' },
      deductPoints: { clientSide: 'number', serverSide: 'number' },
      points: { clientSide: 'number', serverSide: 'number' },
      self: { clientSide: 'number', serverSide: 'number' },
      ichUnit: { clientSide: 'number', serverSide: 'number' },
      unitPoints: { clientSide: 'number', serverSide: 'number' },
      county: { clientSide: 'number', serverSide: 'number' },
      countyPoints: { clientSide: 'number', serverSide: 'number' },
      district: { clientSide: 'number', serverSide: 'number' },
      districtPoints: { clientSide: 'number', serverSide: 'number' },
      province: { clientSide: 'number', serverSide: 'number' },
      provincePoints: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'string' },
    };
    this._convertKeyType = (key) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return { clientSide: 'string', serverSide: 'undefined' };
      }
      return undefined;
    };
  }

  id = 0 as number;
  userId = 0 as number;
  year = 0 as number;
  inheritor = '' as string|null;
  unit = '' as string|null;
  ichName = '' as string|null;
  mobile = '' as string|null;
  idCard = '' as string|null;
  level = null as number|string|null;
  address = '' as string|null;
  weigh = 0 as number;
  deductPoints = 0 as number;
  points = 0 as number;
  self = null as number|null;
  ichUnit = null as number|null;
  unitPoints = 0 as number;
  county = null as number|null;
  countyPoints = 0 as number;
  district = null as number|null;
  districtPoints = 0 as number;
  province = null as number|null;
  provincePoints = 0 as number;
  createtime = '' as string;
  updatetime = '' as string;
  selfText = '' as string;
}

/** 传承协议列表行 */
export class AgreementListRow extends DataModel<AgreementListRow> {
  constructor() {
    super(AgreementListRow, '传承协议列表项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      userId: { clientSide: 'number', serverSide: 'number' },
      year: { clientSide: 'number', serverSide: 'number' },
      apprentice: { clientSide: 'number', serverSide: 'number' },
      activity: { clientSide: 'number', serverSide: 'number' },
      course: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'number' },
    };
  }

  id = 0 as number;
  userId = 0 as number;
  level = null as number|null;
  year = 0 as number;
  partyA = '' as string|null;
  partyB = '' as string|null;
  apprentice = 0 as number;
  activity = 0 as number;
  course = 0 as number;
  mobile = '' as string|null;
  partyAMobile = '' as string|null;
  idCard = '' as string|null;
  health = '' as string|null;
  ich = '' as string|null;
  partyASign = '' as string|null;
  partyBSign = '' as string|null;
  createtime = '' as string;
  updatetime = '' as string;
  deletetime = '' as string|null;
}

/** 传承人基础信息（ich/check/basic） */
export class InheritorCheckBasicInfo extends DataModel<InheritorCheckBasicInfo> {
  constructor() {
    super(InheritorCheckBasicInfo, '传承人自查基础信息');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      userId: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'number' },
      batch: { clientSide: 'number', serverSide: 'number' },
    };
    this._convertKeyType = (key) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return { clientSide: 'string', serverSide: 'undefined' };
      }
      return undefined;
    };
  }

  userId = 0 as number;
  name = '' as string;
  region = '' as string;
  gender = '' as string;
  education = '' as string|null;
  ichName = '' as string;
  unit = '' as string;
  level = 0 as number;
  idCard = '' as string;
  address = '' as string;
  batch = 0 as number;
  mobile = '' as string;
  genderText = '' as string;
  educationText = '' as string;
  levelText = '' as string;
  regionText = '' as string;
}

/** 详情中已选计分项 */
export class SelfAssessmentCheckItemAnswer extends DataModel<SelfAssessmentCheckItemAnswer> {
  constructor() {
    super(SelfAssessmentCheckItemAnswer, '自查计分选项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      points: { clientSide: 'number', serverSide: 'number' },
      count: { clientSide: 'number', serverSide: 'number' },
    };
  }

  /**
   * 选项ID
   */
  id = 0 as number;
  points = 0 as number;
  count = 0 as number;
}

/** 自查评估表详情 */
export class SelfAssessmentDetail extends DataModel<SelfAssessmentDetail> {
  constructor() {
    super(SelfAssessmentDetail, '自查评估表详情');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      userId: { clientSide: 'number', serverSide: 'number' },
      year: { clientSide: 'number', serverSide: 'number' },
      weigh: { clientSide: 'number', serverSide: 'number' },
      deductPoints: { clientSide: 'number', serverSide: 'number' },
      points: { clientSide: 'number', serverSide: 'number' },
      self: { clientSide: 'number', serverSide: 'number' },
      ichUnit: { clientSide: 'number', serverSide: 'number' },
      unitPoints: { clientSide: 'number', serverSide: 'number' },
      county: { clientSide: 'number', serverSide: 'number' },
      countyPoints: { clientSide: 'number', serverSide: 'number' },
      district: { clientSide: 'number', serverSide: 'number' },
      districtPoints: { clientSide: 'number', serverSide: 'number' },
      province: { clientSide: 'number', serverSide: 'number' },
      provincePoints: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'string' },
      checkItems: {
        clientSide: 'array',
        clientSideChildDataModel: SelfAssessmentCheckItemAnswer,
        customToServerFn: (value) => {
          return (value as SelfAssessmentCheckItemAnswer[])
            .filter(item => item.count > 0)
            .map((item) => {
              return {
                id: item.id,
                count: item.count,
              };
            });
        },
      },
    };
    this._blackList.toServer = [
      'createtime',
      'updatetime',
      'deletetime',
    ]
    this._convertKeyType = (key) => {
      if (key.endsWith('Text') || key.endsWith('_text')) {
        return { clientSide: 'string', serverSide: 'undefined' };
      }
      return undefined;
    };
    this._beforeSolveClient = (data) => {
      if (data.id == 0)
        delete data.id;
      return data;
    }
  }

  id = 0 as number;
  userId = 0 as number;
  year = 0 as number;
  inheritor = '' as string|null;
  unit = '' as string|null;
  ichName = '' as string|null;
  mobile = '' as string|null;
  idCard = '' as string|null;
  level = null as number|string|null;
  address = '' as string|null;
  content = '' as string|null;
  weigh = 0 as number;
  deductContent = '' as string|null;
  deductPoints = 0 as number;
  points = 0 as number;
  self = null as number|null;
  sign = '' as string|null;
  ichUnit = null as number|null;
  unitPoints = 0 as number;
  county = null as number|null;
  countyPoints = 0 as number;
  district = null as number|null;
  districtPoints = 0 as number;
  province = null as number|null;
  provincePoints = 0 as number;
  createtime = '' as string;
  updatetime = '' as string;
  deletetime = '' as string|null;
  selfText = '' as string;
  checkItems :  SelfAssessmentCheckItemAnswer[] = [];
}

/** 传承协议详情 */
export class AgreementDetail extends DataModel<AgreementDetail> {
  constructor() {
    super(AgreementDetail, '传承协议详情');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      userId: { clientSide: 'number', serverSide: 'number' },
      year: { clientSide: 'number', serverSide: 'number' },
      apprentice: { clientSide: 'number', serverSide: 'number' },
      activity: { clientSide: 'number', serverSide: 'number' },
      course: { clientSide: 'number', serverSide: 'number' },
      level: { clientSide: 'number', serverSide: 'number' },
      updatetime: { clientSide: 'date', serverSide: 'undefined' },
    };
    this._nameMapperClient = {
      partyA: 'party_a',
      partyB: 'party_b',
      partyASign: 'party_a_sign',
      partyBSign: 'party_b_sign',
      partyAMobile: 'party_a_mobile',
    }
    this._blackList.toServer = [
      'createtime',
      'updatetime',
      'deletetime',
    ]
    this._beforeSolveClient = (data) => {
      if (data.id == 0)
        delete data.id;
    }
  }

  id = 0 as number;
  userId = 0 as number;
  level = null as number|null;
  year = 0 as number;
  partyA = '' as string|null;
  partyB = '' as string|null;
  apprentice = 0 as number;
  activity = 0 as number;
  course = 0 as number;
  mobile = '' as string|null;
  partyAMobile = '' as string|null;
  idCard = '' as string|null;
  health = '' as string|null;
  ich = '' as string|null;
  partyASign = '' as string|null;
  partyBSign = '' as string|null;
  updatetime = new Date();
}

export type IchCheckPaginated<T> = {
  total: number;
  perPage: number;
  currentPage: number;
  lastPage: number;
  data: T[];
};

function normalizePaginated<T extends DataModel>(rowClass: new () => T, raw: KeyValue): IchCheckPaginated<T> {
  const rows = Array.isArray(raw.data) ? (raw.data as KeyValue[]) : [];
  return {
    total: Number(raw.total ?? 0),
    perPage: Number(raw.per_page ?? 0),
    currentPage: Number(raw.current_page ?? 0),
    lastPage: Number(raw.last_page ?? 0),
    data: transformArrayDataModel(rowClass, rows, 'data'),
  };
}

export class AssessmentContentApi extends AppServerRequestModule<DataModel> {

  constructor() {
    super();
  }

  /**
   * 计分点列表
   * @param level 23=国家级,24=省级,25=市级；0=通用
   */
  async getCheckItems(level: number) {
    const res = await this.post('/ich/check/getCheckItems', '自查计分项目', { level });
    const list = transformSomeToArray(res.data) as KeyValue[];
    const items = transformArrayDataModel<CheckItemInfo>(CheckItemInfo, list, 'data');
    const top = items.filter((item) => item.pid === 0);
    for (const item of items) 
      item.children = items.filter((i) => i.pid === item.id);
    return top;
  }

  /**
   * 自查评估表分页列表
   * @see https://www.showdoc.com.cn/minnanCE/11559060626966335
   */
  async getSelfAssessmentList(data: {
    userId?: number;
    level?: number;
    year?: number;
    keywords?: string;
    page?: number;
    pageSize?: number;
  }) {
    const res = await this.post<KeyValue>('/ich/check/getList', '评估表列表', {
      user_id: data.userId,
      level: data.level,
      year: data.year,
      keywords: data.keywords,
      page: data.page,
      pageSize: data.pageSize,
    });
    return normalizePaginated<SelfAssessmentListRow>(SelfAssessmentListRow, res.requireData());
  }

  /**
   * 传承协议分页列表
   */
  async getAgreementList(data: {
    userId?: number;
    level?: number;
    year?: number;
    keywords?: string;
    page?: number;
    pageSize?: number;
  }) {
    const res = await this.post<KeyValue>('/ich/check/getAgreementList', '传承协议列表', {
      user_id: data.userId,
      level: data.level,
      year: data.year,
      keywords: data.keywords,
      page: data.page,
      pageSize: data.pageSize,
    });
    return normalizePaginated<AgreementListRow>(AgreementListRow, res.requireData());
  }

  /**
   * 保存传承协议
   */
  async saveAgreement(dataModel: AgreementDetail) {
    return this.post('/ich/check/saveAgreement', '传承协议保存', dataModel.toServerSide());
  }

  /**
   * 保存自查评估表
   */
  async saveSelfAssessment(dataModel: SelfAssessmentDetail) {
    return this.post('/ich/check/save', '自查评估表保存', dataModel.toServerSide());
  }

  /**
   * 传承人基础信息（默认当前用户；管理员可传 userId）
   */
  async getInheritorBasic(userId?: number) {
    const res = await this.post<KeyValue>('/ich/check/basic', '传承人自查基础信息', {
      user_id: userId,
    });
    return transformDataModel<InheritorCheckBasicInfo>(InheritorCheckBasicInfo, res.requireData());
  }

  /**
   * 自查评估表详情
   */
  async getSelfAssessmentDetail(id: number) {
    const res = await this.post<KeyValue>('/ich/check/detail', '评估表详情', { id });
    return transformDataModel<SelfAssessmentDetail>(SelfAssessmentDetail, res.requireData());
  }

  /**
   * 传承协议详情
   */
  async getAgreementDetail(id: number) {
    const res = await this.post<KeyValue>('/ich/check/agreementDetail', '传承协议详情', { id });
    return transformDataModel<AgreementDetail>(AgreementDetail, res.requireData());
  }
}

export default new AssessmentContentApi();
