import React , { useEffect , useState , forwardRef , useRef } from 'react';
import { Form , InputNumber } from 'antd';
import { Box , LongWidth } from '../../Component/layout';
import DropMenu from '../Component/dropMenu';
import ChooseMenu from '../Component/chooseMenu';
import AddTagsBox from '../Component/addTagsBox';
import Date from '../Component/date';
import NewPanel from '../Component/newPanel';
import axios from 'axios';

function New(props){
  // history search 是否含有意见反馈标识
  const {location:{search}, projectDetail} = props;
  const feedBack = search && search.indexOf('type=feedback') !== -1;
  // 里程碑id
  const milepostId = props.match.params.milepostId;


  const [ statusList , setStatusList ] = useState([]);
  const [ prioritiesList , setPrioritiesList ] = useState([]);
  const [ chargeList , setChargeList ] = useState([]);
  const [ charge , setCharge ] = useState(undefined);
  const [ millstoneList , setMillstoneList ] = useState([]);
  const [ millstone , setMillstone ] = useState(undefined);
  const [ tagList , setTagList ] = useState(undefined);
  const [ tag , setTag ] = useState(undefined);
  const [ branchList , setBranchList ] = useState(undefined);
  const [ branch , setBranch ] = useState(undefined);


  const [ assigner_choose , setAssigner_choose ] = useState([]);
  const [ prioritie_choose , setPrioritie_choose ] = useState([]);
  const [ status_choose , setStatus_choose ] = useState([]);
  const [ tag_choose , setTag_choose ] = useState([]);
  const [ millstone_choose , setMillstone_choose ] = useState([]);
  const [ branch_choose , setBranch_choose ] = useState([]);

  const [ start_date, setStartDate ] = useState("");//moment().format('YYYY-MM-DD')
  const [ due_date, setDueDate ] = useState("");

  const [ rewardAmount , setRewardAmount ] = useState(undefined);
  const [ rewardFlag , setRewardFlag ] = useState(false);
  
  const owner = props.match.params.owner;
  const projectsId = props.match.params.projectsId;
  const permission = props && props.projectDetail && props.projectDetail.permission;
  const { open_blockchain } = props;
  const ref = useRef(null);

  useEffect(()=>{
    if(projectDetail){
      if(feedBack){
        document.title = `意见反馈`;
        return;
      }
      const { author, name} = projectDetail;
      document.title = `新建疑修-${author.name}/${name}`
    }
  },[projectDetail, feedBack])

  useEffect(()=>{
    if(milepostId){
      getMillstone(milepostId);
    }
  },[milepostId])


  // 获取状态列表
  useEffect(()=>{
    getStatus();
  },[])
  function getStatus(){
    const url = `/v1/${owner}/${projectsId}/issue_statues`;
    axios.get(url).then(result=>{
      if(result && result.data){
        let status = result.data.statues;
        setStatusList(status);
        if(status && status.length>0){
          setStatus_choose(status.filter(i=>i.id === 1));
        }
      }
    })
  }
  // 获取优先级列表
  useEffect(()=>{
    getPriorities();
  },[])

  function getPriorities(){
    const url = `/v1/${owner}/${projectsId}/issue_priorities`;
    axios.get(url).then(result=>{
      if(result && result.data){
        let priorities = result.data.priorities;
        let array =[];
        let colors = ["#1abcb1","#28be6c","#e67e22","#db3d1d"];
        if(priorities && priorities.length>0){
          array = priorities.map((i,k)=>{
            let arr = {...i,color:colors[k]}
            return arr;
          })
        }
        setPrioritiesList(array);
        setPrioritie_choose(array.filter(i=>i.id === 2));
      }
    })
  }

  // 获取负责人列表
  useEffect(()=>{
    getCharge();
  },[charge])

  function getCharge(){
    const url = `/v1/${owner}/${projectsId}/collaborators`;
    axios.get(url,{params:{keyword:charge,only_name:true}}).then(result=>{
      if(result && result.data){
        setChargeList(result.data.collaborators);
        if(feedBack && !charge){
          // 指定指派成员-意见反馈
          const {collaborators} = result.data;
          const id = collaborators.filter(item=>item.id === 86107);
          setAssigner_choose(id.length === 0 ? [collaborators[0]] : id)
        }
      }
    })
  }
  // 获取里程碑列表
  useEffect(()=>{
    getMillstone(millstone);
  },[millstone])

  function getMillstone(keyword){
    const url = `/v1/${owner}/${projectsId}/milestones`;
    axios.get(url,{params:{keyword,only_name:true}}).then(result=>{
      if(result && result.data){
        let milestones = result.data.milestones;
        if(milepostId && milepostId === keyword){
          setMillstone_choose(milestones);
        }else{
          setMillstoneList(milestones);
        }
      }
    })
  }
  // 获取标记列表
  useEffect(()=>{
    getSign();
  },[tag])
  function getSign(){
    const url = `/v1/${owner}/${projectsId}/issue_tags`;
    axios.get(url,{params:{keyword:tag,only_name:true}}).then(result=>{
      if(result && result.data){
        setTagList(result.data.issue_tags);
      }
    })
  }
  // 获取标记列表
  useEffect(()=>{
    getBranch(branch);
  },[branch])
  function getBranch(branch){
    if(branch){
      let b = [...branchList];
      let l = b.filter(i=>i.name.indexOf(branch)>-1);
      setBranchList(l);
      return ;
    }
    const url = `/${owner}/${projectsId}/branches.json`;
    axios.get(url,{params:{keyword:tag}}).then(result=>{
      if(result && result.data){
        setBranchList(result.data);
      }
    })
  }


  // 创建
  function createFunc(values,fileList,receivers_login,description){
    const { subject } = values;
    const url = `/v1/${owner}/${projectsId}/issues`;
    let b = branch_choose && branch_choose.length>0 ? branch_choose.map(i=>{return i.name}) :undefined;
    let t = tag_choose && tag_choose.length>0 ? tag_choose.map(i=>{return i.id}) :undefined;
    let a = assigner_choose && assigner_choose.length>0 ? assigner_choose.map(i=>{return i.id}) :undefined;
    let m = millstone_choose && millstone_choose.length>0 ? millstone_choose.map(i=>{return i.id}) :undefined;
    let p = prioritie_choose && prioritie_choose.length>0 ? prioritie_choose.map(i=>{return i.id}) :undefined;
    let s = status_choose && status_choose.length>0 ? status_choose.map(i=>{return i.id}) :undefined;
    axios.post(url,{
      description,subject,
      branch_name:b && b.join(","),
      status_id:s && s.join(","),
      priority_id:p && p.join(","),
      milestone_id:m && m.join(","),
      issue_tag_ids:t,
      assigner_ids:a,
      attachment_ids:fileList,
      start_date,due_date,receivers_login,
      blockchain_token_num:rewardAmount
    }).then(result=>{
      if(result && result.data && result.data.project_issues_index){
        window.scrollTo(0,0);
        props.showNotification("任务创建成功！");
        props.history.push(`/${owner}/${projectsId}/issues/${result.data.project_issues_index}`);
      }
    }).catch(error=>{})
  }


  function changeAmount(value){
    if(value && value > 0){
      setRewardAmount(value);
    }
    if(!value){
      setRewardAmount(value);
    }
  }
  return(
    <div>
      <p className="font-17 color-grey-3 mt20 mb15">新建疑修</p>
      <Box>
        <LongWidth>
          {/* 意见反馈初始化内容 */}
          <NewPanel {...props} createFunc={createFunc} owner = {owner} projectsId = {projectsId} desc={feedBack ? "####问题描述\n\n\n####重现问题步骤\n\n\n####截图\n\n\n####建议解决办法\n" : undefined}/>
        </LongWidth>
        <div className="shortwidth">
          <ChooseMenu 
            placeholder="负责人" 
            menus={chargeList}
            searchFunc={(value)=>{setCharge(value)}}
            headImg
            selectValueList={assigner_choose}
            chooseFunc={(list)=>{setAssigner_choose(list);}}
            double={5}
            removeFlag
          />
          <DropMenu 
            placeholder="状态" 
            menus={statusList}
            selectValueList={status_choose}
            mustFlag
            editFlag={false}
            chooseFunc={(list)=>{setStatus_choose(list);}}
          />
          <DropMenu 
            placeholder="优先级" 
            menus={prioritiesList}
            selectValueList={prioritie_choose}
            colorFlag="1"
            mustFlag
            chooseFunc={(list)=>{setPrioritie_choose(list);}}
          />
          <ChooseMenu 
            placeholder="标记" 
            menus={tagList}
            searchFunc={(value)=>{setTag(value)}}
            selectValueList={tag_choose}
            chooseFunc={(list)=>{setTag_choose(list);}}
            double={3}
            colorFlag="2"
            removeFlag
            onAdd={permission && permission !== "Reporter" ? ()=>{getSign();} :false}
            owner={owner}
            projectsId={projectsId}
          />
          <ChooseMenu 
            placeholder="里程碑" 
            menus={millstoneList}
            auto
            searchFunc={(value)=>{setMillstone(value)}}
            selectValueList={millstone_choose}
            editFlag={milepostId ? true : false}
            chooseFunc={(list)=>{setMillstone_choose(list);}}
          />
          <ChooseMenu 
            placeholder="关联分支" 
            menus={branchList}
            auto
            searchFunc={(value)=>{setBranch(value)}}
            selectValueList={branch_choose}
            chooseFunc={(list)=>{setBranch_choose(list);}}
          />
          {
            open_blockchain &&
            <li style={{paddingBottom:"0px"}}>
              <span>
                悬赏金额
                {/* {!(milepostId ? true : false) && <a onClick={editReward}><i className="iconfont icon-a-bianji12 font-13" style={{color:"#898d9d"}}></i></a> } */}
              </span>
              <InputNumber 
                placeholder="请输入悬赏金额" 
                style={{width:"100%",color:rewardAmount?"#333":"#acb0bf"}} 
                value={rewardAmount} 
                onChange={changeAmount} 
                className="borderNo mt5" disabled={milepostId ? true : false}/>
            </li>
          }
          <Date name="开始日期" today={start_date} setDate={(date)=>setStartDate(date)}/>
          <Date name="结束日期" today={due_date} setDate={(date)=>setDueDate(date)}/>
        </div>
      </Box>
    </div>
  )
}
export default Form.create()(forwardRef(New));