import React, { useState, useRef, useContext, useEffect } from 'react';
import { Modal, Form, Table, Input, Button, message, Select, Tag } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import styles from './ParmarsModal.less';
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  dataSource,
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  let keyNameRule = [
    {
      required: true,
      message: `${title}不能为空`,
    },
    {
      validator: (rule, value) => {
        let list = JSON.parse(JSON.stringify(dataSource));
        // 合并内置字段
        if (value && list.some((item, i) => item.field === value && item.key !== record.key)) {
          return Promise.reject(new Error('参数称重复，请重新输入'));
        }
        return Promise.resolve();
      },
    },
  ];
  let rules = dataIndex === 'field' ? keyNameRule : [];
  const rendeFrom = () => {
    if (dataIndex === 'defaultValue' && record.type === '选择型') {
      let options = record.valueDesc
        .split(';')
        .map(item => ({ label: item.split(':')[1], value: item.split(':')[0] }));

      return (
        <Select
          // showSearch
          placeholder="选择值"
          optionFilterProp="children"
          optionLabelProp="value"
          // filterOption={(input, option) =>
          //   (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          // }
          options={options}
          ref={inputRef}
          onPressEnter={save}
          onBlur={save}
        />
      );
    }
    return (
      <Input
        readOnly={record.releaseDate && dataIndex !== 'defaultValue'}
        ref={inputRef}
        onPressEnter={save}
        onBlur={save}
      />
    );
  };
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={rules}
      >
        {rendeFrom()}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
const ParmarsModal = props => {
  const { pageUrl, visible, handleCancel, parmarCallBack, menuParmar, codeParam } = props;
  const [dataSource, setDataSource] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (visible) {
      // 给url通过字符串分割成表单需要的数据形式

      let parmas = pageUrl
        .split('|')[1]
        ?.split('&')
        ?.map((item, index) => {
          let obj = {
            field: item.split('=')[0],
            defaultValue: item.split('=')[1],
          };

          return obj;
        });

      if (!parmas) {
        parmas = [];
      }

      let codeParams = codeParam || [];
      console.log(menuParmar, codeParams, parmas, 'menuParmar');
      let finalArray = [];
      if (menuParmar) {
        finalArray = menuParmar?.concat(codeParams, parmas).reduce((acc, cur) => {
          let existingIndex = acc.findIndex(item => item.field === cur.field);
          if (existingIndex !== -1) {
            acc[existingIndex] = Object.assign(acc[existingIndex], cur);
          } else {
            acc.push(cur);
          }
          return acc;
        }, []);
      } else {
        finalArray = parmas;
      }

      console.log(finalArray.map((item, index) => ({ ...item, key: index })));
      let select = [];
      let newList = finalArray.map((item, index) => {
        if (parmas.some(ele => ele.field === item.field)) {
          select.push(index);
        }
        return { ...item, key: index };
      });
      setCount(finalArray.length);
      setDataSource(newList);
      setSelectedRowKeys(select);
    } else {
      setDataSource([]);
      setSelectedRowKeys([]);
      setCount(0);
    }
  }, [visible]);

  const onFinish = () => {
    console.log(selectedRowKeys, dataSource, 'selectedRowKeys');
    if (dataSource.some(item => !item.field)) {
      message.error('参数名称不能为空');
      return;
    }

    let selectSet = new Set(selectedRowKeys);
    let list = dataSource.reduce((acc, cur) => {
      console.log(acc, 'accc');
      if (selectSet.has(cur.key)) {
        acc.push(cur);
      }
      return acc;
    }, []);
    let parma = list.map(item => `${item.field}=${item.defaultValue}`).join('&');
    let parmas = dataSource.map(item => ({
      field: item.field,
      defaultValue: item.defaultValue,
      paramDesc: item.paramDesc,
      name: item.name,
    }));
    if (parma) {
      parmarCallBack(`${pageUrl.split('|')[0]}|${parma}`, parmas);
    } else {
      parmarCallBack(`${pageUrl.split('|')[0]}`, parmas);
    }
    console.log(list, 'list');
  };
  const handleDelete = key => {
    const newData = dataSource.filter(item => item.key !== key);
    const newSelect = selectedRowKeys.filter(item => item !== key);
    setSelectedRowKeys(newSelect);
    setDataSource(newData);
  };
  const defaultColumns = [
    {
      title: '序号',
      align: 'center',
      width: 50,
      render: (text, record, index) => <span>{index + 1}</span>,
    },
    {
      title: '类型',
      align: 'center',
      width: 70,
      render: (text, record) => {
        if (record.releaseDate) {
          return <Tag color="cyan">内置</Tag>;
        }
        return <Tag color="purple">自定义</Tag>;
      },
    },
    {
      title: '配置项',
      dataIndex: 'name',
      width: 250,
      editable: true,
    },
    {
      title: '参数名',
      dataIndex: 'field',
      width: 150,
      editable: true,
    },

    {
      title: '参数值',
      dataIndex: 'defaultValue',
      width: 150,
      editable: true,
    },

    {
      title: '参数配置说明',
      dataIndex: 'paramDesc',
      width: 250,
      editable: true,
    },

    {
      title: '操作',
      dataIndex: '',
      width: 50,
      align: 'center',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Button
            style={{ border: 'none', padding: '4px 5px', background: 'none' }}
            onClick={() => handleDelete(record.key)}
            disabled={!!record.releaseDate}
          >
            <DeleteOutlined
              style={{ fontSize: '16px', color: `${record.releaseDate ? '#ccc' : '#e86060'}` }}
            />
          </Button>
        ) : null,
    },
  ];
  // 添加
  const handleAdd = () => {
    const newData = {
      key: count,
      field: '',
      defaultValue: '',
      paramDesc: '',
      name: '',
    };
    console.log(newData, 'newData');
    setDataSource([...dataSource, newData]);
    setSelectedRowKeys([...selectedRowKeys, count]);
    setCount(count + 1);
  };
  const handleSave = row => {
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const columns = defaultColumns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        dataSource,
        handleSave,
      }),
    };
  });
  // 表格复选框
  const onSelectChange = newSelectedRowKeys => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: record => ({
      disabled: record.required,
    }),
  };
  return (
    <>
      <Modal
        title="参数配置"
        width="1100px"
        visible={visible}
        onOk={onFinish}
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
        centered
      >
        <div className={styles.contentParmars}>
          <Button
            onClick={handleAdd}
            type="primary"
            style={{
              marginBottom: 16,
            }}
          >
            添加参数
          </Button>
          <Table
            components={components}
            rowSelection={rowSelection}
            size="small"
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={dataSource}
            columns={columns}
            scroll={{ y: '340px' }}
            pagination={false}
          />
        </div>
      </Modal>
    </>
  );
};

export default ParmarsModal;
