import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Select, Space, TreeSelect, Empty, Switch, Button, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { AddSMSStatus } from '@/services/messagemanage/messagemanage';
const { Option } = Select;
const { TextArea } = Input;

const ShortMessageConfig = props => {
  const { formValue, id, template } = props;
  const [form] = Form.useForm();
  useEffect(() => {
    console.log(template, 'template');
    getFormData();
  }, []);

  const getFormData = () => {
    console.log(formValue, 'formValue');
    if (formValue) {
      form.setFieldsValue({ ...formValue, SMSStatus: formValue.SMSStatus === 1 });
    }
  };
  // 监听表单
  const changeValue = (changedFields, allFields) => {
    console.log(Object.keys(changedFields), allFields, 'changedFields');
    if (Object.keys(changedFields)[0] === 'SMSContent') {
      let regex = /\{@(.+?)\}/g;
      let originalList = allFields.lines || [];
      let list = changedFields.SMSContent.match(regex)?.map(item => {
        let Name = item.substring(2, item.length - 1);
        let orgItem = originalList.find(ele => ele.Name === Name);
        return {
          Name,
          Description: orgItem ? orgItem.Description : '',
          DefaultValue: orgItem ? orgItem.DefaultValue : '',
        };
      });
      if (list) {
        form.setFieldsValue({ lines: list });
      } else {
        form.setFieldsValue({ lines: [] });
      }
    }
    if (Object.keys(changedFields)[0] === 'SMSType') {
      let content = template.find(item => item.id === changedFields.SMSType);
      let regex = /\{@(.+?)\}/g;
      let list = content.Param.match(regex)?.map(item => {
        let Name = item.substring(2, item.length - 1);
        return {
          Name,
          Description: '',
          DefaultValue: '',
        };
      });
      form.setFieldsValue({ SMSContent: content.Param, lines: list, SMSNumber: content.Code });
    }
  };
  const onFinish = () => {
    if (!id) {
      message.error('请保存基础信息');
      return;
    }
    form.validateFields().then(values => {
      let value = JSON.parse(JSON.stringify(values));
      AddSMSStatus({
        ...value,
        SMSStatus: value.SMSStatus ? 1 : 0,
        id,
      }).then(res => {
        if (res.code === 0) {
          message.success('保存成功');
        } else {
          message.error(res.msg);
        }
      });
    });
  };
  return (
    <div>
      <Form
        form={form}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onValuesChange={changeValue}
        labelAlign="left"
      >
        <div style={{ display: 'flex' }}>
          <Form.Item
            label="消息类型"
            name="SMSType"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            style={{ width: '400px', marginRight: '15px', display: 'block' }}
          >
            <Select placeholder="请选择消息类型">
              {template.map(item => (
                <Option value={item.id} key={item.id}>
                  {item.Name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="短信编号"
            name="SMSNumber"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Input placeholder="请填写消息标题" />
          </Form.Item>
          <Form.Item
            label="是否开启"
            name="SMSStatus"
            valuePropName="checked"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>
        </div>

        <Form.Item label="内容" name="SMSContent" style={{ display: 'block', width: '1200px' }}>
          <TextArea rows={4} placeholder="请输入内容" />
        </Form.Item>
        <Form.List name="lines">
          {fields => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Space
                  key={key}
                  style={{
                    display: 'flex',
                    marginBottom: 8,
                  }}
                  align="baseline"
                >
                  <Form.Item
                    {...restField}
                    label="参数名"
                    name={[name, 'Name']}
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                  >
                    <Input readOnly />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'Description']}
                    label="含义"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    rules={[
                      {
                        required: true,
                        message: '请填写含义',
                      },
                    ]}
                  >
                    <Input placeholder="请填写含义" />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'DefaultValue']}
                    label="默认值"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    // rules={[
                    //   {
                    //     required: true,
                    //     message: '请填写默认值',
                    //   },
                    // ]}
                  >
                    <Input placeholder="请填写默认值" />
                  </Form.Item>
                  {/* <MinusCircleOutlined onClick={() => remove(name)} /> */}
                </Space>
              ))}
              {/* <Form.Item>
            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
              Add field
            </Button>
          </Form.Item> */}
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" onClick={onFinish}>
            保存
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default ShortMessageConfig;