import React , { useEffect , useState } from 'react';

function Choosen({ chooseFunc, temp , templateId , category }){
  const [ tempId, setTemId ] = useState(undefined);
  const [ cate , setCate ]= useState(undefined);
  const [ templates , setTemplates ] = useState(undefined);
  const [ categories , setCategories ] = useState(undefined);

  useEffect(()=>{
    if(templateId){
      setTemId(templateId);
    }
  },[templateId])

  useEffect(()=>{
    if(category){
      setCate(category);
    }
  },[category])
  

  useEffect(()=>{
    if(temp && temp.length > 0){
      if(temp[0].category !== "初始化"){
        setCategories(temp);
      }else{
        setCategories(undefined);
      }
      if(category && temp[0].category !== "初始化" && category !== "初始化"){
        let c = temp.filter(item=>item.category === category);
        let t = c && c.length > 0 && c[0].templates;
        setTemplates(t);
        setCate(category);
      }else{
        setTemplates(temp[0].templates);
        setCate(temp[0].category);
      }
    }else{
      setTemplates(undefined);
      setCate(undefined);
      setCategories(undefined);
    }
  },[temp,category])

  // 选择类别
  function changeCate(cate){
    setCate(cate);
    let c = categories && categories.filter(item=>item.category === cate);
    let t = c && c[0].templates;
    setTemplates(t);
    let m_t_id = t && t.length>0 && t[0].id;
    let m_t_content = t && t.length>0 && t[0].content;
    setTemId(m_t_id);
    chooseFunc && chooseFunc(m_t_content,m_t_id,cate);
  }


  // 选择模板
  function chooseOption(id){
    let item = templates.filter(item=>item.id === id);
    let content = item && item.length >0 && item[0].content;
    chooseFunc && chooseFunc(content,id,cate);
    setTemId(id);
  }

  return(
    <React.Fragment>
      {
        categories && categories.length > 0 &&
        <div className="choosenList">
          <span>模板类别：</span>
          <ul>
          {
            categories.map((item,key)=>{
              return(
                <li className={cate === item.category ?"active":""} onClick={()=>changeCate(item.category)}>{item.category}</li>)
              })
            }
          </ul>
        </div>
      }
      {
        templates && templates.length> 0 &&
        <div className="choosenList">
          <span>模板选择：</span>
          <ul>
            {
              templates.map((item,key)=>{
                return(
                  <li className={tempId === item.id ? "active":""} onClick={()=>chooseOption(item.id)}>{item.template_name}</li>
                )
              })
            }
          </ul>
        </div>
      }
    </React.Fragment>
  )
}
export default Choosen;