import { Checkbox } from "antd";
import React, { useEffect, useState } from "react";
import axios from 'axios';
import './Index.scss';

function NoticeManager(props){
  const {current_user} = props;

  const [settingTypes, setSettingTypes] = useState();
  const [userNotification, setUserNotification] = useState();
  const [userEmail, setUserEmail] = useState();

  function onChange(type,e,setting){
    let notification_body = userNotification;
    let email_body = userEmail;
    if(type){//站内信
      notification_body[setting] = e.target.checked;
    }else{//邮件
      email_body[setting] = e.target.checked;
    }
    axios.post(`/users/${current_user.login}/template_message_settings/update_setting.json`,{
      setting:{
        notification_body:notification_body,
        email_body:email_body
      }
    }).then(response=>{
      if(response && response.status === 0){
        getUserSettings();
      }
    })
  }

  function getUserSettings(){
    axios.get(`/users/${current_user.login}/template_message_settings.json`).then((response)=>{
      if(response && response.status === 200 ){
        setUserEmail(response.data.email_body);
        setUserNotification(response.data.notification_body);
      }
    })
  }

  useEffect(()=>{
    axios.get("/template_message_settings.json").then(response => {
      if (response && response.status === 200) {
        setSettingTypes(response.data.setting_types);
      }
    })
    getUserSettings();
  },[])

  return(
    <div className="notice01">
      <div className="sshHead">
        <span className="text-shadow07">通知管理</span>
      </div>
      <div>
        <span className="notice-manager-tip">您可以通过通知管理来选择接受通知的方式</span>
        {settingTypes && userNotification && userEmail && settingTypes.map((item,key)=>{
          return(
            item.type_name && <div key={key}>
              <div className="manager-cont-top">{item.type_name}</div>
              {item.settings.map((i, k) => {
                const setting = item.type.substring(item.type.indexOf("::")+2)+"::"+i.key;
                return (
                  <div className="manager-cont" key={k}>
                    <div className="manager-cont-title">{i.name}</div>
                    <Checkbox disabled = {i.notification_disabled} defaultChecked={userNotification[setting]} onChange={(e)=>{onChange(true,e,setting)}}>站内信</Checkbox>
                    <Checkbox disabled = {i.email_disabled} defaultChecked={userEmail[setting]} onChange={(e)=>{onChange(false,e,setting)}}>邮件</Checkbox>
                  </div>
                )
              })}
            </div>
          )
        })}
      </div>
    </div>
  )
}
export default NoticeManager;