import { Image } from '@tarojs/components';
import Taro, { useLoad } from '@tarojs/taro';

import { List } from '@taroify/core';
import classNames from 'classnames';
import { useCallback, useState } from 'react';

import { EventName, OpenSource } from '@/constants/app';
import { JobManageStatus } from '@/constants/job';
import { JobManageInfo } from '@/types/job';
import { getJobLocation, requestJobManageList } from '@/utils/job';
import { getPageQuery, navigateBack } from '@/utils/route';
import { formatTime } from '@/utils/time';
import Toast from '@/utils/toast';

import './index.less';

const PREFIX = 'page-job-select-my-publish';

export default function JobSelectMyPublish() {
  const [list, setList] = useState<JobManageInfo[]>([]);
  const [jobId, setJobId] = useState<string | null>('1');
  const [source, setSource] = useState<OpenSource>();

  const handleClick = useCallback(
    (info: JobManageInfo) => {
      Taro.eventCenter.trigger(EventName.SELECT_MY_PUBLISH_JOB, info, source);
      navigateBack();
    },
    [source]
  );

  useLoad(async () => {
    const query = getPageQuery<{ id: string; source: OpenSource }>();
    query?.id && setJobId(query.id);
    try {
      const res = await requestJobManageList({ status: JobManageStatus.Open });
      setList(res.jobResults);
      setSource(query.source);
    } catch (e) {
      console.error(e);
      Toast.error('出错了，请重试');
    }
  });

  return (
    <div className={PREFIX}>
      <List disabled>
        {list.map(item => (
          <div
            key={item.id}
            onClick={() => handleClick(item)}
            className={classNames(`${PREFIX}__card`, { selected: item.id === jobId })}
          >
            <div className={`${PREFIX}__info`}>
              <div className={`${PREFIX}__info__title`}>{item.title}</div>
              <div className={`${PREFIX}__info__location`}>{getJobLocation(item)}</div>
            </div>
            <div className={`${PREFIX}__right`}>
              <div className={`${PREFIX}__right__time`}>{formatTime(item.updated)}</div>
              {item.id === jobId && (
                <Image
                  mode="aspectFit"
                  className={`${PREFIX}__right__icon`}
                  src={require('@/statics/svg/success.svg')}
                />
              )}
            </div>
          </div>
        ))}
      </List>
    </div>
  );
}
