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 onSubmit = async () => {
    const value = await form.validateFields();
    if (!value?.data?.length) return;
    const params = {
      productId,
      skus: value.data,
    };
    setLoading(true);
    await apiProductBiddingUpdate(params);
    setLoading(false);
    options.refresh();
    options.onCancel();
  };

  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="修改供货价"
      open={visible}
      onCancel={options.onCancel}
      onOk={onSubmit}
      confirmLoading={loading}
      width={800}
      className={styles.priceStockTable}
      destroyOnClose
    >
      <div className={styles.modalTitle}>SPU名称：{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>
    </Modal>
  );
};

export default UpdatePriceStock;
