import React, { useState } from 'react';
import { getConfigContent } from '@/services/webConfig/api';
import { Form, Input, Button, Select, Radio, message } from 'antd';
import styles from './addForm.less';
import PicturesWall from '@/components/Upload/index';
import EditeConfigWrapper from './editConfigFileWrapper';
import TreeSelect from './TreeSelect';

const { Item } = Form;
const { Option } = Select;
const AddForm = props => {
  const {
    submitCallback,
    nodeObj,
    addType,
    submitLoading,
    configFiles,
    productList,
    allProductList,
  } = props;
  const [curretnMenu, setCurrentMenu] = useState({}); // 当前选中菜单数据
  const [form] = Form.useForm();
  const [otherForm] = Form.useForm();
  const [configContent, setConfigContent] = useState(''); // 配置文件内容
  const layout = {
    layout: 'horizontal',
    labelCol: { span: 4, offset: 1 },
    wrapperCol: { span: 16 },
  };
  const submit = () => {
    if (addType === 1) {
      let obj = form.getFieldsValue();
      let arr = obj.pageUrl.split('/'); // 用const声明常量
      if (!arr[0]) {
        arr.shift();
      }
      let allProList = JSON.parse(JSON.stringify(allProductList));
      allProList.push({ PackageName: 'civ_base' });
      const product = allProList.find(item => item.PackageName.includes(arr[0]));
      if (product) {
        if (arr.length > 1) {
          arr.shift();
        }

        obj.pageUrl = arr.join('/');
      }
      console.log(product, 'product');
      obj.product = product?.PackageName || 'civweb4';
      let proList = JSON.parse(JSON.stringify(productList));
      proList.push({ PackageName: 'civ_base' });
      if (!proList.some(item => item.PackageName === obj.product) && obj.product !== 'civweb4') {
        message.error(`${obj.product}未授权，不能使用该功能`);
        return;
      }
      obj.codeParam = JSON.stringify(curretnMenu.param);
      obj.code = curretnMenu.code;
      obj.configContent = configContent;
      console.log(obj, 'obj');
      submitCallback(obj, nodeObj);
    }
    if (addType === 2) {
      // 分组
      let obj = otherForm.getFieldsValue();
      submitCallback(obj, nodeObj);
    }
  };
  const finish = () => {
    submit();
  };
  const menuChange = val => {
    if (!val) {
      return;
    }
    setCurrentMenu(val);
    form.setFieldsValue({
      menuName: val?.function,
      shortName: val?.shortName,
      imageUrl: val?.icon,
      configName: val?.configName,
    });
    setConfigContent(val.configContent);
  };
  const wrapperFinish = val => {
    setConfigContent(val);
  };
  // 选择配置文件获取到配置文件内容
  const selectConfig = val => {
    console.log(val);
    getConfigContent(val)
      .then(res => {
        if (res.code === 0) {
          setConfigContent(res.data);
        }
      })
      .catch(e => {
        console.error(e);
      });
  };
  return (
    <div>
      {addType === 1 && (
        <Form
          form={form}
          name="groupform"
          {...layout}
          className={styles.formStyle}
          onFinish={finish}
        >
          <Item
            label="菜单名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单名称',
              },
            ]}
          >
            <Input placeholder="请输入菜单名称" />
          </Item>
          <Item label="菜单别名" name="shortName">
            <Input placeholder="请输入菜单别名" />
          </Item>
          {/* <Item label="产品类型：" name="product">
            <Select placeholder="请选择产品类型" allowClear>
              {productList &&
                productList.length > 0 &&
                productList.map(item => (
                  <Option value={item.PackageName} key={item.PackageName}>
                    {`${item.ProductName}（${item.PackageName}）`}
                  </Option>
                ))}
            </Select>
          </Item> */}
          <Item
            label="菜单图标"
            name="imageUrl"
            rules={[
              {
                required: true,
                message: '请选择菜单图标',
              },
            ]}
          >
            <PicturesWall picType="menuNew" />
          </Item>
          <Item label="菜单隐藏" name="hideInMenu" initialValue={false}>
            <Radio.Group>
              <Radio value={false}>否</Radio>
              <Radio value>是</Radio>
            </Radio.Group>
          </Item>
          <Item
            label="功能路径"
            name="pageUrl"
            rules={[
              {
                required: true,
                // pattern: /^[^\s]*$/,
                message: '请输入功能路径',
              },
            ]}
          >
            {/* <Input placeholder="请输入功能路径" /> */}
            <TreeSelect menuChange={val => menuChange(val)} />
          </Item>
          <Item label="配置文件" name="configName">
            <EditeConfigWrapper onFinish={wrapperFinish} configContent={configContent}>
              <Select
                allowClear
                showSearch
                onSelect={selectConfig}
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {configFiles.map(c => (
                  <Select.Option key={c.text} value={c.value}>
                    {c.text}
                  </Select.Option>
                ))}
              </Select>
            </EditeConfigWrapper>
          </Item>
          <Item wrapperCol={{ offset: 5 }} style={{ marginTop: '40px' }}>
            <Button type="primary" htmlType="submit" loading={submitLoading}>
              提交
            </Button>
          </Item>
        </Form>
      )}

      {addType === 2 && (
        <Form
          form={otherForm}
          name="menuform"
          {...layout}
          onFinish={finish}
          className={styles.formStyle}
        >
          <Item
            label="菜单组名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单组名称',
              },
            ]}
          >
            <Input placeholder="请输入菜单组名称" />
          </Item>
          <Item label="菜单组别名" name="shortName">
            <Input placeholder="请输入菜单组别名" />
          </Item>
          <Item
            label="菜单组图标"
            name="imageUrl"
            rules={[
              {
                required: true,
                message: '请选择菜单组图标',
              },
            ]}
          >
            <PicturesWall picType="menuNew" />
          </Item>
          <Item wrapperCol={{ offset: 5 }} style={{ marginTop: '40px' }}>
            <Button type="primary" htmlType="submit" loading={submitLoading}>
              提交
            </Button>
          </Item>
        </Form>
      )}
    </div>
  );
};
export default AddForm;
