//案件流转记录（办理经过）
import services from '@/services';
import { imageOptions } from '@/utils/comm';
import { getSession, setSession } from '@/utils/session';
import { IMG_URL } from '@/utils/variables';
import {
  FileWordTwoTone,
  SortAscendingOutlined,
  SortDescendingOutlined,
} from '@ant-design/icons';
import { Flex, Image, message, Popover, Space } from 'antd';
import classNames from 'classnames';
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from 'react';
import { propsType } from '..';
import styles from './index.less';
import LimitTime from './LimitTime';

export type CulationComponentRef = {
  queryCirculationRecord: () => void;
  getLastCasecirculationId: API.CulationType; //案件流转记录最新
};

interface culationProps {
  eventId: string; //案件id
  pretreatmentType?: string;
  eventType?: propsType['eventType'];
  casecirculationRecordData?: any[]; //流转记录
}
export type SortDto = 'asc' | 'des'; //排序方式
const CulationComponent = forwardRef<CulationComponentRef, culationProps>(
  (props, ref) => {
    useImperativeHandle(ref, () => ({
      queryCirculationRecord, //查询案件流转
      getLastCasecirculationId: getLastCasecirculationId,
    }));

    const {
      eventId,
      pretreatmentType = '',
      eventType,
      casecirculationRecordData,
    } = props;
    const [isTimeout, setIsTimeout] = useState<boolean>(false); //判断是否超时
    const [casecirculationRecord, setCasecirculationRecord] = useState<
      API.CulationType[]
    >([]); //案件流转记录
    const [recordSort, setRecordSort] = useState<SortDto | string>(
      getSession('recordSort') || 'des',
    ); //流转记录排序

    useEffect(() => {
      if (casecirculationRecordData) {
        setCasecirculationRecord(casecirculationRecordData);
      } else {
        //queryCirculationRecord();
      }
    }, [casecirculationRecordData]);

    //最新的案件流转记录
    const getLastCasecirculationId = useMemo(() => {
      return casecirculationRecord[casecirculationRecord?.length - 1];
    }, [casecirculationRecord]);

    //查询案件流转
    const queryCirculationRecord = () => {
      if (eventType === 'pretreatment') {
        //预处理
        services.PreEventQuery.getCaseCirculationRecord({
          caseId: String(eventId),
          pretreatmentType,
        }).then((res) => {
          if (res.code === 200) {
            setCasecirculationRecord(res.data);
          }
        });
      } else {
        //通用
        services.DealQuery.getCaseCirculationRecord(String(eventId)).then(
          (res) => {
            if (res.code === 200) {
              setCasecirculationRecord(res.data);
            }
          },
        );
      }
    };

    const caseResult = casecirculationRecord[casecirculationRecord?.length - 1]; //流转结果
    const record = casecirculationRecord
      .slice(0, casecirculationRecord?.length - 1)
      .reverse(); //流转记录
    //查看文件下载
    const handleFileCheck = (path: string) => {
      let btn: any = document.createElement('a');
      btn.target = '_blank';
      btn.download = path; //文件类型
      btn.href = path;
      btn.click();
      btn = null;
      window.setTimeout(function () {
        message.success('下载完成');
      }, 2000);
    };
    //设置排序方式
    const handleChangeSort = (type: SortDto) => {
      setSession('recordSort', type); //缓存流转记录的排序方式
      setRecordSort(type);
    };
    return (
      <div className={styles.culationWrap}>
        <Flex
          className={styles.headerTitle}
          justify="space-between"
          align="center"
        >
          <div className={styles.titleWrap}>
            <span>风险处置流程</span>
          </div>

          <Space>
            <div
              className={classNames(
                styles.sortIcon,
                recordSort === 'asc' ? styles.active : '',
              )}
              onClick={() => handleChangeSort('asc')}
            >
              <SortAscendingOutlined />
            </div>
            <div
              className={classNames(
                styles.sortIcon,
                recordSort === 'des' ? styles.active : '',
              )}
              onClick={() => handleChangeSort('des')}
            >
              <SortDescendingOutlined />
            </div>
          </Space>
        </Flex>

        <div className={classNames(styles.culationContent, styles[recordSort])}>
          {/* <div
            className={styles.result}
            style={{ background: isTimeout ? 'rgba(250, 48, 51,.9)' : '' }}
          >
            <span className={styles.status}>
              {caseResult?.operationType ?? caseResult?.caseStatusName}
            </span>
            {!caseResult?.operationType && (
              <LimitTime
                handleIsTime={(flag) => setIsTimeout(flag)}
                endTime={caseResult?.disposeDeadline}
                progressShow
                startTime={caseResult?.createTime}
                timeText={caseResult?.remainingTimeText}
              />
            )}
            <p className={styles.timeInfotext}>
              节点耗时:{caseResult?.consumptionTimeText}&emsp;
              {caseResult?.processingTimeLimitText && (
                <>
                  节点办理时限:
                  {caseResult?.processingTimeLimitText}
                </>
              )}
              {caseResult?.processingCenter && (
                <Popover content={caseResult?.processingCenter}>
                  <span className={classNames('textellipsis', styles.dept)}>
                    节点办理单位:{caseResult?.processingCenter}
                  </span>
                </Popover>
              )}
            </p>
          </div> */}

          {/* 流转 */}
          {record &&
            record.map((item, index) => (
              <div
                key={index}
                className={classNames(styles.record_item, styles[recordSort])}
              >
                {
                  (index!==0)&&<div className={styles.flow}>
                    {recordSort === 'asc' ? (
                      <img
                        src={require('@/assets/images/eventInfo/up.png')}
                        className={styles.down}
                      />
                    ) : (
                      <img src={require('@/assets/images/eventInfo/up.png')} />
                    )}
                    {record[index - 1]?.consumptionTimeText && (
                      <span className={styles.timeDes}>
                        {record[index - 1]?.consumptionTimeText}
                      </span>
                    )}
                  </div>
                }
                <div className={styles.culationItems}>
                  <Flex
                    align="center"
                    justify="center"
                    className={styles.leftIcon}
                  >
                    <img
                      src={require(`@/assets/images/eventInfo/tz.png`)}
                      className={styles.icon}
                      alt=""
                    />
                  </Flex>

                  <Flex vertical style={{ flex: 1 }}>
                    <Flex style={{ flex: 1 }} align="center">
                      <div className={styles.info}>
                        {item.circulationPersonId && (
                          <div className={styles.role}>
                            <p>{item.circulationPersonName}</p>
                          </div>
                        )}
                        <p className={styles.time}>{item?.recordTime}</p>
                      </div>
                    </Flex>
                    {/* 备注 */}
                    {item.remarks && (
                      <div className={styles.remark}>备注：{item.remarks}</div>
                    )}

                    {/* 上报不显示附件 */}
                    {item?.eventAttachmentInfos &&
                      item?.operationType !== '上报' && (
                        <div className={styles.eventAttachment}>
                          <span className={styles.attachment}> 办理附件:</span>
                          {item?.eventAttachmentInfos?.map(
                            (attachment, index: number) => {
                              if (attachment?.fileType === '图片') {
                                return (
                                  <Image
                                    width={20}
                                    height={24}
                                    src={
                                      attachment?.attachmentPath?.includes(
                                        'http',
                                      )
                                        ? attachment?.attachmentPath
                                        : IMG_URL + attachment.attachmentPath
                                    }
                                    {...imageOptions}
                                    key={index}
                                    style={{ objectFit: 'cover' }}
                                  />
                                );
                              } else {
                                return (
                                  <FileWordTwoTone
                                    className={styles.icon}
                                    onClick={() =>
                                      handleFileCheck(
                                        attachment?.attachmentPath,
                                      )
                                    }
                                    key={index}
                                  />
                                );
                              }
                            },
                          )}
                        </div>
                      )}
                  </Flex>
                  <span className={styles.status}>{item?.operationType}</span>
                </div>
              </div>
            ))}
        </div>
      </div>
    );
  },
);
export default CulationComponent;
