import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { App, Button, Collapse, Table, Space, Divider } from 'antd';
import { useProductsTypes, useProductsAuditStatesMapVal } from '@/hooks/useProductsSets';
import SecondHeaderWrapper from '@/components/SecondHeaderWrapper';
import { useTranslation } from 'react-i18next';
import useProductsStore, { postProductsQuoteAuditAction, } from '@/stores/Products/Index';
import { isEmpty } from '@/utils/commons';
// import PrintContractPDF from './PrintContractPDF';

const Header = ({ title, agency, refresh, ...props }) => {
  const { travel_agency_id, use_year, audit_state  } = useParams();
  const { t } = useTranslation();
  const [activeAgency] = useProductsStore((state) => [state.activeAgency]);
  const { message, notification } = App.useApp();
  const handleAuditItem = (state, row) => {
    postProductsQuoteAuditAction(state, { id: row.id, travel_agency_id: activeAgency.travel_agency_id })
      .then((json) => {
        if (json.errcode === 0) {
          message.success(json.errmsg);
          if (typeof refresh === 'function') {
            refresh();
          }
        }
      })
      .catch((ex) => {
        notification.error({
          message: 'Notification',
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      });
  };
  return (
    <div className='flex justify-end items-center gap-4 h-full'>
      <div className='grow'>
        <h2 className='m-0 leading-tight'>{title}<Divider type={'vertical'} />{(use_year || '').replace('all', '')}</h2>
      </div>
      {/* <Button size='small'>{t('Copy')}</Button> */}
      {/* <Button size='small'>{t('Import')}</Button> */}
      <Link className='px-2' to={`/products/${travel_agency_id}/${use_year}/${audit_state}/edit`}>{t('Edit')}</Link>
      <Button size='small' type={'primary'} onClick={() => handleAuditItem('2', agency)}>
        {t('products:auditStateAction.Published')}
      </Button>
      {/* <Button size='small' type={'primary'} ghost onClick={() => handleAuditItem('2', agency)}>
        {t('products:auditStateAction.Approved')}
      </Button> */}
      <Button size='small' type={'primary'} danger ghost onClick={() => handleAuditItem('3', agency)}>
        {t('products:auditStateAction.Rejected')}
      </Button>
      {/* todo: export, 审核完成之后才能导出 */}
      <Button size='small'>{t('Print')} PDF</Button>
      {/* <PrintContractPDF /> */}
    </div>
  );
};

const PriceTable = ({ dataSource, refresh }) => {
  const { t } = useTranslation('products');
  const [loading, activeAgency] = useProductsStore((state) => [state.loading, state.activeAgency]);
  const { message, notification } = App.useApp();
  const stateMapVal = useProductsAuditStatesMapVal();

  // console.log(dataSource);

  const handleAuditPriceItem = (state, row) => {
    postProductsQuoteAuditAction(state, { id: row.id, travel_agency_id: activeAgency.travel_agency_id })
      .then((json) => {
        if (json.errcode === 0) {
          message.success(json.errmsg);
          if (typeof refresh === 'function') {
            refresh();
          }
        }
      })
      .catch((ex) => {
        notification.error({
          message: 'Notification',
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      });
  };

  const columns = [
    { key: 'title', dataIndex: ['info', 'title'], width: '16rem', title: t('Title'), onCell: (r, index) => ({ rowSpan: r.rowSpan }), render: (text, r) => text || r.lgc_details?.['2']?.title || '' },
    { key: 'adult', title: t('AgeType.Adult'), render: (_, { value, currency, unit_name }) => `${value} ${currency} / ${unit_name}` },
    { key: 'child', title: t('AgeType.Child'), render: (_, { value, currency, unit_name }) => `${value} ${currency} / ${unit_name}` },
    // {key: 'price', title: t('Currency'), },
    // {key: 'currency', title: t('Currency'), },
    // {key: 'unit', title: t('Unit'), },
    {
      key: 'groupSize',
      dataIndex: ['group_size_min'],
      title: t('GroupSize'),
      render: (_, { group_size_min, group_size_max }) => `${group_size_min} - ${group_size_max}`,
    },
    {
      key: 'useDates',
      dataIndex: ['use_dates_start'],
      title: t('UseDates'),
      render: (_, { use_dates_start, use_dates_end, weekdays }) => `${use_dates_start} ~ ${use_dates_end}`, // + (weekdays ? `, ${t('OnWeekdays')}${weekdays}` : ''),
    },
    { key: 'weekdays', dataIndex: ['weekdays'], title: t('Weekdays'), render: (text, r) => text || t('Unlimited') },
    {
      key: 'state',
      title: t('State'),
      render: (_, r) => {
        return <span className={`text-${stateMapVal[`${r.audit_state_id}`]?.color}`}>{stateMapVal[`${r.audit_state_id}`]?.label}</span>;
      },
    },
    {
      title: '价格审核',
      key: 'action',
      render: (_, r) =>
        r.audit_state_id <= 0 ? (
          <Space>
            <Button onClick={() => handleAuditPriceItem('2', r)}>✔</Button>
            <Button onClick={() => handleAuditPriceItem('3', r)}>✖</Button>
          </Space>
        ) : null,
    },
  ];
  return <Table size={'small'} pagination={false} {...{ columns, dataSource }} rowKey={(r) => r.id} />;
};

/**
 *
 */
const TypesPanels = (props) => {
  const { t } = useTranslation();
  const [loading, agencyProducts] = useProductsStore((state) => [state.loading, state.agencyProducts]);
  // console.log(agencyProducts);
  const productsTypes = useProductsTypes();
  const [activeKey, setActiveKey] = useState([]);
  const [showTypes, setShowTypes] = useState([]);
  useEffect(() => {
    // 只显示有产品的类型; 展开产品的价格表, 合并名称列; 转化为价格主表, 携带产品属性信息
    const hasDataTypes = Object.keys(agencyProducts);
    const _show = productsTypes
      .filter((kk) => hasDataTypes.includes(kk.value))
      .map((ele) => ({
        ...ele,
        extra: t('Table.Total', { total: agencyProducts[ele.value].length }),
        children: (
          <PriceTable
            // loading={loading}
            dataSource={agencyProducts[ele.value].reduce(
              (r, c) =>
                r.concat(
                  c.quotation.map((q, i) => ({
                    ...q,
                    weekdays: q.weekdays
                      .split(',')
                      .filter(Boolean)
                      .map((w) => t(`weekdaysShort.${w}`))
                      .join(', '),
                    info: c.info,
                    lgc_details: c.lgc_details.reduce((rlgc, clgc) => ({...r, [clgc.lgc]: clgc}), {}),
                    rowSpan: i === 0 ? c.quotation.length : 0,
                  }))
                ),
              []
            )}
            refresh={props.refresh}
          />
        ),
      }));
    setShowTypes(_show);

    setActiveKey(isEmpty(_show) ? [] : [_show[0].key]);

    return () => {};
  }, [productsTypes, agencyProducts]);

  const onCollapseChange = (_activeKey) => {
    setActiveKey(_activeKey);
  };
  return <Collapse items={showTypes} activeKey={activeKey} onChange={onCollapseChange} />;
};

const Audit = ({ ...props }) => {
  const { travel_agency_id, use_year, audit_state } = useParams();
  const [loading, activeAgency, getAgencyProducts] = useProductsStore((state) => [state.loading, state.activeAgency, state.getAgencyProducts]);

  const handleGetAgencyProducts = () => {
    getAgencyProducts({ travel_agency_id, use_year, audit_state });
  };

  useEffect(() => {
    handleGetAgencyProducts();

    return () => {};
  }, [travel_agency_id]);

  return (
    <>
      <SecondHeaderWrapper header={<Header title={activeAgency.travel_agency_name} agency={activeAgency} refresh={handleGetAgencyProducts} />} loading={loading} >
        {/* debug: 0 */}
        {/* <PrintContractPDF /> */}

        <TypesPanels refresh={handleGetAgencyProducts} />
      </SecondHeaderWrapper>
    </>
  );
};
export default Audit;
