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' },
      progress: { clientSide: 'number', serverSide: 'number' },
    };
    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;
  /** -1=未提交,0=草稿,1=已自评,2～5 各级审核完成 */
  progress = null as number|null;
}

/** 传承协议列表行 */
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/getUserAgreement） */
export class UserAgreementListRow extends DataModel<UserAgreementListRow> {
  constructor() {
    super(UserAgreementListRow, '传承人传承协议列表项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      sitesId: { clientSide: 'number', serverSide: 'number' },
      batch: { clientSide: 'number', serverSide: 'number' },
      ichId: { clientSide: 'number', serverSide: 'number' },
      agreementId: { 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' },
      progress: { 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;
  title = '' as string;
  associationId = '' as string;
  sitesId = 0 as number;
  level = null as number|string|null;
  batch = 0 as number;
  gender = '' as string;
  basicMobile = '' as string|null;
  basicUnit = '' as string|null;
  ichId = 0 as number;
  ichTitle = '' as string;
  /** 已填写的传承协议记录 ID，未填写时为 null */
  agreementId = null as number|null;
  userId = null as number|null;
  year = null as number|null;
  partyA = '' as string|null;
  partyB = '' as string|null;
  apprentice = null as number|null;
  activity = null as number|null;
  course = null as number|null;
  mobile = '' as string|null;
  partyAMobile = '' as string|null;
  partyAContact = '' as string|null;
  idCard = '' as string|null;
  health = '' as string|null;
  ich = '' as string|null;
  partyASign = '' as string|null;
  partyBSign = '' as string|null;
  /** -1=未提交,0=草稿,1=已自评,2=审核完成 */
  progress = null as number|null;
  createtime = '' as string|null;
  updatetime = '' as string|null;
  deletetime = '' as string|null;
  batchText = '' as string;
  ichSiteTypeText = '' as string;
}

/** 保护单位账号：传承人列表行（ich/check/getInheritorList） */
export class InheritorCheckListRow extends DataModel<InheritorCheckListRow> {
  constructor() {
    super(InheritorCheckListRow, '传承人列表项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      sitesId: { clientSide: 'number', serverSide: 'number' },
      batch: { clientSide: 'number', serverSide: 'number' },
      ichId: { clientSide: 'number', serverSide: 'number' },
      checkId: { 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' },
      progress: { 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;
  title = '' as string;
  /** 关联项目 ID（接口可能返回字符串数字） */
  associationId = '' as string;
  sitesId = 0 as number;
  level = null as number|string|null;
  batch = 0 as number;
  gender = '' as string;
  basicMobile = '' as string|null;
  basicUnit = '' as string|null;
  ichId = 0 as number;
  ichTitle = '' as string;
  checkId = null as number|null;
  userId = null as number|null;
  year = null as number|null;
  inheritor = '' as string|null;
  unit = '' as string|null;
  ichName = '' as string|null;
  mobile = '' as string|null;
  idCard = '' as string|null;
  address = '' as string|null;
  weigh = null as number|null;
  deductPoints = null as number|null;
  points = null as number|null;
  self = null as number|null;
  ichUnit = null as number|null;
  unitPoints = null as number|null;
  county = null as number|null;
  countyPoints = null as number|null;
  district = null as number|null;
  districtPoints = null as number|null;
  province = null as number|null;
  provincePoints = null as number|null;
  createtime = '' as string|null;
  updatetime = '' as string|null;
  /** -1=未提交,0=草稿,1=已自评,2=项目保护单位审核完成,3=县（区）文旅部门审核完成,4=设区市文旅部门/省非遗中心审核完成,5=省文化和旅游厅审核完成 */
  progress = null as number|null;
  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;
}

/** 传承人基础信息（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;
  /** 已填写的传承协议ID */
  agreementId = 0 as number;
  /** 已填写的自查表ID */
  checkId = 0 as number;
}

/** 详情中已选计分项 */
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' },
    };
    this._afterSolveServer = (data) => {
      if (data.itemId)
        data.id = data.itemId;
    }
  }

  /**
   * 选项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' },
      content: { 
        customToClientFn: (value) => {
          try {
            if (typeof value === 'object') 
              return value;
            return JSON.parse(value as string);
          } catch {
            return {};
          }
        },
        customToServerFn: (value) => {
          return value;
        },
      },
      awardTime: {
        clientSide: 'date', 
        clientSideDateFormat: 'YYYY-MM-DD',
        serverSide: 'string',
        serverSideDateFormat: 'YYYY-MM-DD',
      },
      checkItems: {
        customToClientFn: (value) => {
          return transformArrayDataModel(SelfAssessmentCheckItemAnswer, transformSomeToArray(value), 'data');
        },
        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 : Record<string, any>|null = null;
  weigh = 0 as number;
  awardTime = new Date();
  deductContent = '' as string|null;
  deductPoints = 0 as number;
  points = 0 as number;
  progress = 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[] = [];  
  /** 退回状态: 0=无,1=自评阶段退回,2=项目保护单位退回,3=县(区)文旅部门退回,4=设区市文旅部门/省非遗中心退回,5=省文化和旅游厅退回 */
  rejectType?: number;
  /** 退回原因 */
  rejectReason?: string;
}

/** 传承协议详情 */
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();
}

/** 证明材料附件类型（saveAnnex `type`） */
export const CheckAnnexType = {
  Image: 1,
  Video: 2,
  Audio: 3,
  Document: 4,
  Other: 5,
  ExternalLink: 6,
} as const;

export function getCheckAnnexType(mimetype: string) {
  if (mimetype.startsWith('image/')) return CheckAnnexType.Image;
  if (mimetype.startsWith('video/')) return CheckAnnexType.Video;
  if (mimetype.startsWith('audio/')) return CheckAnnexType.Audio;
  if (mimetype.startsWith('application/pdf')) return CheckAnnexType.Document;
  return CheckAnnexType.Other;
}

export type CheckAnnexTypeValue = (typeof CheckAnnexType)[keyof typeof CheckAnnexType];

/** 自查表审核提交（POST /ich/check/review） */
export interface IchCheckReviewPayload {
  /** 自查表 ID */
  id: number;
  /** 项目保护单位意见: 1=优秀,2=合格,3=不合格,4=丧失传承能力,5=取消资格 */
  ichUnit?: number;
  unitPoints?: number;
  /** 县（区）文旅部门审核意见，取值同 ichUnit */
  county?: number;
  countyPoints?: number;
  /** 设区市文旅部门、省非遗中心审核意见，取值同 ichUnit */
  district?: number;
  districtPoints?: number;
  /** 省文化和旅游厅意见，取值同 ichUnit */
  province?: number;
  provincePoints?: number;
  /** 0=草稿,1=已自评,2=项目保护单位审核完成,3=县（区）文旅部门审核完成,4=设区市文旅部门/省非遗中心审核完成,5=省文化和旅游厅审核完成 */
  progress: number;
  /** 退回状态: 0=无,1=自评阶段退回,2=项目保护单位退回,3=县(区)文旅部门退回,4=设区市文旅部门/省非遗中心退回,5=省文化和旅游厅退回 */
  rejectType?: number;
  /** 退回原因 */
  rejectReason?: string;
}

/** 证明材料修改与新增请求体（POST /ich/check/saveAnnex） */
export interface SaveCheckAnnexPayload {
  /** 记录 ID，修改时必填 */
  id?: number;
  name: string;
  formId: number;
  /** 计分项 ID */
  itemId?: number;
  url: string;
  /** 1=图片,2=视频,3=音频,4=文档,5=其他附件,6=外部链接 */
  type: CheckAnnexTypeValue | number;
  desc?: string;
  mimetype?: string;
  attachId?: number;
  /** 文件大小，单位 KB */
  fileSize?: number;
}

/** 证明材料列表项（getAnnexList） */
export class CheckAnnexListItem extends DataModel<CheckAnnexListItem> {
  constructor() {
    super(CheckAnnexListItem, '证明材料列表项');
    this.setNameMapperCase('Camel', 'Snake');
    this._convertTable = {
      id: { clientSide: 'number', serverSide: 'number' },
      formId: { clientSide: 'number', serverSide: 'number' },
      type: { clientSide: 'number', serverSide: 'number' },
      attachId: { clientSide: 'number', serverSide: 'number' },
      fileSize: { clientSide: 'number', serverSide: 'number' },
    };
  }

  id = 0 as number;
  name = '' as string;
  formId = 0 as number;
  url = '' as string;
  /** 1=图片,2=视频,3=音频,4=文档,5=其他,6=外部链接 */
  type = 0 as number;
  desc = '' as string|null;
  mimetype = '' as string|null;
  attachId = null as number|null;
  /** 文件大小 KB */
  fileSize = null as number|null;
  createtime = '' as string|null;
  updatetime = '' as string|null;
}

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> {
  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, transformSomeToArray(raw.data), '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') as CheckItemInfo[];
    const map = new Map<number, CheckItemInfo>();
    for (const item of items)
      map.set(item.id, item);
    const top = items.filter((item) => item.pid === 0);
    for (const item of items) 
      item.children = items.filter((i) => i.pid === item.id);
    return {
      top,
      map,
    };
  }

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

  /**
   * 保护单位账号：传承人传承协议分页列表
   * POST `/ich/check/getUserAgreement`
   * @param data.progress -1=未提交,0=草稿,1=已自评,2=审核完成
   */
  async getUserAgreementList(data: {
    userId?: number;
    progress?: number;
    level?: number;
    year?: number;
    keywords?: string;
    page?: number;
    pageSize?: number;
  }) {
    const res = await this.post<KeyValue>('/ich/check/getUserAgreement', '传承人传承协议列表', {
      user_id: data.userId,
      progress: data.progress,
      level: data.level,
      year: data.year,
      keywords: data.keywords,
      page: data.page,
      pageSize: data.pageSize,
    });
    return normalizePaginated<UserAgreementListRow>(UserAgreementListRow, res.requireData());
  }

  /**
   * 保护单位账号：传承人分页列表
   * POST `/ich/check/getInheritorList`
   * @param data.progress -1=未提交,0=草稿,1=已自评,2=项目保护单位审核完成,3=县（区）文旅部门审核完成,4=设区市文旅部门/省非遗中心审核完成,5=省文化和旅游厅审核完成
   */
  async getInheritorList(data: {
    userId?: number;
    progress?: number;
    level?: number;
    year?: number;
    keywords?: string;
    page?: number;
    pageSize?: number;
  }) {
    const res = await this.post<KeyValue>('/ich/check/getInheritorList', '传承人列表', {
      user_id: data.userId,
      progress: data.progress,
      level: data.level,
      year: data.year,
      keywords: data.keywords,
      page: data.page,
      pageSize: data.pageSize,
    });
    return normalizePaginated<InheritorCheckListRow>(InheritorCheckListRow, res.requireData());
  }

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

  /**
   * 保存自查评估表
   */
  async saveSelfAssessment(dataModel: SelfAssessmentDetail, progress?: number) {
    const data = dataModel.toServerSide();
    if (progress !== undefined)
      data.progress = progress;
    return this.post('/ich/check/save', '自查评估表保存', data);
  }

  /**
   * 自查评估表审核
   * POST `/ich/check/review`
   */
  async reviewSelfAssessment(payload: IchCheckReviewPayload) {
    return this.post('/ich/check/review', '自查评估表审核', {
      id: payload.id,
      ich_unit: payload.ichUnit,
      unit_points: payload.unitPoints,
      county: payload.county,
      county_points: payload.countyPoints,
      district: payload.district,
      district_points: payload.districtPoints,
      province: payload.province,
      province_points: payload.provincePoints,
      progress: payload.progress,
      reject_type: payload.rejectType || 0,
      reject_reason: payload.rejectReason,
    });
  }

  /**
   * 下载自查评估表PDF
   */
  async downloadSelfAssessmentPdf(id: number) {
    return new Promise<string>((resolve, reject) => {
      uni.downloadFile({
        url: `${this.config.baseUrl}/pdf/create?id=${id}`,
        success: (res) => {
          if (res.statusCode !== 200)
            throw new Error('下载失败，状态码：' + res.statusCode);
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }

  /**
   * 下载传承协议PDF
   */
  async downloadAgreementPdf(id: number) {
    return new Promise<string>((resolve, reject) => {
      uni.downloadFile({
        url: `${this.config.baseUrl}/pdf/nationalContract?id=${id}`,
        success: (res) => {
          if (res.statusCode !== 200)
            throw new Error('下载失败，状态码：' + res.statusCode);
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }

  /**
   * 证明材料修改与新增
   * POST `/ich/check/saveAnnex`
   */
  async saveAnnex(payload: SaveCheckAnnexPayload) {
    return this.post('/ich/check/saveAnnex', '证明材料保存', {
      id: payload.id,
      name: payload.name,
      form_id: payload.formId,
      item_id: payload.itemId,
      url: payload.url,
      type: payload.type,
      desc: payload.desc,
      mimetype: payload.mimetype,
      attach_id: payload.attachId,
      filesize: payload.fileSize,
    });
  }

  /**
   * 证明材料列表（按自查表）
   * POST `/ich/check/getAnnexList`
   */
  async getAnnexList(formId: number, itemId?: number) {
    const res = await this.post<KeyValue>('/ich/check/getAnnexList', '证明材料列表', {
      form_id: formId,
      item_id: itemId,
    });
    return normalizePaginated<CheckAnnexListItem>(CheckAnnexListItem, res.requireData());
  }

  /**
   * 删除证明材料
   * POST `/ich/check/delAnnex`
   */
  async delAnnex(id: number) {
    return this.post('/ich/check/delAnnex', '删除证明材料', { id });
  }

  /**
   * 传承人基础信息（默认当前用户；管理员可传 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, userId?: number) {
    const res = await this.post<KeyValue>('/ich/check/detail', '评估表详情', { id, user_id: userId });
    return transformDataModel<SelfAssessmentDetail>(SelfAssessmentDetail, res.requireData());
  }

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

export default new AssessmentContentApi();
