import { useEffect, useState } from 'react';
import { App, Breadcrumb, Divider } from 'antd';
import { useTranslation } from 'react-i18next';
import { useProductsTypesMapVal, useNewProductRecord } from '@/hooks/useProductsSets';
import useProductsStore, { postProductsSaveAction } from '@/stores/Products/Index';
import useAuthStore from '@/stores/Auth';
import { PERM_PRODUCTS_MANAGEMENT, PERM_PRODUCTS_OFFER_PUT } from '@/config';
import { isEmpty, pick } from '@/utils/commons';
import ProductInfoForm from './ProductInfoForm';
import { usingStorage } from '@/hooks/usingStorage';
import Extras from './Extras';

const ProductInfo = ({ ...props }) => {
  const { t } = useTranslation();
  const { notification, message } = App.useApp();
  const { userId } = usingStorage();
  const isPermitted = useAuthStore((state) => state.isPermitted);
  const productsTypesMapVal = useProductsTypesMapVal();
  const newProductRecord = useNewProductRecord();

  const [loading, setLoading, appendNewProduct] = useProductsStore((state) => [state.loading, state.setLoading, state.appendNewProduct]);
  const [activeAgency, editingProduct, setEditingProduct] = useProductsStore((state) => [state.activeAgency, state.editingProduct, state.setEditingProduct]);

  const [extrasVisible, setExtrasVisible] = useState(false);
  const [editable, setEditable] = useState(false);
  const topPerm = isPermitted(PERM_PRODUCTS_MANAGEMENT); // 高级权限
  useEffect(() => {
    const hasHT = (editingProduct?.info?.htid || 0) > 0;
    // const hasAuditPer = isPermitted(PERM_PRODUCTS_OFFER_AUDIT);
    const hasEditPer = isPermitted(PERM_PRODUCTS_OFFER_PUT);
    setEditable(topPerm || (!hasHT && hasEditPer));
    // setEditable(topPerm || (hasAuditPer ? true : (!hasHT && hasEditPer)));
    // setEditable(true); // debug: 0
    // console.log('editable', hasAuditPer, (notAudit && hasEditPer));

    const showExtras = topPerm && !isEmpty(editingProduct) && hasHT;
    setExtrasVisible(showExtras);
    return () => {};
  }, [activeAgency, editingProduct]);

  const onSave = async (err, values, forms) => {
    values.travel_agency_id = activeAgency.travel_agency_id;
    const copyNewProduct = structuredClone(newProductRecord);
    const poster = {
      'audit_state': '-1',
      // "create_date": dayjs().format('YYYY-MM-DD HH:mm:ss'),
      // "created_by": userId,
      'travel_agency_id': activeAgency.travel_agency_id,
      // "travel_agency_name": "",
      // "lastedit_changed": "",
    };
    /** lgc_details */
    const copyFields = pick(editingProduct.info, ['product_type_id']); // 'title',
    const readyToSubInfo = { ...copyNewProduct.info, ...editingProduct.info, ...values.info, ...copyFields, type: copyFields.product_type_id, ...poster };
    // console.log('onSave', editingProduct.info, readyToSubInfo);
    const prevLgcDetailsMapped = editingProduct.lgc_details.reduce((r, c) => ({ ...r, [c.lgc]: { ...c, description: c.descriptions } }), {}); // todo: description字段不一致
    const mergedLgc = { ...prevLgcDetailsMapped, ...values.lgc_details_mapped };

    /** quotation */
    const prevQuotationMapped = editingProduct.quotation.reduce((r, c) => ({ ...r, [c.id]: { ...c, unit: c.unit_id, audit_state: c.audit_state_id } }), {});
    const mergedQ = { ...prevQuotationMapped, ...(values.quotation || []) };
    // console.log(values);
    // return false; // debug: 0
    /** 提交保存 */
    setLoading(true);
    const { success, result } = await postProductsSaveAction({
      travel_agency_id: activeAgency.travel_agency_id,
      info: readyToSubInfo,
      lgc_details: Object.values(mergedLgc),
      quotation: Object.values(mergedQ),
    });
    setLoading(false);
    success ? message.success(t('Success')) : message.error(t('Failed'));
    // 保存后更新数据
    appendNewProduct(result);
    setEditingProduct(result);
  };
  return (
    <>
      <Breadcrumb
        items={[
          { title: productsTypesMapVal[editingProduct?.info?.product_type_id]?.label || editingProduct?.info?.product_type_name },
          { title: editingProduct?.info?.title ?? t('New') },
        ]}
      />
      <Divider className='my-1' />
      <h2>{t('products:EditComponents.info')}</h2>
      <ProductInfoForm editable={editable} initialValues={editingProduct?.info} onSubmit={onSave} />
      <Divider className='my-1' />
      {extrasVisible && <Extras productId={editingProduct?.info?.id} />}
    </>
  );
};
export default ProductInfo;
