import React, { useState, useEffect } 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,
} from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import WebConfigForm from './webConfigForm';
import ColorLinear from './ColorLinear';
import Upload from '@/components/Upload';
import styles from './siteConfigDrawer.less';
import ParmarModal from './ParmarModal';
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 } = 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);

  useEffect(() => {
    onGetLoginPages();
    console.log(isEdit);
    if (isEdit) {
      console.log(config);
      if (config != null && config.topMenu) {
        console.log(config);
        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');
        form.setFieldsValue({
          ...config,
          primaryColor: config.primaryColor ? config.primaryColor : '#0087F7',
          navTheme: config.navTheme ? config.navTheme : 'dark',
          CloudStyle: config.CloudStyle ? config.CloudStyle : '是',
          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%)');
        form.setFieldsValue({
          messageMarking: 'All',
          messageVoice: true,
          hideMap: false,
          loginTemplate: 'Default.html',
          primaryColor: '#0087F7',
          navTheme: 'dark',
          CloudStyle: '是',
          headerPrimaryColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        });
      }
    } else {
      setShowAdvanced(false);
      form.resetFields();
    }
  }, [visible]);
  const onGetLoginPages = () => {
    if (loginPages.length === 0) {
      getLoginPage().then(res => {
        setLoginPages(res.data);
        setLoginPages(res.data);
      });
    }
  };

  const onsubmit = () => {
    form.validateFields().then(validate => {
      console.log(validate);
      console.log(checkedList);
      // if (checkedList.find(i => i == '首页') && !validate.homePage) {
      //   notification.warning({
      //     message: '提示',
      //     duration: 3,
      //     description: '功能配置勾选首页时主页Url必填',
      //   });
      //   return;
      // }
      validate.topMenu = checkedList.toString();
      console.log(validate);
      if (validate) {
        const colorIndex = colorList.findIndex(item => item.color === validate.primaryColor);
        onOk({
          ...validate,
          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 => {
    console.log(checkedList);
    console.log(list);
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };
  const colorChange = value => {
    console.log(value, 'value');
    setColor(value);
    form.setFieldsValue({ headerPrimaryColor: value });
  };

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

  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: '标题为必填项',
            },
          ]}
        >
          <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: '虚拟目录不能为空',
            },
          ]}
        >
          <Input autoComplete="off" disabled={isEdit} />
        </Form.Item>
        {/* <Row>
          <Col span={20}> */}
        <Form.Item label="登录模板" name="loginTemplate">
          <AutoComplete placeholder="请选择登录模板" options={loginPages} allowClear />
          {/* <Select placeholder="请选择登录模板">
            {loginPages.map(item => (
              <Option value={item.value} key={item.value}>
                {item.value}
              </Option>
            ))}
          </Select> */}
        </Form.Item>
        {/* </Col> */}
        {/* <Col span={4}>
            <Form.Item>
              <Button onClick={addParama}>参数管理</Button>
            </Form.Item>
          </Col>
        </Row> */}
        <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="主页Url" name="homePage">
          <Input placeholder="请输入主页路径" autoComplete="off" />
        </Form.Item>
        <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>
        </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>
          </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">
            <Radio.Group>
              <Radio value={false}>开启</Radio>
              <Radio value={true}>关闭</Radio>
            </Radio.Group>
          </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>
          </Form.Item>
          <Form.Item label="语音播报" name="messageVoice">
            <Radio.Group>
              <Radio value={true}>开启</Radio>
              <Radio value={false}>关闭</Radio>
            </Radio.Group>
          </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>
  );
};
