import Taro from '@tarojs/taro';

import { CacheKey } from '@/constants/cache-key';
import { CollectEventName } from '@/constants/event';
import { EmployType, JobManageStatus, UserJobType } from '@/constants/job';
import http from '@/http';
import { API } from '@/http/api';
import store from '@/store';
import { selectLocation } from '@/store/selector';
import {
  JobDetails,
  GetJobsDetailsRequest,
  GetJobsRequest,
  GetJobsResponse,
  JobInfo,
  GetUserJobRequest,
  GetUserJobResponse,
  MyDeclaredJobInfo,
  MyBrowsedJobInfo,
  GetMyRecommendJobRequest,
  GetJobManagesRequest,
  GetJobManagesResponse,
  CreateJobInfo,
  JobManageInfo,
} from '@/types/job';
import { collectEvent } from '@/utils/event';
import { getCityValues } from '@/utils/location';

export const isFullTimePriceRequired = (employType?: JobDetails['employType']) => {
  return employType === EmployType.Full || employType === EmployType.All;
};

export const isPartTimePriceRequired = (employType?: JobDetails['employType']) => {
  return employType === EmployType.Part || employType === EmployType.All;
};

export const getJobSalary = (data: Partial<JobDetails>) => {
  const { salary, employType, lowPriceForFullTime, highPriceForFullTime, lowPriceForPartyTime, highPriceForPartyTime } =
    data;
  if (salary) {
    return salary;
  }
  const fullSalary =
    lowPriceForFullTime && highPriceForFullTime
      ? `${lowPriceForFullTime / 1000} - ${highPriceForFullTime / 1000}K/月`
      : '';
  const partSalary =
    lowPriceForPartyTime && highPriceForPartyTime ? `${lowPriceForPartyTime} - ${highPriceForPartyTime}/小时` : '';
  const salaries: string[] = [];
  if (employType === EmployType.All) {
    salaries.push(fullSalary, partSalary);
  } else if (employType === EmployType.Full) {
    salaries.push(fullSalary);
  } else if (employType === EmployType.Part) {
    salaries.push(partSalary);
  }
  return salaries.filter(Boolean).join('，');
};

export const setLastSelectMyJobId = (jobId: string) => Taro.setStorageSync(CacheKey.LAST_SELECT_MY_JOB, jobId);

export const getLastSelectMyJobId = () => Taro.getStorageSync<string>(CacheKey.LAST_SELECT_MY_JOB);

export const getJobLocation = (data: JobManageInfo) => {
  const cityValues = getCityValues([data.provinceCode, data.cityCode, data.countyCode], '-');
  return cityValues ? cityValues : data.jobLocation;
};

export const getJobTitle = (data: JobInfo) => data.title || (data.sourceText || '').substring(0, 20);

async function requestMyDeclaredJobList(data: GetUserJobRequest) {
  const result = await http.post<GetUserJobResponse<MyDeclaredJobInfo>>(API.MY_DECLARED_JOB_LIST, { data });
  return result;
}

async function requestMyBrowsedJobList(data: GetUserJobRequest) {
  const result = await http.post<GetUserJobResponse<MyBrowsedJobInfo>>(API.MY_BROWSED_JOB_LIST, { data });
  return result;
}

export async function requestJobList(data: GetJobsRequest = {}) {
  const isGetMyJob = data.isOwner || data.isFollow;
  const url = isGetMyJob ? API.GET_MY_JOB_LIST_V2 : API.GET_JOB_LIST;
  return await http.post<GetJobsResponse>(url, { data });
}

export async function requestJobDetail(jobId: GetJobsDetailsRequest['jobId']) {
  const { longitude, latitude } = selectLocation(store.getState());
  const data: GetJobsDetailsRequest = { jobId, longitude, latitude };
  const detail = await http.post<JobDetails>(API.GET_JOB_DETAIL, { data });
  if (!detail.publisher || !detail.sourceText) {
    collectEvent(CollectEventName.DEBUG, { action: 'invalid_job_detail', response: detail, request: data });
  }
  return detail;
}

export async function requestUserJobList(data: GetUserJobRequest) {
  const request = data.type === UserJobType.MyDeclared ? requestMyDeclaredJobList : requestMyBrowsedJobList;
  const result = await request(data);
  const dataMap = new Map();
  Object.entries(result.data).forEach(([k, v]) => dataMap.set(k, v));
  result.dataMap = dataMap;
  return result;
}

export async function requestMyRecommendJobList(data: GetMyRecommendJobRequest) {
  return await http.post<GetJobsResponse>(API.MY_RECOMMEND_JOB_LIST, { data });
}

export async function requestJobManageList(data: Partial<GetJobManagesRequest> = {}) {
  return await http.post<GetJobManagesResponse>(API.GET_JOB_MANAGE_LIST, { data });
}

export async function requestHasPublishedJob() {
  const data = await requestJobManageList({ status: JobManageStatus.Open });
  return data.jobResults.length > 0;
}

export function postCreateJob(data: CreateJobInfo) {
  return http.post(API.CREATE_JOB, { data });
}

export function postUpdateJob(data: CreateJobInfo) {
  return http.post(API.UPDATE_JOB, { data });
}

export function postPublishJob(jobId: string) {
  return http.post(API.PUBLISH_JOB, { data: { jobId }, contentType: 'application/x-www-form-urlencoded' });
}

export function postCloseJob(jobId: string) {
  return http.post(API.CLOSE_JOB, { data: { jobId }, contentType: 'application/x-www-form-urlencoded' });
}
