import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  getLoginPage,
  getMapCofigs,
  getWebThemes,
  getProductList,
  GetUserName,
} 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 RMSComponents from '@/components/RolePmSite/index';
import PersonnelSelector from '@/components/PersonnelSelector/index';
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',
  },
];

const { TextArea } = Input;

export default props => {
  const {
    visible,
    onClose,
    config,
    hasIntegerate,
    isEdit,
    onOk,
    submitting,
    productList,
    allProductList,
    userMode,
    webs,
    curWeb,
  } = 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();
  const [addVisible, setAddVisible] = useState(false);
  const [checkValue, setCheckValue] = useState([]);
  const [checkValueList, setCheckValueList] = useState([]);
  const [aftercare, setAftercare] = useState('请勾选不显示售后服务的用户');
  const [visibleAnn, setVisibleAnn] = useState();
  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 {
      setCheckValue([]);
      setAftercare('请勾选不显示售后服务的用户');
      setCheckedList(defaultCheckedList);
      setIndeterminate(false);
      setCheckAll(true);
    }
    if (visible == false) {
      setCheckedList([]);
      setCheckValue([]);
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      if (isEdit) {
        // 获取表单回显
        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);
        debugger;
        setVisibleChecked(config.navTheme == 'light');
        setVisibleChecked2(config.hideMap);
        setVisibleChecked4(config.messageVoice);
        setVisibleChecked7(config.useCoverMap == 'true');
        setHomePageConfig(config.roleHomePages);
        setVisibleAnn(config.OpenAnnouncement);
        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,
          changeStation: config.changeStation,
          OpenAnnouncement: config.OpenAnnouncement,
          AnnouncementContent: config.AnnouncementContent,
          headerPrimaryColor: config.headerPrimaryColor
            ? config.headerPrimaryColor
            : 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        });
        setColor(
          config.headerPrimaryColor
            ? config.headerPrimaryColor
            : 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        );
        if (!config.afterSales || config.afterSales === '' || config.afterSales === null) {
          setAftercare('请勾选不显示售后服务的用户');
          setCheckValue([]);
          setCheckValueList([]);
        } else {
          setCheckValue(config.afterSales);
          setCheckValueList(config.afterSalesInfo);
          GetUserName({ userIds: config.afterSales }).then(res => {
            if (res.code === 0) {
              let data = res.data.toString();
              setAftercare(data);
              form.setFieldsValue({ afterSales: data });
            }
          });
        }
      } 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,
          changeStation: false,
          OpenAnnouncement: false,
          headerPrimaryColor: 'linear-gradient(0deg, #0066D6 0%, #39A9FF 100%)',
        });
        setVisibleAnn(false);
        setCheckValue([]);
        setAftercare('请勾选不显示售后服务的用户');
      }
    } else {
      setShowAdvanced(false);
      form.resetFields();
      setVisibleChecked('');
      setVisibleChecked1('');
      setVisibleChecked2('');
      setVisibleChecked3('');
      setVisibleChecked4('');
      setVisibleChecked5('');
      setVisibleAnn('');
      setHomePageConfig([]);
      setCheckValue([]);
      setCheckValueList([]);
      setAftercare('');
    }
  }, [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';
      validate.afterSales = checkValue && checkValue.toString();

      console.log(validate);
      if (validate.homePage) {
        let arr = validate.homePage.split('/'); // 用const声明常量
        let allProList = JSON.parse(JSON.stringify(allProductList));
        allProList.push({ PackageName: 'civ_base' });
        const product = allProList.find(item => item.PackageName === arr[0]);
        if (product) {
          arr.shift();
          validate.homePage = arr.join('/');
        }
        console.log(product, 'product');
        validate.productType = product?.PackageName || 'civweb4';
        let proList = JSON.parse(JSON.stringify(productList));
        proList.push({ PackageName: 'civ_base' });
        if (
          !proList.some(item => item.PackageName === validate.productType) &&
          validate.productType !== 'civweb4'
        ) {
          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 changeAnn = e => {
    setVisibleAnn(e);
  };

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

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

  const rolCallBack = useCallback(list => {
    console.log(list);
    debugger;
    setCheckValueList(list.checkList);
    setAddVisible(false);
    setAftercare(list.text === '' ? '请勾选不显示售后服务的用户' : list.text);
    setCheckValue(list.ids);
  });

  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>
        <Form.Item label="站点切换" name="changeStation" 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}
          userMode={userMode}
          curWeb={curWeb}
          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="售后服务">
            <div
              style={{
                border: '2px solid #6A98FA',
                minHeight: '34px',
                lineHeight: '34px',
                padding: '0px 10px',
                width: '100%',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
              }}
              onClick={() => {
                setAddVisible(true);
              }}
            >
              <span style={{ color: checkValue && checkValue.length > 0 ? 'black' : '#dcdcdc' }}>
                <Tooltip title={checkValue && checkValue.length > 0 ? aftercare : ''}>
                  {aftercare}
                </Tooltip>
              </span>
            </div>
          </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>
          <Row>
            <Col span={8}>
              <Form.Item
                label="开启公告"
                name="OpenAnnouncement"
                valuePropName="checked"
                labelCol={{ span: 15 }}
              >
                <Switch checkedChildren="是" unCheckedChildren="否" onChange={changeAnn} />
              </Form.Item>
            </Col>
            {visibleAnn && (
              <Col span={16}>
                <Form.Item label="公告内容" name="AnnouncementContent" labelCol={{ span: 6 }}>
                  <TextArea rows={3} placeholder="请输入公告内容" />
                </Form.Item>
              </Col>
            )}
          </Row>
          {/* <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);
        }}
      />
      {/* <RMSComponents
        visible={addVisible}
        onCancel={() => {
          setAddVisible(false);
        }}
        callBackSubmit={roleList => rolCallBack(roleList)}
        newCheckedList={checkValue.toString().split(',')} // 单选框中的值
        groupName="角色" // 打开组件展示的分组名，用来首次获取数据
        chooseGroupName={['角色']} // 可选分组名
        dataType="id"
      /> */}
      <PersonnelSelector
        visible={addVisible}
        onCancel={() => {
          setAddVisible(false);
        }}
        callBackSubmit={roleList => rolCallBack(roleList)}
        itemObj={checkValue && checkValue.toString().split(',')} // 单选框中的值
        aftercare={aftercare}
        checkValueList={checkValueList}
      />
    </Drawer>
  );
};
