import { Input, Modal, Button, Form, Table } from 'antd';
import React, {
  useContext,
  createContext,
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { ServiceContext } from '../context';
import { CreateFormInput } from './CommonTemplate';
import { debounce } from '@/utils/utils';

const UpdateSkuName = ({ skuVisble, value, confirmEvent, cancelEvent }) => {
  const [skuForm] = Form.useForm();

  const handleCancel = () => {
    skuForm.resetFields();
    cancelEvent();
  };
  const handleSaveEvent = async () => {
    try {
      const result = await skuForm.validateFields();
      confirmEvent({ skuName: result.skuName, rowIndex: value.rowIndex });
      handleCancel();
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <Modal title={$t('edit.sku.name')} visible={skuVisble} onOk={handleSaveEvent} onCancel={handleCancel}>
      <Form form={skuForm} name="skuRegister">
        <Form.Item
          label={$t('sku.name')}
          key="skuName"
          name="skuName"
          initialValue={value.skuName}
          rules={[{ required: true, message: $t('enter.sku.name') }]}
        >
          <Input.TextArea autoSize={{ minRows: 2, maxRows: 6 }} allowClear />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const EditableContext = createContext(null);
const EditFormTable = forwardRef((props, ref) => {
  const { initData, defaultColumns, setTableData, mergeTable } = props;
  const customer = useContext(ServiceContext);
  const [dataSource, setDataSource] = useState([]);
  const [skuVisble, setSkuVisble] = useState(false);
  const [skuNameItem, setSkuNameItem] = useState({
    skuName: '',
    rowIndex: null,
  });
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({
      tableList: initData,
    });
    setDataSource([...initData]);
  }, [initData]);

  const getValues = () =>
    [...dataSource].map(item => {
      const { rowSpanCount, option, ...childItem } = item;
      return childItem;
    });

  const onCheck = async () => {
    try {
      await form.validateFields();
      return getValues();
    } catch (errorInfo) {
      console.log(errorInfo);
      return null;
    }
  };

  const getFormValues = debounce(() => {
    props.onValuesChange();
  }, 400);

  const handleSave = (value, dataIndex, rowIndex) => {
    const dataList = [...dataSource];
    dataList[rowIndex][dataIndex] = value;
    setDataSource([...dataList]);
    getFormValues();
  };

  const rowOnClickEvent = row => {
    setSkuVisble(true);
    setSkuNameItem({
      skuName: row.name,
      rowIndex: row.rowIndex,
    });
  };

  const cancelEvent = () => {
    setSkuVisble(false);
  };

  const confirmEvent = skuItem => {
    const newDataSource = [...dataSource];
    newDataSource[skuItem.rowIndex].name = skuItem.skuName;
    setDataSource(newDataSource);
    form.setFieldsValue({
      tableList: newDataSource,
    });
  };
  const onClickEvent = (type, row) => {
    // 点击拉取京东图片功能
    if (type === 'cloneImg') {
      customer.onEventBus(type, row);
      return;
    }

    // 修改sku名称
    if (type === 'updateName') {
      rowOnClickEvent(row);
    }
  };

  useImperativeHandle(ref, () => ({
    onCheck,
    form,
    getValues,
  }));
  // 根据这里做判断渲染表格
  const columns = defaultColumns
    .filter(item => !item.role || item.role.includes(customer.productType))
    .map((col, colIndex) => ({
      ...col,
      align: 'center',
      render(text, record, rowIndex) {
        const {
          dataIndex,
          title,
          editable,
          roleRules = {},
          roleProps = {},
          inputType,
          ...otherParams
        } = col;
        const disabled = Boolean(col.disabeldRender ? col.disabeldRender(record) : false);
        const childrenElement = (
          <Form.Item
            style={{ margin: 0 }}
            key={`${dataIndex}_${rowIndex}`}
            name={['tableList', rowIndex, dataIndex]}
            initialValue={record[dataIndex] || null}
            rules={[{ required: roleRules.required, message: `请输入${title}.` }]}
          >
            <CreateFormInput
              {...otherParams}
              title={title}
              type={inputType}
              record={record}
              rowIndex={rowIndex}
              roleProps={roleProps}
              dataIndex={dataIndex}
              disabled={disabled}
              onBlurEvent={handleSave}
              onClickEvent={onClickEvent}
            />
          </Form.Item>
        );
        const rowProps = { children: childrenElement, props: {} };
        if (dataIndex === 'firstSpecValue' && mergeTable) {
          const rowSpan = record.rowSpanCount;
          rowProps.props.rowSpan = rowSpan || 0;
        }
        return rowProps;
      },
    }));

  return (
    <>
      <Form form={form} scrollToFirstError component={false} onValuesChange={getFormValues}>
        <EditableContext.Provider value={form}>
          <Table
            scroll={{ y: 320, x: 1000 }}
            height={320}
            pagination={false}
            size="small"
            bordered
            rowKey={(record, i) => i}
            dataSource={dataSource}
            columns={columns}
          />
        </EditableContext.Provider>
      </Form>
      <Button onClick={() => {}}></Button>
      <UpdateSkuName
        skuVisble={skuVisble}
        form={form}
        value={skuNameItem}
        confirmEvent={confirmEvent}
        cancelEvent={cancelEvent}
      />
    </>
  );
});

export default EditFormTable;
