import React , { useEffect , useState } from 'react';
import { Button , Popconfirm } from 'antd';
import { Cancel } from '../../Component/layout';
import Item from './StageItem';

function Stage({ 
  templates , 
  datas , 
  saveDatas , 
  saveFunc , 
  stepName , 
  deleteStep , 
  deleteFunc , 
  deleteFlag 
}){
  const [ stepList , setStepList ] = useState(undefined);
  const [ temp , setTemp ] = useState(undefined);

  useEffect(()=>{
    if(templates && templates.length > 0){
      setTemp(templates);
    }
  },[templates])

  useEffect(()=>{
    if(datas){
      if(datas.length > 0 && stepList !== datas){
        setStepList(datas);
      }else if(datas.length === 0){
        let list = [];
        setStepList(list);
      }
    }
  },[datas])

  // 添加步骤
  function addFunc(){
    let list = stepList;
    let length = list ? list.length : 0;
    let pre = temp && temp.length > 0 && temp[0];
    let c = pre && pre.category;
    let child = pre && pre.templates && pre.templates.length > 0 && pre.templates[0];
    let step = 
    {
      "category":c,
      "step_name": stepName+`${length + 1}`,
      "show_index": length + 1,
      "content":child.content,
      "template_id":child.id,
      "hide":false
    }
    list.push(step);
    saveDatas(list);
  }

  // 将修改的对应项保存在数组中
  function saveItems(content,id,cate,key){
    let item = stepList;
    item[key].content = content;
    item[key].template_id = id;
    item[key].category = cate;
    saveDatas([...item]);
  }

  function slideItems(key,hide){
    let item = stepList;
    item[key].hide = !hide;
    setStepList([...item]);
    saveDatas(item);
  }

  function deleteItem(id,key){
    deleteStep(id,key);
  }
  // 点击下一步时
  function nextStep(btn){
    saveFunc(undefined,undefined,undefined,undefined,btn);
  }

  return(
    <div>
      {
        stepList && stepList.length > 0 && stepList.map((item,key)=>{
          return(
            <Item item={item} templates={temp} k={key} saveItems={saveItems} slideItems={slideItems} deleteStep={deleteItem}/>
          )
        })
      }
      <a className="addStageBtn" onClick={addFunc}>+ 添加步骤</a>
      <div className="mt20">
        <Button type="primary" onClick={()=>nextStep("last")}>上一步</Button>
        <Button className="ml20" type="primary" onClick={()=>nextStep("next")}>下一步</Button>
        {!deleteFlag && 
          <Popconfirm title={'确定要删除当前阶段吗'} okText="是" cancelText="否" onConfirm={deleteFunc}>
            <Cancel className="ml20">删除</Cancel>
          </Popconfirm>
        }
      </div>
    </div>
  )
}
export default Stage;