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 [editablePerm, setEditablePerm] = useState(false);
  const [infoEditable, setInfoEditable] = useState(false);
  const [priceEditable, setPriceEditable] = 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);

    setEditablePerm(topPerm || hasEditPer);
    // setEditable(topPerm || (hasAuditPer ? true : (!hasHT && hasEditPer)));
    // setEditable(true); // debug: 0
    // console.log('editable', hasAuditPer, (notAudit && hasEditPer));
    setInfoEditable(topPerm || (!hasHT && hasEditPer));

    const _priceEditable = [-1, 3].includes(activeAgency?.audit_state_id);
    setPriceEditable(topPerm || (_priceEditable && hasEditPer));

    const showExtras = topPerm && hasHT; // !isEmpty(editingProduct) &&
    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 = {
      ...(topPerm ? {} : { '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": "",
    };
    const copyFields = pick(editingProduct.info, ['product_type_id']); // 'title',
    const readyToSubInfo = { ...copyNewProduct.info, ...editingProduct.info, ...values.info, ...copyFields, type: copyFields.product_type_id, ...poster };
    readyToSubInfo.dept = Number(readyToSubInfo.dept);
    // console.log('onSave', editingProduct.info, readyToSubInfo);
    /** lgc_details */
    const prevLgcDetailsMapped = editingProduct.lgc_details.reduce((r, c) => ({ ...r, [c.lgc]: { ...c, description: c.descriptions } }), {});
    const mergedLgc = { ...prevLgcDetailsMapped, ...values.lgc_details_mapped };

    // 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: values.quotation.map((q) => ({ ...q, unit: Number(q.unit || q.unit_id), unit_id: Number(q.unit_id) })), // || editingProduct.quotation, // 没改动, 就用原来的
    }).catch((ex) => {
      setLoading(false);
      notification.error({
        message: 'Notification',
        description: ex.message,
        placement: 'top',
        duration: 4,
      });
    });
    setLoading(false);
    success ? message.success(t('Success')) : message.error(t('Failed'));
    // 保存后更新数据
    // result.quotation = isEmpty(result.quotation) ? editingProduct.quotation : result.quotation;
    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' />
      {isEmpty(editingProduct) ? null : (
        <>
          <h2>{t('products:EditComponents.info')}</h2>
          <ProductInfoForm {...{ editablePerm, infoEditable, priceEditable }} initialValues={editingProduct?.info} onSubmit={onSave} />
          <Divider className='my-1' />
          {extrasVisible && <Extras productId={editingProduct?.info?.id} />}
        </>
      )}
    </>
  );
};
export default ProductInfo;
