/* eslint-disable react-hooks/exhaustive-deps */
import { ProDescriptions } from '@ant-design/pro-components';
import React, { useMemo, useState } from 'react';
import { doFetch } from '@/utils/doFetch';
import PropTypes from 'prop-types';
import styles from './index.less';
import { Col } from 'antd';

const { Item } = ProDescriptions;

function DetailPro(props) {
  let { fields } = props;
  const [curitem, setcuritem] = useState(props.detailData ?? {}); //全部数据

  const dataProps = useMemo(() => {
    if (props.detailData) {
      setcuritem(props.detailData);
      return { dataSource: props.detailData };
    } else {
      return {
        request: async () => {
          let res = await doFetch({ url: props.detailpath, params: props.params });
          if (props?.extendField) {
            let obj = {};
            res?.data?.data[props.extendField]?.forEach((it) => {
              obj[it?.fieldId] = it?.fieldRealValue;
            });
            //console.log('extendField:', obj);
            setcuritem({
              ...(res?.data?.data ?? {}),
              ...obj,
            });
            // console.log('drawerpro:', {
            //   ...(res?.data?.data ?? {}),
            //   ...obj,
            // });

            return {
              success: res?.code == '0000',
              data:
                {
                  ...(res?.data?.data ?? {}),
                  ...obj,
                } ?? {},
            };
          }
        },
      };
    }
  }, [props.detailData]);

  return (
    <ProDescriptions column={3} {...dataProps} title={props.title}>
      {fields?.map((it, i) => {
        const dataIndexs =
          !it?.render || it?.valueType == 'option'
            ? { dataIndex: it.dataIndex, valueType: it.valueType }
            : {};
        if (it.valueType == 'split') {
          return (
            <>
              <Col span={24}>
                <div className={styles.title} style={{ borderWidth: i == 0 ? 0 : 1 }}>
                  {it.title}
                </div>
              </Col>
            </>
          );
        }
        return (
          <Item
            span={it?.span ? it?.span : fields[i + 1]?.valueType == 'split' ? 3 : 1}
            key={it.dataIndex}
            label={it.title}
            {...dataIndexs}
          >
            {it?.render ? it?.render?.(curitem[it.dataIndex], curitem) : ''}
          </Item>
        );
      })}
    </ProDescriptions>
  );
}

DetailPro.propTypes = {
  detailpath: PropTypes.string,
  params: PropTypes.object,
  detailData: PropTypes.object,
  fields: PropTypes.array,
};

export default DetailPro;
