import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Button,
  Form,
  Input,
  Switch,
  Tooltip,
  Divider,
  Collapse,
  PageHeader,
  message,
  Tabs,
} from 'antd';
import { FieldTimeOutlined, UsergroupAddOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { getWebModuleTree } from '@/services/webConfig/api';
import { getMiniAppModuleTree } from '@/services/mobileConfig/api';
import {
  AddMessageConfigs,
  UpdateMessageConfigs,
  AddIISAgentConfig,
} from '@/services/messagemanage/messagemanage';
import { useHistory } from 'react-router-dom';
import PlatformConfig from './components/PlatformConfig';
import ShortMessageConfig from './components/ShortMessageConfig';
import WeChatConfig from './components/WeChatConfig';
import EnterpriseWeChatConfig from './components/EnterpriseWeChatConfig';
import RoleModal from '../projectManage/components/RolseSelect/RoleModalNew';
import VisibleIISAgentConfig from '../projectManage/components/IISAgentConfig/VisibleIISAgentConfigNew';
import styles from './schemeDetails.less';

const { Panel } = Collapse;

const SchemeDetails = props => {
  const history = useHistory();
  const { schemeMsg, msgTemplate } = props.location.state;
  const [baseForm] = Form.useForm();
  const [menuWebList, setMenuWebList] = useState([]); // web菜单列表
  const [menuMoblieList, setMenuMoblieList] = useState([]); // app菜单列表
  const [IISConfig, setIISConfig] = useState(null); // 定时计划配置
  const [showRoleModal, setShowRoleModal] = useState(false); // 推送组选择角色弹窗
  const [msgTemplates, setMsgTemplates] = useState({});
  const [flag, setFlag] = useState(0);
  const schemeTypeList = useRef({});
  const schemeId = useRef();
  const timePlan = useRef();
  const roleSelect = useRef([]);
  useEffect(() => {
    console.log(schemeMsg, msgTemplate, 'schemeMsg');
    getTemplate();
    getFormData();
    getWebTree();
    getAppTRee();
  }, []);
  // 获取模板信息
  const getTemplate = () => {
    let list = new Map([]);
    msgTemplate.forEach(item => {
      let children = list.get(item.Type) || [];
      list.set(item.Type, [...children, item]);
    });
    setMsgTemplates(Object.fromEntries(list.entries()));
    console.log(Object.fromEntries(list.entries()));
  };
  const getFormData = () => {
    if (!schemeMsg) {
      return;
    }
    roleSelect.current = schemeMsg.TimeJobGroup.map(item =>
      JSON.stringify({
        value: item.id,
        label: item.name,
      }),
    );
    console.log(roleSelect.current, 'roleSelect.current');
    baseForm.setFieldsValue({
      SchemeName: schemeMsg.SchemeName,
      TimeJobGroup: schemeMsg.TimeJobGroup.map(item => item.name).join(','),
      TimeJobOpen: schemeMsg.TimeJobOpen === 1,
      IsEnable: schemeMsg.IsEnable === 1,
    });
    setFlag(flag + 1);
  };
  // 获取apptree数据
  const getAppTRee = () => {
    getMiniAppModuleTree({
      userMode: 'super',
    })
      .then(res => {
        if (res.code === 0) {
          let list = res.data.find(item => item.id === 'MiniAppSite');
          let applist = list.children.map(item => ({
            ...item,
            children: item.children[1].children,
          }));
          setMenuMoblieList(applist);
        } else {
          message.error(res.msg);
        }
      })
      .catch(err => {
        message.error('网络异常请稍后再试');
      });
  };
  const getWebTree = () => {
    getWebModuleTree('super')
      .then(res => {
        const { code, data } = res;
        if (code === 0) {
          let list = data.find(item => item.id === 'Web4SingleStation');
          let weblist = list.children.map(item => ({
            ...item,
            children: item.children[1].children,
          }));
          setMenuWebList(weblist);
        } else {
          message.error(res.msg);
        }
      })
      .catch(err => {
        message.error('网络异常请稍后再试');
      });
  };
  const headerRender = value => {
    return value;
  };
  // 角色回调函数
  const rolCallBack = useCallback(list => {
    console.log(list, 'list');
    let strList = [];
    roleSelect.current = [];
    if (list.length > 0) {
      list.forEach(item => {
        item.checkedList.forEach(ele => {
          strList.push(JSON.parse(ele).label);
          roleSelect.current.push(ele);
        });
      });

      baseForm.setFieldsValue({ TimeJobGroup: strList.join(',') });
      setShowRoleModal(false);
    }
  });
  // 定时计划
  const onIISAgentSubmit = val => {
    console.log(val, 'valfadsf');
    setIISConfig(val);
  };
  const onFinish = () => {
    let val = baseForm.getFieldsValue(true);
    let obj = {
      SchemeName: val.SchemeName,
      IsEnable: val.IsEnable ? 1 : 0,
      TimeJobOpen: val.TimeJobOpen ? 1 : 0,
      TimeJobGroup: roleSelect.current.map(item => JSON.parse(item).value).join(','),
    };
    if (schemeMsg) {
      UpdateMessageConfigs({ ...obj, id: schemeMsg.Id }).then(res => {
        if (res.code === 0) {
          message.success('保存成功');
          saveIISAgentConfig();
        } else {
          message.error(res.msg);
        }
      });
    } else {
      AddMessageConfigs(obj).then(res => {
        if (res.code === 0) {
          schemeId.current = res.data;
          setFlag(flag + 1);
          message.success('保存成功');
          saveIISAgentConfig();
        } else {
          message.error(res.msg);
        }
      });
    }
  };
  const saveIISAgentConfig = () => {
    if (IISConfig) {
      AddIISAgentConfig(IISConfig).then(res => {
        if (res.code === 0) {
          // message.success('保存成功');
        } else {
          message.error(res.msg);
        }
      });
    }
  };
  const tabRender = name => {
    return (
      <>
        {name}
        {/* <CheckCircleOutlined /> */}
      </>
    );
  };
  return (
    <div className={styles.detailContent}>
      <PageHeader
        className="site-page-header"
        onBack={() =>
          history.push({
            pathname: '/platform/notificationNew',
          })
        }
        title="返回"
        subTitle=""
      />
      <div className={styles.configContent}>
        <Divider
          orientation="left"
          style={{
            borderTopColor: '#99bbe8',
            color: '#15428b',
            fontWeight: 700,
          }}
        >
          基础设置
        </Divider>
        <Form form={baseForm} layout="inline">
          <Form.Item label="方案名称" name="SchemeName">
            <Input />
          </Form.Item>
          <Form.Item label="是否启用" name="IsEnable" valuePropName="checked">
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>
          <Form.Item label="启用定时计划" name="TimeJobOpen" valuePropName="checked">
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>
          <Form.Item label="推送组">
            <Input.Group
              compact
              style={{
                display: 'flex',
              }}
            >
              <Form.Item name="TimeJobGroup">
                <Input readOnly />
              </Form.Item>
              <Tooltip title="选择推送组">
                <Button icon={<UsergroupAddOutlined />} onClick={() => setShowRoleModal(true)} />
              </Tooltip>
            </Input.Group>
          </Form.Item>
          <Form.Item label="定时计划">
            <Input.Group
              compact
              style={{
                display: 'flex',
              }}
            >
              {/* <Input /> */}
              <Tooltip title="配置定时计划">
                <Button
                  icon={<FieldTimeOutlined />}
                  onClick={() => {
                    setFlag(flag + 1);
                    timePlan.current.setPreviewVisible(true);
                  }}
                />
              </Tooltip>
            </Input.Group>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={onFinish}>
              保存
            </Button>
          </Form.Item>
        </Form>
        <Divider
          orientation="left"
          style={{
            borderTopColor: '#99bbe8',
            color: '#15428b',
            fontWeight: 700,
          }}
        >
          方案管理
        </Divider>
        <Tabs>
          <Tabs.TabPane tab={tabRender('平台消息配置')} key="1">
            <div style={{ height: '100%', overflowY: 'scroll' }}>
              <PlatformConfig
                id={schemeMsg ? schemeMsg?.Id : schemeId.current}
                menuWebList={menuWebList}
                menuMoblieList={menuMoblieList}
                formValue={schemeMsg?.Platform}
              />
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane tab="短信消息配置" key="2">
            <ShortMessageConfig
              template={msgTemplates['短信'] || []}
              formValue={schemeMsg?.SMS}
              id={schemeMsg ? schemeMsg?.Id : schemeId.current}
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="微信公众号配置" key="3">
            <WeChatConfig
              template={msgTemplates['公众号'] || []}
              menuMoblieList={menuMoblieList}
              formValue={schemeMsg?.Wechat}
              id={schemeMsg ? schemeMsg?.Id : schemeId.current}
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="企业微信配置" key="4">
            <EnterpriseWeChatConfig
              menuMoblieList={menuMoblieList}
              formValue={schemeMsg?.WorkWechat}
              id={schemeMsg ? schemeMsg?.Id : schemeId.current}
            />
          </Tabs.TabPane>
        </Tabs>
      </div>
      <RoleModal
        selectValue={roleSelect.current.join('|')}
        visible={showRoleModal}
        rolCallBack={roleList => rolCallBack(roleList)}
        onCancel={() => {
          setShowRoleModal(false);
        }}
      />
      <VisibleIISAgentConfig
        ref={timePlan}
        agentConfig={schemeMsg?.AgentConfig}
        value={baseForm.getFieldValue('SchemeName')}
        onIISAgentSubmit={onIISAgentSubmit}
      />
    </div>
  );
};

export default SchemeDetails;
