import React, { useState, useEffect, useRef } from 'react';
import { getLoginPage, getMapCofigs, getWebThemes, getProductList } from '@/services/webConfig/api';
import { SketchPicker } from 'react-color';
import {
  Drawer,
  notification,
  Button,
  Space,
  Form,
  Input,
  Select,
  Checkbox,
  Radio,
  Tooltip,
  Divider,
  AutoComplete,
  Row,
  Col,
  Switch,
  message,
} from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import TreeSelect from '../menuconfig/TreeSelect';
import WebConfigForm from './webConfigForm';
import ColorLinear from './ColorLinear';
import Upload from '@/components/Upload';
import styles from './siteConfigDrawer.less';
import ParmarModal from './ParmarModal';
import HomePageConfigs from './HomePageConfigs';
const { Option } = Select;
const plainOptions = ['搜索', '消息', '反馈'];
const defaultCheckedList = ['搜索', '消息', '反馈'];
const colorList = [
  {
    key: '科技蓝',
    color: '#0087F7',
    headerColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
  },
  {
    key: '环保绿',
    color: '#009C73',
    headerColor: 'linear-gradient(0deg, #00845D 0%, #02BF87 100%)',
  },
  {
    key: '清澈蓝',
    color: '#1890FF',
    headerColor: '#1890FF',
  },
];

