import { List, Popup, InfiniteScroll } from 'antd-mobile';
import { Card } from 'antd';
import { useDataGrip } from './useDataGrip';
import './index.less';
import { useEffect, useState } from 'react';
import React from 'react';
import { formatDate, getDictionaryColumnsValueByValue } from '../../utils/util';
import { useModel } from '../../utils/umiExport';
import Badge from '../../components/Badge';
interface Props {
  queryList: any[];
  columnJson: any[];
  condition: any;
  totalPage: number;
  shouldLoad: boolean;
  actions: Array<any>;
  loadData: any;
  config?: DataGripConfig;
}
export interface DataGripConfig {
  ischeckChange?: boolean; //是否支持选中，触发选中样式和事件
  checkmust?: boolean; //是否支持多选
  changeCallBack?: (data1: any, data2: any) => void; //选中事件
  seeColumnTitle?: Array<string>; //需要查看的列标题
}
// 默认配置
const defaultDataGripConfig: DataGripConfig = {
  ischeckChange: false,
  checkmust: false,
  seeColumnTitle: [],
};

const DataGrip: React.FC<Props> = ({
  totalPage,
  loadData,
  actions,
  queryList,
  columnJson,
  condition,
  shouldLoad = true,
  config = defaultDataGripConfig,
}) => {
  const {
    list,
    visible,
    pageNo,
    setVisible,
    loadMore,
    getActions,
    showDetails,
  } = useDataGrip(loadData, actions, condition);
  // 选中的key，赋予动态样式
  const [getCardChange, setChangeCard] = useState<Array<any>>([]);
  const [getCardChangeData, setCardChangeData] = useState<Array<any>>([]);
  // Store
  const { initialState }: any = useModel("@@initialState")
  const dictionary = initialState.dictionary;


  const cardClick = function (e: any, key: any, queryData: any) {
    // 是否开启选择
    if (config.ischeckChange) {
      let thisGradCard = JSON.parse(JSON.stringify(getCardChange));
      let thisGradCardQueryData = JSON.parse(JSON.stringify(getCardChangeData));

      if (thisGradCard.some((item: any) => item === key)) {
        thisGradCard.splice(thisGradCard.indexOf(key), 1);
        setChangeCard([...thisGradCard]);
      } else {
        // 是否支持多选
        if (config.checkmust) {
          setChangeCard([key, ...thisGradCard]);
        } else {
          setChangeCard([key]);
        }
      }
      if (
        thisGradCardQueryData.some(
          (item: any) => JSON.stringify(item) === JSON.stringify(queryData),
        )
      ) {
        thisGradCardQueryData.splice(
          thisGradCardQueryData.findIndex(
            (item: any) => JSON.stringify(item) === JSON.stringify(queryData),
          ),
          1,
        );
        setCardChangeData([...thisGradCardQueryData]);
      } else {
        // 是否支持多选
        if (config.checkmust) {
          setCardChangeData([queryData, ...thisGradCardQueryData]);
        } else {
          setCardChangeData([queryData]);
        }
      }
    }
  };

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    config.changeCallBack &&
      config.changeCallBack(getCardChange, getCardChangeData);
  }, [getCardChangeData]);

  return (
    <>
      <div className="af-data-grip-list">
        <>
          {queryList.map((query) => (
            <Card
              onClick={(e: any) =>
                cardClick(e, query[columnJson[0].dataIndex], query)
              }
              key={query[columnJson[0].dataIndex]}
              title={query[columnJson[0].dataIndex]}
              extra={<a onClick={() => showDetails(query)}>详情</a>}
              style={{ margin: '6px 10px 0px 10px' }}
              className={
                getCardChange.includes(query[columnJson[0].dataIndex])
                  ? 'card-active'
                  : ''
              }
              actions={getActions(query)}
            >
              {
                columnJson.filter((column, index) => config.seeColumnTitle && config.seeColumnTitle.length > 0 ? config.seeColumnTitle.some((seetitle) => seetitle === column.title) : index < 3)
                  .map((column, index) => {
                    return <p key={index} className="infiniteScroll-p-class">
                      {column.title}:
                      {
                        column.slotType === 'ellipsis' ? query[column.dataIndex]
                          //徽标(badge) 
                          : column.slotType === 'badge' ? <Badge badgeKey={column.slotKeyMap} value={query[column.dataIndex]} />
                            //日期(date)
                            : column.slotType === 'date' ? formatDate(query[column.dataIndex], 'yyyy-MM-dd')
                              //日期时间(datetime)
                              : column.slotType === 'dateTime' ? formatDate(query[column.dataIndex], 'yyyy-MM-dd hh:mm:ss') : query[column.dataIndex]
                      }
                    </p>
                  })
              }
            </Card>
          ))}
        </>
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={totalPage >= pageNo && shouldLoad}
        />
        <Popup
          visible={visible}
          onMaskClick={() => {
            setVisible(false);
          }}
          bodyStyle={{
            minHeight: '50vh',
            maxHeight: '60vh',
            backgroundColor: 'rgb(245,247,250)',
            overflow: 'scroll',
          }}
        >
          <List mode="card" header="详细信息">
            {columnJson.map((column, index) => {
              return column.dataIndex !== 'action' ? (
                <List.Item extra={column.slotType === 'badge' && column.slotKeyMap ? getDictionaryColumnsValueByValue(dictionary, column.slotKeyMap, list[column.dataIndex])?.label : list[column.dataIndex]} key={index}>
                  {column.title}
                </List.Item>
              ) : (
                ''
              );
            })}
          </List>
        </Popup>
      </div>
    </>
  );
};

export default DataGrip;
