/* eslint-disable radix */
/* eslint-disable camelcase */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import SiteModal from '@/components/Modal/SiteModa';
import {
  Form,
  Input,
  notification,
  Select,
  Checkbox,
  message,
  Button,
  Card,
  Row,
  Col,
  Switch as Switchs,
} from 'antd';
import BaseForm from '@/components/BaseForm/index';
import { Switch } from 'react-router';
import { iteratee } from 'lodash';
import v from 'voca';

import { UsergroupDeleteOutlined, IdcardOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useHistory } from 'react-router-dom';
import VisibleRoleModal from '../projectManage/components/RolseSelect/VisibleRoleModal';
import VisibleIISAgentConfig from '../projectManage/components/IISAgentConfig/VisibleIISAgentConfig';
import RoleModal from '../projectManage/components/RolseSelect/RoleModal';
import {
  GetMessageTemplate,
  UpdateMessageConfig,
  InsertMessageConfig,
  AddIISAgentConfig,
  // eslint-disable-next-line import/no-duplicates
} from '@/services/messagemanage/messagemanage';

import styles from './schemeDetail.less';
const { Item } = Form;
const { TextArea } = Input;
const EditModal = props => {
  const history = useHistory();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [plan, setPlan] = useState('');
  const [isStart, setIsStart] = useState(false);
  const [IISConfig, setIISConfig] = useState(null);
  const [isUse, setIsUse] = useState('0');
  const [btnType, setBtnType] = useState('定时推送');
  const { template, confirmModal, currentPage } = props.location.state;
  const [currentTrench, setCurrentTrench] = useState({
    isMessageShow: false,
    isAPPShow: false,
    isWEBShow: false,
    isWXShow: false,
    isEnterpriseWXShow: false,
  });
  const [showRoleModal, setShowRoleModal] = useState(false); // 推送组选择角色弹窗
  // eslint-disable-next-line camelcase
  const [APP_ITEMS, setAPP_ITEMS] = useState([]);
  const [WEB_ITEMS, setWEB_ITEMS] = useState([]);
  const [WX_ITEMS, setWX_ITEMS] = useState([]);
  const [MES_ITEMS, setMES_ITEMS] = useState([]);
  const [EN_ITEMS, setEN_ITEMS] = useState([]);
  const [listType, setListType] = useState([
    {
      title: '定时推送',
      desc: '用于周期性简报的定时推送，如智能巡检、运行周报。',
    },
    {
      title: '监控报警',
      desc: '设备硬件故障，阈值超限，状态突变，采集超时等异常情况报警。',
    },
    {
      title: '工单办理',
      desc: '在工单系统中，针对特定人员的通知，包括工作办理、审核、会签、回退等操作。',
    },
    {
      title: '平台公告',
      desc: '由运维人员向所有用户或特定用户发送的事务公告，如系统升级、维护。',
    },
  ]);

  useEffect(() => {
    GetMessageTemplate().then(res => {
      if (res.code === 0) {
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        let arr5 = [];
        // eslint-disable-next-line array-callback-return
        res.data.map((item, index) => {
          if (item.Type === '公众号') {
            arr1.push(item);
          }
          if (item.Type === '短信') {
            arr2.push(item);
          }
          if (item.Type === 'APP') {
            arr3.push(item);
          }
          if (item.Type === 'WEB') {
            arr4.push(item);
          }
          if (item.Type === '企业微信') {
            arr5.push(item);
          }
        });
        setAPP_ITEMS(arr3);
        setMES_ITEMS(arr2);
        setWX_ITEMS(arr1);
        setWEB_ITEMS(arr4);
        setEN_ITEMS(arr5);
      }
    });
  }, []);
  useEffect(() => {
    console.log('template', template);
    console.log(template.WorkWeiXinTemplateId);
    let aa;
    if (template.WorkWeiXinTemplateId == null || template.WorkWeiXinTemplateId === '') {
      aa = '';
    } else {
      // eslint-disable-next-line radix
      aa = parseInt(template.WorkWeiXinTemplateId);
    }
    if (template.ThemeName) {
      form.setFieldsValue({
        name: template.MsgType,
        isStart: template.IsStarted === '0' ? '关闭' : '开启',
        to_person: template.PushGroup,
        push_mode: template.PushMode === null ? '' : template.PushMode.split(','),

        app_template: template.AppTemplateID,
        app_path: template.AppFunctionPath,
        wx_template: template.PublicTemplateID ? parseInt(template.PublicTemplateID) : '',
        h5_path: template.PublicPath,
        miniprogram_path: template.MiniAppRoute,
        web_template: template.WebTemplateID,
        web_path: template.WebFunctionPath,
        message_template: template.MsgTemplateID,
        enterprise_template: aa,
      });
      setPlan(template.MsgType);
      setBtnType(template.type);
      setIsUse(template.IsStarted);
      setCurrentTrench({
        isAPPShow: !!(template.PushMode && template.PushMode.split(',').indexOf('平台弹框') > -1),
        isWXShow: !!(template.PushMode && template.PushMode.split(',').indexOf('公众号推送') > -1),
        isWEBShow: !!(template.PushMode && template.PushMode.split(',').indexOf('平台弹框') > -1),
        isMessageShow: !!(
          template.PushMode && template.PushMode.split(',').indexOf('短信推送') > -1
        ),
        isEnterpriseWXShow: !!(
          template.PushMode && template.PushMode.split(',').indexOf('企业微信推送') > -1
        ),
      });
    } else {
      console.log(111);
      setBtnType('定时推送');
    }
  }, [props]);
  const onNameChange = e => {
    setPlan(e.target.value);
  };

  const onSubmit = () => {
    let fv = form.getFieldValue();
    console.log(fv.enterprise_template);
    let aa;
    if (fv.enterprise_template === undefined) {
      aa = '';
    } else {
      aa = fv.enterprise_template.toString();
    }
    console.log(fv);

    let push_mode = [];
    Object.keys(currentTrench).forEach(key => {
      console.log(key, 'key');
      switch (key) {
        case 'isAPPShow':
          if (currentTrench[key]) {
            push_mode.push('平台弹框');
          }
          break;
        case 'isWEBShow':
          if (currentTrench[key]) {
            push_mode.push('平台弹框');
          }
          break;
        case 'isWXShow':
          if (currentTrench[key]) {
            push_mode.push('公众号推送');
          }
          break;
        case 'isMessageShow':
          if (currentTrench[key]) {
            push_mode.push('短信推送');
          }
          break;
        case 'isEnterpriseWXShow':
          if (currentTrench[key]) {
            push_mode.push('企业微信推送');
          }
          break;
        default:
          break;
      }
    });

    if (template.ThemeName) {
      let a = {
        ID: template.ID,
        ThemeName: template.ThemeName,
        MsgType: fv.name,
        PublicTemplateID: fv.wx_template.toString() ? fv.wx_template.toString() : WX_ITEMS[0].Id,
        PublicConfig: template.PublicConfig,
        PublicPath: fv.h5_path,
        MsgTemplateName: template.MsgTemplateName,
        MsgTemplateCode: template.MsgTemplateCode,
        MsgConfig: template.MsgConfig,
        MiniAppRoute: fv.miniprogram_path,
        AppFunctionPath: fv.app_path,
        AppConfig: template.AppConfig,
        WebFunctionPath: fv.web_path,
        WebConfig: template.WebConfig,
        IsDelete: template.IsDelete,
        InputTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        Pusher: template.Pusher,
        PushMode: push_mode.join(','),
        PushPath: template.PushPath,
        IsStarted: isUse,
        MsgTemplateID: fv.message_template ? fv.message_template : MES_ITEMS[0].Id,
        AppTemplateID: fv.app_template ? fv.app_template : APP_ITEMS[0].Id,
        WebTemplateID: fv.web_template ? fv.web_template : WEB_ITEMS[0].Id,
        PushGroup: fv.to_person ? fv.to_person.toString() : '',
        WorkWeiXinTemplateId: aa,
      };

      UpdateMessageConfig(a).then(res => {
        if (res.code === 0) {
          if (IISConfig) {
            // eslint-disable-next-line no-shadow
            AddIISAgentConfig(IISConfig).then(res => {
              if (res.code === 0) {
                message.success('保存成功');
                back();
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.msg,
                });
              }
            });
          } else {
            back();
            message.success('保存成功');
          }
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    } else {
      let bb;
      if (fv.enterprise_template === undefined) {
        bb = '';
      } else {
        bb = fv.enterprise_template.toString();
      }
      console.log(fv.enterprise_template);
      let b = {
        ThemeName: '定时推送',
        MsgType: fv.name,
        PublicTemplateID: fv.wx_template ? fv.wx_template.toString() : WX_ITEMS[0].Id,
        PublicConfig: template.PublicConfig,
        PublicPath: fv.h5_path,
        MsgTemplateName: template.MsgTemplateName,
        MsgTemplateCode: template.MsgTemplateCode,
        MsgConfig: template.MsgConfig,
        MiniAppRoute: fv.miniprogram_path,
        AppFunctionPath: fv.app_path,
        AppConfig: template.AppConfig,
        WebFunctionPath: fv.web_path,
        WebConfig: template.WebConfig,
        IsDelete: template.IsDelete,
        InputTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        Pusher: template.Pusher,
        PushMode: push_mode.join(','),
        PushPath: template.PushPath,
        IsStarted: isUse,
        MsgTemplateID: fv.message_template ? fv.message_template : MES_ITEMS[0].Id,
        AppTemplateID: fv.app_template ? fv.app_template : APP_ITEMS[0].Id,
        WebTemplateID: fv.web_template ? fv.web_template : WEB_ITEMS[0].Id,
        PushGroup: fv.to_person ? fv.to_person.toString() : '',
        WorkWeiXinTemplateId: bb,
      };
      InsertMessageConfig(b).then(res => {
        if (res.code === 0) {
          if (IISConfig) {
            // eslint-disable-next-line no-shadow
            AddIISAgentConfig(IISConfig).then(res => {
              if (res.code === 0) {
                message.success('保存成功');
                back();
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.msg,
                });
              }
            });
          } else {
            back();
            message.success('保存成功');
          }
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    }
  };

  const onIISAgentSubmit = value => {
    console.log('value', value);
    setIISConfig(value);
  };

  const onPushSubmit = value => {
    console.log(value, 'onPushSubmit');
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 2,
    },
    wrapperCol: {
      span: 24,
    },
  };
  const onChange = value => {
    setIsUse(value ? '1' : '0');
  };
  const back = () => {
    history.push({
      pathname: '/platform/notification',
      query: {
        currentPage,
      },
    });
  };
  const tailLayout = {
    wrapperCol: { offset: 21, span: 24 },
  };
  const onTypeChange = (value, type) => {
    let data = { ...currentTrench };
    data[type] = value;
    setCurrentTrench(data);
  };
  // 推送组选择角色
  const rolCallBack = useCallback(list => {
    console.log(list, 'list');
    let strList = [];
    if (list.length > 0) {
      list.forEach(item => {
        console.log(item, 'item');
        item.checkedList.forEach(ele => {
          strList.push(ele);
        });
      });
      form.setFieldsValue({ to_person: strList.join(',') });
      setShowRoleModal(false);
      console.log(strList.join(','));
    }
  });

  return (
    <div className={styles.editModal_container}>
      <Form form={form} onFinish={onSubmit}>
        <div className={styles.content}>
          <Card title="方案" style={{ width: '100%' }}>
            <Item
              label="方案名称"
              name="name"
              labelAlign="right"
              rules={[
                {
                  required: true,
                  message: '请输入方案名称',
                },
              ]}
            >
              <Input
                style={{ width: '25rem' }}
                placeholder="请输入方案名称"
                disabled={!!template.ThemeName}
                onChange={onNameChange}
              />
            </Item>
            <Item label="方案类型" labelAlign="right" style={{ marginLeft: '12px' }}>
              <div className={styles.cardList}>
                {listType.map(item => (
                  <div key={item.title} className={styles.cardListItem}>
                    <Button
                      type={item.title === btnType ? 'primary' : 'default'}
                      style={{ cursor: 'not-allowed', marginRight: '1rem' }}
                    >
                      {item.title}
                    </Button>{' '}
                    <span>{item.desc}</span>
                  </div>
                ))}
              </div>
            </Item>
          </Card>
          {btnType === '定时推送' && (
            <Card title="推送信息" style={{ width: '100%', marginTop: '1rem' }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Item labelCol={{ span: 6 }}>
                  <div style={{ display: 'flex' }}>
                    <Item
                      label="推送组"
                      name="to_person"
                      style={{ marginTop: '50px', marginLeft: '32px' }}
                    >
                      <Input disabled />
                    </Item>
                    <IdcardOutlined
                      onClick={() => {
                        setShowRoleModal(true);
                      }}
                      style={{
                        marginTop: '58px',
                        marginLeft: '10px',
                        fontSize: '22px',
                        color: '#1890FF',
                        cursor: 'pointer',
                      }}
                    />
                  </div>
                  {/* <VisibleRoleModal
                    style={{
                      display: 'flex',
                      width: '35rem',
                      alignItems: 'center',
                    }}
                    onSubmit={onPushSubmit}
                    selectValue={
                      template && template.PushGroup ? template.PushGroup : []
                    }
                    title={
                      <UsergroupDeleteOutlined style={{ fontSize: '18px' }} />
                    }
                  /> */}
                </Item>

                <div
                  style={{
                    display: 'flex',
                    width: '30rem',
                    margin: '0 2rem',
                    alignItems: 'center',
                  }}
                >
                  推送计划：{' '}
                  <VisibleIISAgentConfig
                    agentConfig={template.item && template.item.AgentConfig}
                    value={plan}
                    onIISAgentSubmit={onIISAgentSubmit}
                  />
                </div>
                <span>
                  是否启用：
                  <Switchs checked={isUse !== '0'} onChange={onChange} />
                </span>
              </div>
            </Card>
          )}
          <div className={styles.push_trench}>
            <Row>
              <Col xxl={8} xl={12} sm={24} xs={24}>
                {
                  <div className={styles.trench_card}>
                    <div className={styles.card_title}>
                      <div className={styles.lable}>APP</div>
                      <Switchs
                        onChange={e => onTypeChange(e, 'isAPPShow')}
                        checked={currentTrench.isAPPShow}
                      />
                    </div>
                    <div className={styles.card_body}>
                      <Item label="模板" name="app_template" labelCol={{ span: 6 }}>
                        <Select style={{ width: '97%' }} disabled={!currentTrench.isAPPShow}>
                          {APP_ITEMS.map((item, idx) => (
                            <Select.Option value={item.Id} key={idx}>
                              {item.LikeName}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                      <Item label="功能路径" name="app_path" labelCol={{ span: 6 }}>
                        <TextArea
                          rows={1}
                          style={{ width: '97%' }}
                          disabled={!currentTrench.isAPPShow}
                          placeholder="请输入功能路径"
                        />
                      </Item>
                    </div>
                  </div>
                }
              </Col>
              <Col xxl={8} xl={12} sm={24} xs={24}>
                {
                  <div className={styles.trench_card}>
                    <div className={styles.card_title}>
                      <div className={styles.lable}>公众号</div>
                      <Switchs
                        onChange={e => onTypeChange(e, 'isWXShow')}
                        checked={currentTrench.isWXShow}
                      />
                    </div>
                    <div className={styles.card_body}>
                      <Item label="模板" name="wx_template" labelCol={{ span: 6 }}>
                        <Select style={{ width: '97%' }} disabled={!currentTrench.isWXShow}>
                          {WX_ITEMS.map((item, idx) => (
                            <Select.Option value={item.Id} key={idx}>
                              {item.LikeName}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                      <Item label="H5路由" name="h5_path" labelCol={{ span: 6 }}>
                        <Input
                          style={{ width: '97%' }}
                          disabled={!currentTrench.isWXShow}
                          placeholder="请输入功能路径"
                        />
                      </Item>
                      <Item label="小程序路由" name="miniprogram_path" labelCol={{ span: 6 }}>
                        <Input
                          style={{ width: '97%' }}
                          disabled={!currentTrench.isWXShow}
                          placeholder="请输入功能路径"
                        />
                      </Item>
                    </div>
                  </div>
                }
              </Col>
              <Col xxl={8} xl={12} sm={24} xs={24}>
                {
                  <div className={styles.trench_card}>
                    <div className={styles.card_title}>
                      <div className={styles.lable}>WEB</div>
                      <Switchs
                        onChange={e => onTypeChange(e, 'isWEBShow')}
                        checked={currentTrench.isWEBShow}
                      />
                    </div>
                    <div className={styles.card_body}>
                      <Item label="模板" name="web_template" labelCol={{ span: 6 }}>
                        <Select style={{ width: '97%' }} disabled={!currentTrench.isWEBShow}>
                          {WEB_ITEMS.map((item, idx) => (
                            <Select.Option value={item.Id} key={idx}>
                              {item.LikeName}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                      <Item label="功能路径" name="web_path" labelCol={{ span: 6 }}>
                        <TextArea
                          rows={1}
                          style={{ width: '97%' }}
                          disabled={!currentTrench.isWEBShow}
                          placeholder="请输入功能路径"
                        />
                      </Item>
                    </div>
                  </div>
                }
              </Col>
              <Col xxl={8} xl={12} sm={24} xs={24}>
                {
                  <div className={styles.trench_card}>
                    <div className={styles.card_title}>
                      <div className={styles.lable}>短信推送</div>
                      <Switchs
                        onChange={e => onTypeChange(e, 'isMessageShow')}
                        checked={currentTrench.isMessageShow}
                      />
                    </div>
                    <div className={styles.card_body}>
                      <Item label="模板" name="message_template" labelCol={{ span: 6 }}>
                        <Select style={{ width: '97%' }} disabled={!currentTrench.isMessageShow}>
                          {MES_ITEMS.map((item, idx) => (
                            <Select.Option value={item.Id} key={idx}>
                              {item.LikeName}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                    </div>
                  </div>
                }
              </Col>
              <Col xxl={8} xl={12} sm={24} xs={24}>
                {
                  <div className={styles.trench_card}>
                    <div className={styles.card_title}>
                      <div className={styles.lable}>企业微信</div>
                      <Switchs
                        onChange={e => onTypeChange(e, 'isEnterpriseWXShow')}
                        checked={currentTrench.isEnterpriseWXShow}
                      />
                    </div>
                    <div className={styles.card_body}>
                      <Item label="模板" name="enterprise_template" labelCol={{ span: 6 }}>
                        <Select
                          style={{ width: '97%' }}
                          disabled={!currentTrench.isEnterpriseWXShow}
                        >
                          {EN_ITEMS.map((item, idx) => (
                            <Select.Option value={item.Id} key={idx}>
                              {item.LikeName}
                            </Select.Option>
                          ))}
                        </Select>
                      </Item>
                    </div>
                  </div>
                }
              </Col>
            </Row>
          </div>
        </div>
        <Row>
          <Col span={24}>
            <div style={{ marginTop: '1rem', display: 'flex', justifyContent: 'flex-end' }}>
              <Button htmlType="button" onClick={back} style={{ marginRight: '2rem' }}>
                返回
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
      <div />
      <RoleModal
        selectValue={form.getFieldValue('to_person')}
        visible={showRoleModal}
        rolCallBack={roleList => rolCallBack(roleList)}
        onCancel={() => {
          setShowRoleModal(false);
        }}
      />
    </div>
  );
};
export default EditModal;
