import React, { useState, createContext, useEffect } from 'react';
import { Modal, Table, Form } from 'antd';
import { column } from '../staticdata';
import styles from '../style.less';
import { apiProductBiddingUpdate } from '../../service';

/**
 * 更新供货价
 * * */
const UpdatePriceStock = options => {
  const { visible, skuData, productId, spuName } = options;
  const [loading, setLoading] = useState(false);
  const [specArr, setSpecArr] = useState([]); // 规格列
  const [form] = Form.useForm();
  const [errorMsg, setErrorMsg] = useState([]); // 错误信息

  const onSubmit = async () => {
    const value = await form.validateFields();
    if (!value?.data?.length) return;
    const params = {
      productId,
      skus: value.data,
    };
    setLoading(true);
    setErrorMsg([]);
    const res = await apiProductBiddingUpdate(params);
    setLoading(false);
    if (res?.success) {
      options.refresh();
      options.onCancel();
    } else {
      const msg = res?.msg || $t('edit.failed');
      setErrorMsg(msg.split(';'));
    }
  };

  const EditableContext = createContext(null);

  useEffect(() => {
    if (options.visible) {
      let firstSpecTitle = '';
      let secondSpecTitle = '';
      const arr = [];
      skuData.forEach(item => {
        if (item.firstSpec && item.firstSpecValue) {
          firstSpecTitle = item.firstSpec;
        }
        if (item.secondSpec && item.secondSpecValue) {
          secondSpecTitle = item.secondSpec;
        }
      });
      if (firstSpecTitle) {
        arr.push({
          title: firstSpecTitle,
          width: 135,
          align: 'center',
          dataIndex: 'firstSpecValue',
        });
      }
      if (secondSpecTitle) {
        arr.push({
          title: secondSpecTitle,
          width: 135,
          align: 'center',
          dataIndex: 'secondSpecValue',
        });
      }
      setSpecArr(arr);
    }
  }, [visible]);

  return (
    <Modal
      title={$t('edit.supply.price')}
      open={visible}
      onCancel={options.onCancel}
      onOk={onSubmit}
      confirmLoading={loading}
      width={900}
      className={styles.priceStockTable}
      destroyOnClose
    >
      <div className={styles.modalTitle}>{$t('spu.name')}{spuName}</div>
      <Form form={form} scrollToFirstError component={false}>
        <EditableContext.Provider value={form}>
          <Table
            className={styles.priceStockTable}
            rowKey="id"
            columns={column.call(this, specArr)}
            dataSource={skuData}
            pagination={false}
          />
        </EditableContext.Provider>
      </Form>
      {errorMsg && (
        <div className={styles.errorMsg}>
          {errorMsg.map(item => (
            <div key={item}>{item}</div>
          ))}
        </div>
      )}
    </Modal>
  );
};

export default UpdatePriceStock;
