import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Button, Drawer, Card, Table } from 'antd';
import { useTranslation } from 'react-i18next';
import useProductsStore, { getAgencyAllExtrasAction } from '@/stores/Products/Index';
import { useProductsTypes, formatGroupSize, useProductsTypesMapVal } from '@/hooks/useProductsSets';
import { chunkBy, splitTable_6, splitTable_7, splitTable_8, splitTable_B, splitTable_D, splitTable_J, splitTable_Q, splitTable_R } from '@/hooks/useProductsQuotationFormat';
import { groupBy, isNotEmpty } from '@/utils/commons';
import useAuthStore from '@/stores/Auth';
import { PERM_PRODUCTS_MANAGEMENT, PERM_PRODUCTS_OFFER_AUDIT, PERM_PRODUCTS_OFFER_PUT } from '@/config';
import ExportDocxBtn from './ExportDocxBtn';

const AgencyPreview = ({ params, ...props }) => {
  const isPermitted = useAuthStore(state => state.isPermitted);

  const { t } = useTranslation();
  const { travel_agency_id, use_year } = params;
  const productsTypes = useProductsTypes();

  const [agencyProducts] = useProductsStore((state) => [state.agencyProducts]);
  const [setEditingProduct] = useProductsStore((state) => [state.setEditingProduct]);

  const productsTypesMapVal = useProductsTypesMapVal();

  const [previewMode, setPreviewMode] = useState(false);
  const [tables, setTables] = useState([]);
  const [extras, setExtras] = useState([]);

  const handlePreview = async () => {
    setPreviewMode(true);

    const agencyExtras = await getAgencyAllExtrasAction(params);
    setExtras(agencyExtras);
    // console.log(agencyExtras)

    // 只显示有产品的类型; 展开产品的价格表, 合并名称列; 转化为价格主表, 携带产品属性信息
    const hasDataTypes = Object.keys(agencyProducts);
    const _show = productsTypes
      .filter((kk) => hasDataTypes.includes(kk.value))
      .map((typeKey) => {
        const typeProducts = agencyProducts[typeKey.value];
        const chunked = chunkBy(use_year, typeProducts);
        // console.log(typeKey.label, chunked);
        // return {...chunked, typeKey};
        const { SSRange, PSRange, SSsizeSetKey, SSsizeSetsMap, chunk } = chunked;
        const bySizeSetKey = groupBy(chunk, 'sizeSetsSS'); // next: city
        // return bySizeSetKey
        const tables = Object.keys(bySizeSetKey).map((sizeSetsStr) => {
          const _thisSSsetProducts = bySizeSetKey[sizeSetsStr];
          return { cols: SSsizeSetsMap[sizeSetsStr], colsKey: sizeSetsStr, data: _thisSSsetProducts };
        });
        return { tables, typeKey };
      });
    // console.log(_show);
    setTables(_show);

    // const chunkR = chunkBy(use_year, agencyProducts['D'], []); // 'city_id',
    // console.log(chunkR);
  };

  const cityRowHighlights = (record) => (record.info.isCityRow ? 'font-bold text-center ' : '')

  const renderTitle = (text, r) => {
    const title = text || r.lgc_details?.['2']?.title || r.lgc_details?.['1']?.title || '';
    const itemLink = isPermitted(PERM_PRODUCTS_OFFER_AUDIT)
      ? `/products/${travel_agency_id}/${use_year}/all/edit`
      : isPermitted(PERM_PRODUCTS_OFFER_PUT)
      ? `/products/edit`
      : '';
    return (
      <div className=''>
        {isNotEmpty(itemLink) && (r.info?.isCityRow !== true) ? (
          <div className='' onClick={() => setEditingProduct({ info: r.info })}>
            <Link to={itemLink}>{title}</Link>
          </div>
        ) : (
          title
        )}
        <b>{r.info.id}</b>
      </div>
    );
  };

  const renderTable_6 = () => {
    // console.log('666666');
    if (!('6' in agencyProducts)) {
      return null;
    }
    const {tables, SSRange} = splitTable_6(use_year, agencyProducts['6'], false);
    const table2Rows = tables.reduce((acc, {info, SS}) => {
      return acc.concat(SS.map((v, i) => ({...v, info, rowSpan: i===0 ? SS.length : 0})));
    }, []);
    // console.log('tablesQuote', tablesQuote)
    // console.log('table2Rows', table2Rows)
    return (
      <>
        <Table
          bordered
          striped
          sticky={{ offsetHeader: -24 }}
          key={'ti6'}
          rowKey={'rowKey'}
          dataSource={table2Rows}
          size={'small'}
          pagination={false}
          scroll={{ x: 'max-content' }}
          // className='mt-4'
          columns={[
            {
              title: '综费项目',
              dataIndex: ['info', 'product_title'],
              key: 'product_title',
              width: '12rem',
              onCell: (record) => {
                return { rowSpan: record.rowSpan };
              },
            },
            {
              title: '人等',
              dataIndex: 'dateText',
              key: 'dateText',
              width: '5rem',
              render: (_, r) => <div>{formatGroupSize(r.group_size_min, r.group_size_max, true)}</div>,
            },
            {
              title: (
                <>
                  {SSRange.map((v) => (
                    <div key={v}>{v}</div>
                  ))}
                </>
              ),
              dataIndex: 'SS',
              key: 'SS',
              width: '9rem',
              align: 'center',
              children: [
                {
                  title: '成人',
                  dataIndex: ['adult_cost'],
                  key: 'adult_cost',
                  width: '9rem',
                  align: 'center',
                  onCell: (r) => {
                    const text = r?.adult_cost;
                    const _warning = r.info?.isCityRow !== true && text && r?.unit_id !== '0';

                    return { className: _warning ? 'bg-yellow-100' : '' };
                  },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r?.unit_id !== '0';
                        // && r?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r.unit_name}` : ''}
                        </>
                      );
                    },
                },
                {
                  title: '儿童',
                  dataIndex: ['child_cost'],
                  key: 'child_cost',
                  width: '9rem',
                  align: 'center',
                  onCell: (r) => {
                    const text = r?.adult_cost;
                    const _warning = r.info?.isCityRow !== true && text && r?.unit_id !== '0';

                    return { className: _warning ? 'bg-yellow-100' : '' };
                  },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r?.unit_id !== '0';
                        // && r?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r.unit_name}` : ''}
                        </>
                      );
                    },
                },
              ],
            },
          ]}
        />
      </>
    );
  };

  const renderTable_B = () => {
    // console.log('BBBBBBBBBBBB');
    if (!('B' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_B(use_year, agencyProducts.B);
    // console.log(tablesQuote)
    return (
      <>
        {tablesQuote.map(({ cols, colsKey, data }, ti) => (
          <Table
            bordered
            striped
            sticky={{ offsetHeader: -24 }}
            key={colsKey}
            rowKey={'rowKey'}
            rowClassName={cityRowHighlights}
            columns={[
              {
                title: '超公里项目' + ` (${ti + 1})`,
                dataIndex: ['info', 'product_title'],
                key: 'product_title',
                width: '12rem',
                maxWidth: '12rem',
                className: 'max-w-48',
                fixed: 'left',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '往返公里数',
                dataIndex: ['info', 'km'],
                key: 'product_title',
                width: '6rem',
                maxWidth: '6rem',
                className: 'max-w-4',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '时段',
                dataIndex: 'dateText',
                key: 'dateText',
                width: '5rem',
                fixed: 'left',
                render: (_, { quote_season, use_dates_start, use_dates_end, rowSpan }) =>
                  quote_season === 'SS' ? (
                    rowSpan > 1 ? (
                      <div>
                        平季<div>(除特殊时段外)</div>
                      </div>
                    ) : (
                      ''
                    )
                  ) : (
                    <div>
                      特殊时段
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  ),
              },
              ...cols.map((col) => ({
                title: formatGroupSize(...col),
                // dataIndex: [formatGroupSize(...col), 'adult_cost'],
                key: col[0],
                children: [
                  {
                    title: '成人',
                    dataIndex: [formatGroupSize(...col), 'adult_cost'],
                    key: 'adult_cost',
                    width: '4rem',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.adult_cost;
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '0';

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                  {
                    title: '儿童',
                    dataIndex: [formatGroupSize(...col), 'child_cost'],
                    key: 'child_cost',
                    width: '4rem',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.child_cost;
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '0';

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                ],
              })),
            ]}
            dataSource={data}
            size={'small'}
            pagination={false}
            scroll={{ x: 'max-content' }}
          />
        ))}
      </>
    );
  };

  const renderTable_J = () => {
    // console.clear();
    // console.log('jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj');
    if (!('J' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_J(use_year, agencyProducts.J);
    // console.log(tablesQuote)
    return (
      <>
        {tablesQuote.map(({ cols, colsKey, data }, ti) => (
          <Table
            bordered
            striped
            sticky={{ offsetHeader: -24 }}
            key={colsKey}
            rowKey={'rowKey'}
            rowClassName={cityRowHighlights}
            columns={[
              {
                title: '车费项目'+` (${ti+1})`,
                dataIndex: ['info', 'product_title'],
                key: 'product_title',
                width: '12rem',
                fixed: 'left',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '时段',
                dataIndex: 'dateText',
                key: 'dateText',
                width: '9rem',
                fixed: 'left',
                render: (_, { quote_season, use_dates_start, use_dates_end, rowSpan }) =>
                  quote_season === 'SS' ? (
                    rowSpan > 1 ? (
                      <div key={'ss'}>
                        平季<div>(除特殊时段外)</div>
                      </div>
                    ) : (
                      ''
                    )
                  ) : (
                    <div key={'ps'}>
                      特殊时段
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  ),
              },
              ...cols.map((col) => ({
                title: formatGroupSize(...col),
                // dataIndex: [formatGroupSize(...col), 'adult_cost'],
                key: col[0],
                children: [
                  {
                    title: '成人',
                    dataIndex: [formatGroupSize(...col), 'adult_cost'],
                    key: 'adult_cost',
                    width: '4rem',
                    onCell: (r, ) => {
                      const text = r[formatGroupSize(...col)]?.adult_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                  {
                    title: '儿童',
                    dataIndex: [formatGroupSize(...col), 'child_cost'],
                    key: 'child_cost',
                    width: '4rem',
                    onCell: (r, ) => {
                      const text = r[formatGroupSize(...col)]?.child_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;
                      return  (
                          <>
                            {text}
                            {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                          </>
                        );
                    },
                  },
                ],
              })),
            ]}
            dataSource={data}
            size={'small'}
            pagination={false}
            scroll={{ x: 'max-content' }}
            // className='mt-4'
          />
        ))}
      </>
    );
  };

  const renderTable_D = () => {
    // console.clear();
    // console.log('DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD');
    if (!('D' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_D(use_year, agencyProducts.D);
    // console.log(tablesQuote)
    return (
      <>
        {tablesQuote.map(({ cols, colsKey, data }, ti) => (
          <Table
            bordered
            striped
            sticky={{ offsetHeader: -24 }}
            key={colsKey}
            rowKey={'rowKey'}
            rowClassName={cityRowHighlights}
            columns={[
              {
                title: '包价线路项目'+` (${ti+1})`,
                dataIndex: ['info', 'product_title'],
                key: 'product_title',
                width: '12rem',
                fixed: 'left',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '时段',
                dataIndex: 'dateText',
                key: 'dateText',
                width: '9rem',
                fixed: 'left',
                render: (_, { quote_season, use_dates_start, use_dates_end, rowSpan }) =>
                  quote_season === 'SS' ? ((rowSpan === 1) ? '' : (
                    <div>
                      平季<div>(除特殊时段外)</div>
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  )) : (
                    <div>
                      特殊时段
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  ),
              },
              ...cols.map((col) => ({
                title: formatGroupSize(...col),
                // dataIndex: [formatGroupSize(...col), 'adult_cost'],
                key: col[0],
                // children1: [
                //   { title: '成人', dataIndex: [formatGroupSize(...col), 'adult_cost'], key: 'adult_cost' },
                //   { title: '儿童', dataIndex: [formatGroupSize(...col), 'child_cost'], key: 'child_cost' },
                // ],
                children: [
                  {
                    title: '成人',
                    dataIndex: [formatGroupSize(...col), 'adult_cost'],
                    key: 'adult_cost',
                    width: '4rem',
                    onCell: (r, ) => {
                      const text = r[formatGroupSize(...col)]?.adult_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;
                      return  (
                          <>
                            {text}
                            {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                          </>
                        );
                    },
                  },
                  {
                    title: '儿童',
                    dataIndex: [formatGroupSize(...col), 'child_cost'],
                    key: 'child_cost',
                    width: '4rem',
                    onCell: (r, ) => {
                      const text = r[formatGroupSize(...col)]?.child_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '1';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;
                      return  (
                          <>
                            {text}
                            {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                          </>
                        );
                    },
                  },
                ]
              })),
            ]}
            dataSource={data}
            size={'small'}
            pagination={false}
            scroll={{ x: 'max-content' }}
            // className='mt-4'
          />
        ))}
      </>
    );
  };

  /**
   * 导游
   */
  const renderTable_Q = () => {
    // console.log('QQQQQQ');
    if (!('Q' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_Q(use_year, agencyProducts.Q);
    // console.log('tablesQuote', tablesQuote);
    return (
      <>
        <Table
          bordered
          striped
          sticky={{ offsetHeader: -24 }}
          key={'ti'}
          rowKey={'rowKey'}
          dataSource={tablesQuote}
          size={'small'}
          pagination={false}
          scroll={{ x: 'max-content' }}
          rowClassName={cityRowHighlights}
          columns={[
            {
              title: '导游项目',
              dataIndex: ['info', 'product_title'],
              key: 'product_title',
              width: '12rem',
              // onCell: (record) => {
              //   return { rowSpan: record.rowSpan };
              // },
            },
            {
              title: '平季(除特殊时段外)',
              dataIndex: 'SS',
              key: 'SS',
              width: '9rem',
              children: [
                {
                  title: '成人',
                  dataIndex: [0, 'adult_cost'],
                  key: 'adult_cost',
                  width: '9rem', align: 'center',
                  render: (_, { SS }) => (
                    <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                      {(SS || []).length === 1 ? (
                        <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                          <span className={`flex-1 text-center ${SS[0].unit_id !== '1' ? 'bg-yellow-100' : ''}`}>{SS[0].adult_cost}{SS[0].unit_id !== '1' ? ` /${SS[0].unit_name}` : ''}</span>
                        </div>
                      ) : (
                        (SS || []).map((ele, qi) => (
                          <div key={qi} className=''>
                            <div className='flex justify-between text-center divide-x divide-y-0 divide-solid divide-stone-200'>
                              <span className='flex-0 w-32 text-start'>
                                {formatGroupSize(ele.group_size_min, ele.group_size_max, true)}, {ele.unit_name}
                              </span>
                              <span className={`flex-1`}>{ele.adult_cost}</span>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  ),
                },
                {
                  title: '儿童',
                  dataIndex: [0, 'child_cost'],
                  key: 'child_cost',
                  width: '9rem', align: 'center',
                  render: (_, { SS }) => (
                    <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                      {(SS || []).length === 1 ? (
                        <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                          <span className={`flex-1 text-center ${SS[0].unit_id !== '1' ? 'bg-yellow-100' : ''}`}>{SS[0].child_cost}{SS[0].unit_id !== '1' ? ` /${SS[0].unit_name}` : ''}</span>
                        </div>
                      ) : (
                        (SS || []).map((ele, qi) => (
                          <div key={qi} className=''>
                            <div className='flex justify-between text-center divide-x divide-y-0 divide-solid divide-stone-200'>
                              <span className='flex-0 w-32 text-start'>
                                {formatGroupSize(ele.group_size_min, ele.group_size_max, true)}, {ele.unit_name}
                              </span>
                              <span className='flex-1'>{ele.child_cost}</span>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  ),
                },
              ],
            },
            {
              title: '旺季',
              dataIndex: 'PS',
              key: 'PS',
              width: '9rem',
              children: [
                {
                  title: '成人',
                  dataIndex: [0, 'adult_cost'],
                  key: 'adult_cost',
                  width: '9rem', align: 'center',
                  render: (_, { PS }) => (
                    <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                      {(PS || []).map((ele, pi) => (
                        <div key={pi} className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                          <div className='flex-1 self-center'>
                            {ele.rows.map((d, di) => (
                                <div key={di}>
                                  {d.use_dates_start.replace(`${use_year}.`, '')}~{d.use_dates_end.replace(`${use_year}.`, '')}
                                </div>
                              ))}
                          </div>
                          <span className={`flex-1 self-center ${ele.unit_id !== '1' ? 'bg-yellow-100' : ''}`}>{ele.adult_cost}{ele.unit_id !== '1' ? ` /${ele.unit_name}` : ''}</span>
                        </div>
                      ))}
                    </div>
                  ),
                  // // 表格形式
                  // render: (_, { PSData }) => (
                  //   <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                  //     {(PSData || []).map((ele, pi) => (
                  //       <div key={pi} className='divide-x-0 divide-y divide-solid divide-stone-200'>
                  //         <div className='flex-0 text-center w-24-'>
                  //           {ele.headerDates.map((d, di) => (
                  //             <div key={di}>
                  //               {d.use_dates_start.replace(`${use_year}.`, '')}~{d.use_dates_end.replace(`${use_year}.`, '')}
                  //             </div>
                  //           ))}
                  //         </div>
                  //         {ele.rows.map((qrow, qri) => (
                  //           <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200' key={qrow.id}>
                  //             <span className='flex-0 w-16 text-start self-center'>{formatGroupSize(qrow.group_size_min, qrow.group_size_max, true)}</span>
                  //             <span className='flex-0 w-10 self-center'>{qrow.unit_name}</span>
                  //             <span className='flex-1 self-center'>{qrow.adult_cost}</span>
                  //           </div>
                  //         ))}
                  //         <div></div>
                  //       </div>
                  //     ))}
                  //   </div>
                  // ),
                },
                {
                  title: '儿童',
                  dataIndex: [0, 'child_cost'],
                  key: 'child_cost',
                  width: '9rem', align: 'center',
                  render: (_, { PS }) => (
                    <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                      {(PS || []).map((ele, pi) => (
                        <div key={pi} className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                          <div className='flex-1 self-center'>
                            {ele.rows.map((d, di) => (
                              <div key={di}>
                                {d.use_dates_start.replace(`${use_year}.`, '')}~{d.use_dates_end.replace(`${use_year}.`, '')}
                              </div>
                            ))}
                          </div>
                          <span className={`flex-1 self-center ${ele.unit_id !== '1' ? 'bg-yellow-100' : ''}`}>{ele.child_cost}{ele.unit_id !== '1' ? ` /${ele.unit_name}` : ''}</span>
                        </div>
                      ))}
                    </div>
                  ),
                },
              ],
            },
          ]}
        />
      </>
    );
  };

  /**
   * 景点
   */
  const renderTable_7 = () => {
    // console.log('7777777777777');
    if (!('7' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_7(use_year, agencyProducts['7']);
    // console.log('tableQuote', tablesQuote)
    return (
      <>
        <Table
          bordered
          striped
          sticky={{ offsetHeader: -24 }}
          key={'ti'}
          rowKey={'rowKey'}
          dataSource={tablesQuote}
          size={'small'}
          pagination={false}
          scroll={{ x: 'max-content' }}
          // className=''
          rowClassName={cityRowHighlights}
          columns={[
            {
              title: '景点项目',
              dataIndex: ['info', 'product_title'],
              key: 'product_title',
              width: '12rem',
              // onCell: (record) => {
              //   return { rowSpan: record.rowSpan };
              // },
            },
            {
              title: (
                <>
                  平季(除特殊时段外)
                  <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                    <span className='flex-0 text-center w-32'>-</span>
                    <span className='flex-1 text-center'>成人</span>
                    <span className='flex-1 text-center'>儿童</span>
                  </div>
                </>
              ),
              dataIndex: 'SS',
              key: 'SS',
              width: '9rem',
              render: (_, { SS }) => (
                <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                  {(SS || []).length === 1 ? (
                    <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                      {SS[0].unit_id === '0' && SS[0].group_size_min <= 1 && SS[0].group_size_max === 1000 ? (
                        <span className='flex-0 text-center w-32'></span>
                      ) : (
                        <>
                          <span className='flex-0 w-16 text-start'>{formatGroupSize(SS[0].group_size_min, SS[0].group_size_max, true)}</span>
                          <span className='flex-0 w-16 text-center'>{SS[0].unit_name}</span>
                        </>
                      )}
                      <span className='flex-1 text-center'>{SS[0].adult_cost}</span>
                      <span className='flex-1 text-center'>{SS[0].child_cost}</span>
                    </div>
                  ) : (
                    (SS || []).map((ele, qi) => (
                      <div key={qi} className=''>
                        <div className='flex justify-between text-center divide-x divide-y-0 divide-solid divide-stone-200'>
                          <span className='flex-0 w-16 text-start'>{formatGroupSize(ele.group_size_min, ele.group_size_max, true)}</span>
                          <span className='flex-0 w-16'>{ele.unit_name}</span>
                          <span className='flex-1'>{ele.adult_cost}</span>
                          <span className='flex-1'>{ele.child_cost}</span>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              ),
            },
            {
              title: (
                <>
                  旺季
                  <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200'>
                    <span className='flex-0 text-center w-24'>-</span>
                    <span className='flex-1'>成人</span>
                    <span className='flex-1'>儿童</span>
                  </div>
                </>
              ),
              dataIndex: 'PS',
              key: 'PS',
              width: '9rem',
              align: 'center',
              render: (_, { PSData }) => (
                <div className='divide-x-0 divide-y divide-solid divide-stone-200'>
                  {(PSData || []).map((ele, pi) => (
                    <div key={pi} className='divide-x-0 divide-y divide-solid divide-stone-200'>
                      <div className='flex-0 text-center w-24-'>
                        {ele.headerDates.map((d, di) => (
                          <div key={di}>
                            {d.use_dates_start.replace(`${use_year}.`, '')}~{d.use_dates_end.replace(`${use_year}.`, '')}
                          </div>
                        ))}
                      </div>
                      {ele.rows.map((qrow, qri) => (
                        <div className='flex justify-between divide-x divide-y-0 divide-solid divide-stone-200' key={qrow.id}>
                          <span className='flex-0 w-16 text-start self-center'>{formatGroupSize(qrow.group_size_min, qrow.group_size_max, true)}</span>
                          <span className='flex-0 w-8 self-center'>{qrow.unit_name}</span>
                          <span className='flex-1 self-center'>{qrow.adult_cost}</span>
                          <span className='flex-1 self-center'>{qrow.child_cost}</span>
                        </div>
                      ))}
                      <div></div>
                    </div>
                  ))}
                </div>
              ),
            },
            {
              title: '特殊项目',
              width: '9rem',
              key: 'extras',
              render: (_, r) => {
                const _extras = extras[r.info.id] || [];
                return (
                  <div>
                    {_extras.map((e) => (
                      <div key={e.info.id}>
                        {e.info.product_title}【{productsTypesMapVal[e.info.product_type_id]?.label || (e.info.product_type_name)}】
                      </div>
                    ))}
                  </div>
                );
              },
            },
          ]}
        />
      </>
    );
  };

  const renderTable_R = () => {
    // console.log('RRRRRRRRRRRRR');
    if (!('R' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_R(use_year, agencyProducts.R);
    return (
      <>
        {tablesQuote.map(({ cols, colsKey, data }, ti) => (
          <Table
            bordered
            striped
            sticky={{ offsetHeader: -24 }}
            key={colsKey}
            rowKey={'rowKey'}
            rowClassName={cityRowHighlights}
            columns={[
              {
                title: '餐费项目'+` (${ti+1})`,
                dataIndex: ['info', 'product_title'],
                key: 'product_title',
                width: '12rem',
                fixed: 'left',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '时段',
                dataIndex: 'dateText',
                key: 'dateText',
                width: '5rem',
                fixed: 'left',
                render: (_, { quote_season, use_dates_start, use_dates_end, rowSpan }) =>
                  quote_season === 'SS' ? (
                    rowSpan > 1 ? (
                      <div>
                        平季<div>(除特殊时段外)</div>
                      </div>
                    ) : (
                      ''
                    )
                  ) : (
                    <div>
                      特殊时段
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  ),
              },
              ...cols.map((col) => ({
                title: formatGroupSize(...col),
                // dataIndex: [formatGroupSize(...col), 'adult_cost'],
                key: col[0],
                children: [
                  {
                    title: '成人',
                    dataIndex: [formatGroupSize(...col), 'adult_cost'],
                    key: 'adult_cost',
                    width: '4rem',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.adult_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                  {
                    title: '儿童',
                    dataIndex: [formatGroupSize(...col), 'child_cost'],
                    key: 'child_cost',
                    width: '4rem',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.child_cost
                      const _warning = r.info?.isCityRow !== true
                        && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text
                        && r[formatGroupSize(...col)]?.unit_id !== '0';
                        // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                ],
              })),
              {
                title: '司陪餐补（元/团/餐）',
                dataIndex: 'extra',
                key: 'extra',
                width: '4rem',
                onCell: (record, index) => {
                  return { rowSpan: index === 0 ? data.length : 0 };
                },
                render: (_) => <>不分人等</>,
              },
            ]}
            dataSource={data}
            size={'small'}
            pagination={false}
            scroll={{ x: 'max-content' }}
          />
        ))}
      </>
    );
  };

  const renderTable_8 = () => {
    // console.clear();
    // console.log('888888');
    if (!('8' in agencyProducts)) {
      return null;
    }
    const tablesQuote = splitTable_8(use_year, agencyProducts['8']);
    // console.log('---- tablesQuote ----', tablesQuote)
    return (
      <>
        {tablesQuote.map(({ cols, colsKey, data }, ti) => (
          <Table
            bordered
            striped
            sticky={{ offsetHeader: -24 }}
            key={colsKey}
            rowKey={'rowKey'}
            rowClassName={cityRowHighlights}
            columns={[
              {
                title: '附加项目' + ` (${ti + 1})`,
                dataIndex: ['info', 'product_title'],
                key: 'product_title',
                width: '12rem',
                maxWidth: '12rem',
                className: 'max-w-48',
                fixed: 'left',
                onCell: (record) => {
                  return { rowSpan: record.rowSpan };
                },
              },
              {
                title: '时段',
                dataIndex: 'dateText',
                key: 'dateText',
                width: '8rem',
                fixed: 'left',
                render: (_, { quote_season, use_dates_start, use_dates_end, rowSpan }) =>
                  quote_season === 'SS' ? (
                    rowSpan > 1 ? (
                      <div>
                        平季<div>(除特殊时段外)</div>
                      </div>
                    ) : (
                      ''
                    )
                  ) : (
                    <div>
                      特殊时段
                      <div>
                        {use_dates_start.replace(`${use_year}.`, '')}~{use_dates_end.replace(`${use_year}.`, '')}
                      </div>
                    </div>
                  ),
              },
              ...cols.map((col) => ({
                title: formatGroupSize(...col),
                // dataIndex: [formatGroupSize(...col), 'adult_cost'],
                key: col[0],
                children: [
                  {
                    title: '成人',
                    dataIndex: [formatGroupSize(...col), 'adult_cost'],
                    key: 'adult_cost',
                    width: '4rem',
                    className: 'max-w-16',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.adult_cost;
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '1';
                      // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '1';
                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                  {
                    title: '儿童',
                    dataIndex: [formatGroupSize(...col), 'child_cost'],
                    key: 'child_cost',
                    width: '4rem',
                    className: 'max-w-16',
                    onCell: (r) => {
                      const text = r[formatGroupSize(...col)]?.child_cost;
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '1';
                      // && r[formatGroupSize(...col)]?.unit_id !== r.unit_id;

                      return { className: _warning ? 'bg-yellow-100' : '' };
                    },
                    render: (text, r) => {
                      const _warning = r.info?.isCityRow !== true && text && r[formatGroupSize(...col)]?.unit_id !== '1';
                      return (
                        <>
                          {text}
                          {_warning ? ` /${r[formatGroupSize(...col)].unit_name}` : ''}
                        </>
                      );
                    },
                  },
                ],
              })),
            ]}
            dataSource={data}
            size={'small'}
            pagination={false}
            scroll={{ x: 'max-content' }}
          />
        ))}
      </>
    );
  }

  const typeTableMap = {
    // '6': { render: () => {} },
    '6': { render: renderTable_6 },
    // 'B': { render: () => {} },
    'B': { render: renderTable_B },
    // 'J': { render: () => {} },
    'J': { render: renderTable_J },
    // 'Q': { render: () => {} },
    'Q': { render: renderTable_Q },
    // '7': { render: () => {} },
    '7': { render: renderTable_7 },
    // 'R': { render: () => {} },
    'R': { render: renderTable_R },
    // '8': { render: () => {} },
    '8': { render: renderTable_8 },
    // 'D': { render: () => {} },
    'D': { render: renderTable_D },
  };

  const renderTableByType = (allTables) => {
    return allTables.map(({ typeKey, tables }) => {
      return (
        <Card title={typeKey.label} key={typeKey.value} className='[&_.ant-card-head]:bg-neutral-200'  >
        <div className='flex flex-col gap-4'>
          {typeTableMap[typeKey.value].render()}
        </div>
        </Card>
      );
    });
  };

  return (
    <>
      <Button size='small' onClick={handlePreview}>
        {t('Preview')}
      </Button>
      <Drawer
        title={
          <>
            <div className='flex gap-4'>
              <span>{t('Preview')}</span>
              <ExportDocxBtn params={params} />
            </div>
          </>
        }
        width={'70%'}
        open={previewMode}
        onClose={() => setPreviewMode(false)}>
        <div className='flex flex-col gap-2'>{renderTableByType(tables)}</div>
      </Drawer>
    </>
  );
};
export default AgencyPreview;