export default props => {
  const {
    visible,
    onClose,
    config,
    hasIntegerate,
    isEdit,
    onOk,
    submitting,
    productList,
    allProductList,
    webs,
  } = props;
  const [form] = Form.useForm();
  const [loginPages, setLoginPages] = useState([]);
  const [checkedList, setCheckedList] = useState([]);
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(true);
  const [displayColorPicker, setDisplayColorPicker] = useState(false);
  const [color, setColor] = useState('');
  const CheckboxGroup = Checkbox.Group;
  const [showAdvanced, setShowAdvanced] = useState(false); // 是否显示高级设置
  const [showParmarModal, setShowParmarModal] = useState(false);
  const [keepText, setKeepText] = useState([]);
  const [keepValue, setKeepValue] = useState([]);

  const [visibleChecked, setVisibleChecked] = useState(''); // 菜单开关
  const [visibleChecked1, setVisibleChecked1] = useState(''); // SaaS样式开关
  const [visibleChecked2, setVisibleChecked2] = useState(''); // Web4地图开关
  const [visibleChecked3, setVisibleChecked3] = useState(''); // 消息标记开关
  const [visibleChecked4, setVisibleChecked4] = useState(''); // 语音播报开关
  const [visibleChecked5, setVisibleChecked5] = useState(''); // 菜单样式开关
  const [visibleChecked7, setVisibleChecked7] = useState(''); // 地图遮罩开关
  const [homePageConfig, setHomePageConfig] = useState();
  const homepageConfigRef = useRef();
  useEffect(() => {
    onGetLoginPages();
    let text = [];
    let value = [];
    webs.map(i => {
      text.push(i.text);
      value.push(i.subSystemValue);
    });
    setKeepText(text);
    setKeepValue(value);
    if (isEdit) {
      if (config != null && config.topMenu) {
        setCheckedList(config.topMenu.split(','));
        if (config.topMenu.split(',').length == 1 && config.topMenu.split(',')[0] == '') {
          setIndeterminate(false);
        } else {
          setIndeterminate(
            !!config.topMenu.split(',').length &&
              config.topMenu.split(',').length < plainOptions.length,
          );
        }

        setCheckAll(config.topMenu.split(',').length === plainOptions.length);
      }
    } else {
      setCheckedList(defaultCheckedList);
      setIndeterminate(false);
      setCheckAll(true);
    }
    if (visible == false) {
      setCheckedList([]);
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      if (isEdit) {
        // 获取表单回显
        console.log(config, 'config');
        if (config.CloudStyle == '是') {
          config.CloudStyle == true;
          setVisibleChecked1(true);
        } else {
          config.CloudStyle == false;
          setVisibleChecked1(false);
        }

        if (config.messageMarking == 'All') {
          config.messageMarking == true;
          setVisibleChecked3(true);
        } else {
          config.messageMarking == false;
          setVisibleChecked3(false);
        }

        if (config.menuState == 'open') {
          config.menuState == true;
          setVisibleChecked5(true);
        } else {
          config.menuState == false;
          setVisibleChecked5(false);
        }
        console.log(config);
        setVisibleChecked(config.navTheme == 'light');
        setVisibleChecked2(config.hideMap);
        setVisibleChecked4(config.messageVoice);
        setVisibleChecked7(config.useCoverMap == 'true');
        setHomePageConfig(config.roleHomePages);
        form.setFieldsValue({
          ...config,
          primaryColor: config.primaryColor ? config.primaryColor : '#0087F7',
          navTheme: config.navTheme == 'light',
          CloudStyle: config.CloudStyle,
          messageMarking: config.messageMarking,
          hideMap: config.hideMap,
          messageVoice: config.messageVoice,
          menuState: config.menuState,
          useCoverMap: config.useCoverMap == 'true',
          isCache: config.isCache,
          headerPrimaryColor: config.headerPrimaryColor
            ? config.headerPrimaryColor
            : 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        });
        setColor(
          config.headerPrimaryColor
            ? config.headerPrimaryColor
            : 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        );
      } else {
        setColor('linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)');
        setVisibleChecked(false);
        setVisibleChecked1(true);
        setVisibleChecked2(true);
        setVisibleChecked3(true);
        setVisibleChecked4(true);
        setVisibleChecked5(true);
        setVisibleChecked7(true);
        setHomePageConfig([]);
        form.setFieldsValue({
          shortcutIcon: 'assets\\images\\icon\\熊猫-蓝色.png',
          logo: 'assets\\images\\logo\\熊猫-蓝绿色.svg',
          bannerLogo: 'assets\\images\\logo\\熊猫-白色.svg',
          title: '新网站',
          messageMarking: true,
          messageVoice: true,
          menuState: true,
          hideMap: true,
          loginTemplate: 'Dark',
          primaryColor: '#0087F7',
          navTheme: false,
          CloudStyle: true,
          useCoverMap: true,
          isCache: true,
          headerPrimaryColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        });
      }
    } else {
      setShowAdvanced(false);
      form.resetFields();
      setVisibleChecked('');
      setVisibleChecked1('');
      setVisibleChecked2('');
      setVisibleChecked3('');
      setVisibleChecked4('');
      setVisibleChecked5('');
      setHomePageConfig([]);
    }
  }, [visible]);
  const onGetLoginPages = () => {
    if (loginPages.length === 0) {
      getLoginPage().then(res => {
        let list = [
          {
            label: renderTitle('web5内置模板'),
            options: [],
          },
          {
            label: renderTitle('web4登录模板'),
            options: [],
          },
        ];
        res.data.loginTemplate.forEach(item => {
          if (item.type === 'web5') {
            list[0].options.push(renderItem(`${item.title}`));
          }
          if (item.type === 'web4') {
            list[1].options.push(renderItem(`${item.title}`));
          }
        });

        setLoginPages(list);
      });
    }
  };
  const renderItem = title => ({
    value: title,
    label: (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        {title}
      </div>
    ),
  });
  // 登录搜索头部
  const renderTitle = title => <span>{title}</span>;

  const onsubmit = () => {
    form.validateFields().then(validate => {
      // if (checkedList.find(i => i == '首页') && !validate.homePage) {
      //   notification.warning({
      //     message: '提示',
      //     duration: 3,
      //     description: '功能配置勾选首页时主页Url必填',
      //   });
      //   return;
      // }
      validate.topMenu = checkedList.toString();
      validate.navTheme = visibleChecked ? 'light' : 'dark';
      validate.CloudStyle = visibleChecked1 ? '是' : '否';
      validate.messageMarking = visibleChecked3 ? 'All' : 'One';
      validate.menuState = visibleChecked5 ? 'open' : 'close';

      console.log(validate);
      if (validate.homePage) {
        let arr = validate.homePage.split('/'); // 用const声明常量

        const product = allProductList.find(item => item.PackageName.includes(arr[0]));
        if (product) {
          arr.shift();
          validate.homePage = arr.join('/');
        }
        console.log(product, 'product');
        validate.productType = product?.PackageName || 'civweb4';
        if (!productList.some(item => item.PackageName === validate.productType)) {
          message.error(`${validate.productType}未授权，不能使用该功能当主页`);
          return;
        }
      }

      console.log(validate);

      if (validate) {
        const colorIndex = colorList.findIndex(item => item.color === validate.primaryColor);
        let pages = homepageConfigRef.current.getHomePageConfig().map((item, index) => {
          let str = item.homePage.replace(/^[^\/]+\/+/, '');
          console.log(str, 'fasdasd');
          return {
            ...item,
            homePage: item.homePage.replace(/^[^\/]+\/+/, ''),
            index,
          };
        });
        console.log(pages, 'pages');

        onOk({
          ...validate,
          roleHomePages: pages,
          headerPrimaryColor: colorList[colorIndex].headerColor,
          mode: 'single',
          menu: 'banner-left',
        });
      }
    });
  };

  const onCheckAllChange = e => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };
  const colorChange = value => {
    setColor(value);
    form.setFieldsValue({ headerPrimaryColor: value });
  };

  const addParama = () => {
    if (!form.getFieldValue('loginTemplate')) {
      notification.error({ message: '提示', duration: 3, description: '请先选择登录模板' });
      return;
    }
    setShowParmarModal(true);
  };

  const change = e => {
    setVisibleChecked(e);
  };

  const change1 = e => {
    setVisibleChecked1(e);
  };
  const change2 = e => {
    setVisibleChecked2(e);
  };

  const change3 = e => {
    setVisibleChecked3(e);
  };
  const change4 = e => {
    setVisibleChecked4(e);
  };

  const change5 = e => {
    setVisibleChecked5(e);
  };

  const change7 = e => {
    setVisibleChecked7(e);
  };

  return (
    <Drawer
      title={isEdit ? '查看/编辑网站配置' : '新增网站'}
      width={550}
      onClose={onClose}
      visible={visible}
      destroyOnClose
      footer={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button onClick={onsubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
        initialValues={{ remember: true }}
      >
        <Form.Item
          label="标题"
          name="title"
          rules={[
            {
              required: true,
              message: '标题为必填项',
            },
            {
              validator: (rule, value) => {
                let data = form.getFieldValue().title;
                if (keepText.indexOf(data) != -1 && !isEdit) {
                  return Promise.reject('标题已存在');
                }
                if (keepText.indexOf(data) != -1 && data != config.title) {
                  return Promise.reject('标题已存在');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input placeholder="请输入标题" autoComplete="off" />
        </Form.Item>
        <Form.Item label="副标题" name="subtitle">
          <Input placeholder="请输入副标题" autoComplete="off" />
        </Form.Item>
        <Form.Item
          label="系统Icon"
          name="shortcutIcon"
          style={{ height: '112px' }}
          rules={[
            {
              required: true,
              message: '请选择菜单图标',
            },
          ]}
        >
          <Upload picType="icon" />
        </Form.Item>
        <Form.Item
          label="登录Logo"
          name="logo"
          style={{ height: '112px' }}
          rules={[
            {
              required: true,
              message: '请选择图标icon',
            },
          ]}
        >
          <Upload picType="logo" />
        </Form.Item>
        <Form.Item
          label="标题Logo"
          name="bannerLogo"
          style={{ height: '112px' }}
          rules={[
            {
              required: true,
              message: '请选择标题logo',
            },
          ]}
        >
          <Upload picType="logo" />
        </Form.Item>
        <Form.Item
          label="虚拟目录"
          name="client"
          rules={[
            {
              required: true,
              message: '虚拟目录不能为空',
            },
            {
              validator: (rule, value) => {
                let data = form.getFieldValue().client;
                if (data == 'CS') {
                  return Promise.reject('不允许输入CS');
                }
                if (keepValue.indexOf(data) != -1 && !isEdit) {
                  return Promise.reject('虚拟目录已存在');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input autoComplete="off" disabled={isEdit} />
        </Form.Item>
        <Form.Item label="登录模板" name="loginTemplate">
          <AutoComplete placeholder="请选择登录模板" options={loginPages} allowClear filterOption />
        </Form.Item>
        <Form.Item label="页面缓存" name="isCache" valuePropName="checked">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" />
        </Form.Item>
        <Divider orientation="left" style={{ borderTopColor: '#99bbe8' }}>
          主页配置
        </Divider>
        {/* <Form.Item label="产品类型(默认)" name="productType">
          <Select placeholder="请选择主页产品类型">
            {productList.map(item => (
              <Option value={item.PackageName} key={item.PackageName}>
                {`${item.ProductName}（${item.PackageName}）`}
              </Option>
            ))}
          </Select>
        </Form.Item> */}
        <Form.Item label="主页地址(默认)" name="homePage">
          {/* <Input placeholder="请输入主页路径" autoComplete="off" /> */}
          <TreeSelect menuChange={val => {}} />
        </Form.Item>
        <HomePageConfigs
          ref={homepageConfigRef}
          roleHomePages={homePageConfig}
          productList={productList}
          allProductList={allProductList}
          client={form.getFieldValue('client')}
        />
        <Divider orientation="left" style={{ borderTopColor: '#99bbe8' }}>
          主题配置
        </Divider>

        {/* <Form.Item name="headerPrimaryColor" label="顶部">
          <div className={styles.colorBox}>
            <div
              className={styles.colorSwatch}
              onClick={e => {
                setDisplayColorPicker(!displayColorPicker);
              }}
            >
              <div>颜色</div>
              <div
                style={{
                  background: color,
                  height: '10px',
                  width: '10px',
                  margin: '10px 0 0 5px',
                }}
              />
            </div>
          </div>
        </Form.Item> */}
        <Form.Item name="primaryColor" label="主题色">
          <Select placeholder="请选择颜色">
            {colorList.map(item => (
              <Option value={item.color} key={item.color}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div
                    style={{
                      height: '10px',
                      width: '10px',
                      background: item.color,
                      marginRight: '5px',
                    }}
                  />
                  {`${item.key}（${item.color}）`}
                </div>
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="navTheme" label="菜单">
          {/* <Radio.Group>
            <Radio value="dark">暗</Radio>
            <Radio value="light">亮</Radio>
          </Radio.Group> */}
          <Switch
            checkedChildren="亮"
            unCheckedChildren="暗"
            checked={visibleChecked}
            onChange={change}
          />
        </Form.Item>

        <Form.Item>
          <Switch
            checked={showAdvanced}
            checkedChildren="高级设置"
            unCheckedChildren="高级设置"
            onChange={() => setShowAdvanced(!showAdvanced)}
          />
        </Form.Item>
        <div style={{ display: showAdvanced ? 'block' : 'none' }}>
          <Form.Item
            label={
              <div className={styles.formData_label}>
                <Tooltip
                  title={
                    <span>用于云平台模式，默认云，选择租户会在SaaS访问情况下，展示租户样式</span>
                  }
                  overlayStyle={{ maxWidth: 350 }}
                >
                  <InfoCircleOutlined style={{ color: '#40a9ff', padding: '2px 2px 0 0' }} />
                </Tooltip>
                <span>SaaS样式</span>
              </div>
            }
            name="CloudStyle"
          >
            {/* <Radio.Group>
              <Radio value="是">云</Radio>
              <Radio value="否">租户</Radio>
            </Radio.Group> */}
            <Switch
              checkedChildren="云"
              unCheckedChildren="租户"
              checked={visibleChecked1}
              onChange={change1}
            />
          </Form.Item>
          <Form.Item name="topMenu" label="顶部功能">
            <Checkbox
              indeterminate={indeterminate}
              onChange={onCheckAllChange}
              checked={checkAll}
              style={{ marginTop: '5px', display: 'none' }}
            >
              全选
            </Checkbox>
            <CheckboxGroup
              options={plainOptions}
              value={checkedList}
              checked={showAdvanced}
              onChange={onChange}
            />
          </Form.Item>
          {/* <Form.Item label="功能标签" name="mdi">
            <Select placeholder="请选择功能标签">
              <Option value="MDI" key="0">
                多标签模式
              </Option>
              <Option value="SDI" key="1">
                单标签模式
              </Option>
            </Select>
          </Form.Item> */}
          <Form.Item label="二维码地址" name="qrcode">
            <Input placeholder="请输入二维码地址" autoComplete="off" />
          </Form.Item>
          {/* <Form.Item label="Web4地图" name="hideMap">
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
              checked={visibleChecked2}
              onChange={change2}
            />
          </Form.Item> */}
          <Form.Item label="地图遮罩" name="useCoverMap">
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
              checked={visibleChecked7}
              onChange={change7}
            />
          </Form.Item>
          <Form.Item
            label={
              <div className={styles.formData_label}>
                <Tooltip
                  title={
                    <span>
                      多人(默认)：标记自己的消息，不影响他人接收
                      <br />
                      单人：标记已读，消息不再提醒其他人，主要解决报警过多，通知范围过大的情况
                    </span>
                  }
                  overlayStyle={{ maxWidth: 350 }}
                >
                  <InfoCircleOutlined style={{ color: '#40a9ff', padding: '2px 2px 0 0' }} />
                </Tooltip>
                <span>消息标记</span>
              </div>
            }
            name="messageMarking"
          >
            {/* <Radio.Group>
              <Radio value="All">多人</Radio>
              <Radio value="One">单人</Radio>
            </Radio.Group> */}
            <Switch
              checkedChildren="多人"
              unCheckedChildren="单人"
              checked={visibleChecked3}
              onChange={change3}
            />
          </Form.Item>
          <Form.Item label="语音播报" name="messageVoice">
            {/* <Radio.Group>
              <Radio value>开启</Radio>
              <Radio value={false}>关闭</Radio>
            </Radio.Group> */}
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
              checked={visibleChecked4}
              onChange={change4}
            />
          </Form.Item>
          {/* <Form.Item label="菜单样式" name="menuState">
            <Switch
              checkedChildren="展开"
              unCheckedChildren="折叠"
              checked={visibleChecked5}
              onChange={change5}
            />
          </Form.Item> */}
        </div>
      </Form>
      <ColorLinear
        visible={displayColorPicker}
        color={color}
        onSubumit={colorChange}
        handleCancel={() => setDisplayColorPicker(false)}
      />
      <ParmarModal
        pageUrl={form.getFieldValue('loginTemplate')}
        handleCancel={() => setShowParmarModal(false)}
        visible={showParmarModal}
        parmarCallBack={url => {
          form.setFieldsValue({ loginTemplate: url });
          setShowParmarModal(false);
        }}
      />
    </Drawer>
  );
};
