import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Select, Space, TreeSelect, Empty, Switch, Button, message } from 'antd';
import { FolderFilled, FileOutlined, MobileOutlined } from '@ant-design/icons';
import { AddWorkWechatStatus } from '@/services/messagemanage/messagemanage';
const { Option } = Select;
const { TextArea } = Input;
const { TreeNode } = TreeSelect;
const typeList = [
  { name: '文字', value: 1 },
  { name: '卡片', value: 2 },
  { name: '图文', value: 3 },
  { name: '图片', value: 4 },
];

const EnterpriseWeChatConfig = props => {
  const { menuMoblieList, formValue, id } = props;
  const [flag, setFlag] = useState(0);
  const [form] = Form.useForm();
  useEffect(() => {
    getFormData();
  }, []);

  const getFormData = () => {
    console.log(formValue, 'formValue');
    if (formValue) {
      form.setFieldsValue({ ...formValue, WorkWechatStatus: formValue.WorkWechatStatus === 1 });
      setFlag(flag + 1);
    }
  };
  // 监听表单
  const changeValue = (changedFields, allFields) => {
    // console.log(Object.keys(changedFields), allFields, 'changedFields');
    if (Object.keys(changedFields)[0] === 'WorkWechatContent') {
      let regex = /\{@(.+?)\}/g;
      let originalList = allFields.lines || [];
      let list = changedFields.WorkWechatContent.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] === 'WorkWechatType') {
      setFlag(flag + 1);
    }
  };
  const mapAppTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    let icon;
    let value = org.id;

    if (org.menuType === 'MiniAppsingleStation') {
      value = org.stationID;
      icon = <MobileOutlined />;
    }
    if (org.menuType === 'MiniAppMenuGroup' || org.menuType === '"MiniAppMenuGroupTwo"') {
      value = org.id;
      icon = <FolderFilled />;
    }
    if (org.menuType === 'MiniAppMenuThree' || org.menuType === 'MiniAppMenu') {
      icon = <FileOutlined style={{ color: '#1890ff' }} />;
      value = org.pageUrl || org.id;
    }

    return (
      <TreeNode
        value={value}
        title={org.text}
        icon={icon}
        key={value}
        disabled={org.menuType !== 'MiniAppMenuThree' && org.menuType !== 'MiniAppMenu'}
      >
        {haveChildren ? org.children.map(item => mapAppTree(item)) : null}
      </TreeNode>
    );
  };
  const onFinish = () => {
    if (!id) {
      message.error('请保存基础信息');
      return;
    }
    form.validateFields().then(value => {
      if (value) {
        AddWorkWechatStatus({
          ...value,
          WorkWechatStatus: value.WorkWechatStatus ? 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="WorkWechatType"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            style={{ width: '400px', display: 'block' }}
          >
            <Select placeholder="请选择消息类型">
              {typeList.map(item => (
                <Option value={item.value} key={item.value}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="企业应用ID"
            name="WorkWechatAppID"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Input placeholder="请填写企业应用ID" />
          </Form.Item>
          <Form.Item
            label="是否开启"
            name="WorkWechatStatus"
            valuePropName="checked"
            style={{ width: '400px', display: 'block' }}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>
        </div>
        <div style={{ display: 'flex' }}>
          <Form.Item
            label="标题"
            name="WorkWechatTitle"
            style={{
              width: '400px',
              display:
                form.getFieldValue('WorkWechatType') === 2 ||
                form.getFieldValue('WorkWechatType') === 3
                  ? 'block'
                  : 'none',
            }}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Input placeholder="请填写标题" />
          </Form.Item>
          <Form.Item
            label="底部文字"
            name="WorkWechatBtnText"
            style={{
              width: '400px',
              display: form.getFieldValue('WorkWechatType') === 2 ? 'block' : 'none',
            }}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
          >
            <Input placeholder="请填写底部文字" />
          </Form.Item>
        </div>
        <Form.Item
          label="图片路径"
          name="WorkWechatImgUrl"
          style={{
            width: '1200px',
            display:
              form.getFieldValue('WorkWechatType') === 3 ||
              form.getFieldValue('WorkWechatType') === 4
                ? 'block'
                : 'none',
          }}
        >
          <Input placeholder="请填写底部文字" />
        </Form.Item>
        <Form.Item
          label="跳转路径"
          name="WorkWechatUrl"
          style={{
            display:
              form.getFieldValue('WorkWechatType') === 3 ||
              form.getFieldValue('WorkWechatType') === 2
                ? 'block'
                : 'none',
            width: '1200px',
          }}
        >
          <Input placeholder="请填写跳转路径" />
          {/* <TreeSelect
            showSearch
            treeNodeFilterProp="title"
            treeNodeLabelProp="value"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择功能路径"
            allowClear
            treeDefaultExpandAll
            treeIcon
          >
            {menuMoblieList ? (
              menuMoblieList.map(item => mapAppTree(item))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </TreeSelect> */}
        </Form.Item>
        <Form.Item
          label="内容"
          name="WorkWechatContent"
          style={{
            display: form.getFieldValue('WorkWechatType') !== 4 ? 'block' : 'none',
            width: '1200px',
          }}
        >
          <TextArea rows={4} placeholder="请输入内容" />
        </Form.Item>
        <Form.List name="lines">
          {fields => (
            <div
              style={{
                display: form.getFieldValue('WorkWechatType') !== 4 ? 'block' : 'none',
              }}
            >
              {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> */}
            </div>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" onClick={onFinish}>
            保存
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default EnterpriseWeChatConfig;
