import React , { useEffect , useState } from 'react';
import create from '../Img/create.png';
import { Menu , Dropdown , Icon, Input, Button , Spin , Pagination } from 'antd';
import ColorCard from '../Component/colorCard';
import DelBox from '../Component/delBox';
import axios from 'axios';
import {Link} from 'react-router-dom';
const limit = 15;
function Sign(props){
  const [ edit , setEdit ] = useState(false);
  const [ colors , setColors ] = useState(undefined);
  const [ delVisible , setDelVisible ] = useState(false);
  const [ editId , setEditId ] = useState(undefined);
  const [ list , setList ] = useState(undefined);
  const [ total , setTotal ] = useState(undefined);
  const [ page , setPage ] = useState(1);

  const [ name , setName ] = useState(undefined);
  const [ desc , setDesc ] = useState(undefined);
  const [ order_name , setOrderName ] = useState(undefined);
  const [ order_type , setOrderType ] = useState(undefined);
  const [ nameFlag , setNameFlag ] = useState(undefined);
  const [ defaultColor , setDefaultColor ]= useState(undefined);

  const [ arrayName , setArrayName ] = useState("标记");
  const [ key , setKey ] = useState("0");
  const owner = props.match.params.owner;
  const projectsId = props.match.params.projectsId;
  const { projectDetail } = props;
  const permission = projectDetail && props.projectDetail.permission;


  useEffect(()=>{
    if(permission !== undefined){
      if(!permission || (permission && permission === "Reporter")){
        window.location.href = "/403";
      }
    }
  },[permission])

  useEffect(()=>{
    if(projectDetail){
      const { author, name } = projectDetail;
      document.title = `项目标记-${author.name}/${name}`;
    }
  },[projectDetail])

  useEffect(()=>{
    Init();
  },[page,order_name,order_type])

  function Init(){
    const url = `/v1/${owner}/${projectsId}/issue_tags`;
    axios.get(url,{
      params:{
        page,limit,sort_by:order_name,sort_direction:order_type
      }
    }).then(result=>{
      if(result && result.data){
        setList(result.data.issue_tags);
        setTotal(result.data.total_count);
      }
    })
  }

  function arrayList(e){
    const { eventKey , value , children , createName } = e.item.props;
    setPage(1);
    if(value === order_type && createName === order_name){
      setOrderName(undefined);
      setOrderType(undefined);
      setArrayName("标记");
      setKey("0");
    }else{
      setOrderName(createName);
      setOrderType(value);
      setArrayName(children);
      setKey(eventKey);
    }
  }

  const menu = (
    <Menu onClick={arrayList} selectedKeys={[`${key}`]}>
      <Menu.Item key={"1"} value="desc" createName="created_at">
      按创建时间降序排序
      </Menu.Item>
      <Menu.Item key={"2"} value="asc" createName="created_at">
      按创建时间升序排序
      </Menu.Item>
      <Menu.Item key={"3"} value="desc" createName="issues_count">
      按疑修数量降序排序
      </Menu.Item>
      <Menu.Item key={"4"} value="asc" createName="issues_count">
      按疑修数量升序排序
      </Menu.Item>
      <Menu.Item key={"5"} value="desc" createName="pull_requests_count">
      按合并请求数量降序排序
      </Menu.Item>
      <Menu.Item key={"6"} value="asc" createName="pull_requests_count">
      按合并请求数量升序排序
      </Menu.Item>
    </Menu>
  );

  function getColor(colors){
    setColors(colors);
  }

  function deleteFunc(){
    if(editId){
      const url = `/v1/${owner}/${projectsId}/issue_tags/${editId}`;
      axios.delete(url).then(result=>{
        if(result){
          props.showNotification("项目标记删除成功!");
          if(list && list.length === 1 && page>1){
            setPage(page-1);
          }else{
            Init();
          }
          setDelVisible(false);
        }
      }).catch(error=>{})
    }
  }

  function sureSave(){
    if(!name){
      setNameFlag(true);
    }else{
      setNameFlag(false);
      if(editId){
        // 编辑
        const url = `/v1/${owner}/${projectsId}/issue_tags/${editId}`;
        axios.patch(url,{
          color: colors || defaultColor,
          description: desc,
          name
        }).then(result=>{
          if(result){
            props.showNotification("标记编辑成功！");
            Init();
            cancel();
          }
        }).catch(error=>{})
      }else{
        // 保存
        const url = `/v1/${owner}/${projectsId}/issue_tags`;
        axios.post(url,{
          color: colors || defaultColor,
          description: desc,
          name
        }).then(result=>{
          if(result){
            props.showNotification("标记新增成功！");
            Init();
            cancel();
          }
        }).catch(error=>{})
      }
    }
  }

  function cancel(){
    setNameFlag(false);
    setName(undefined);
    setEdit(false);
    setDesc(undefined);
  }

  function editFunc(i){
    setEditId(i.id);
    setDefaultColor(i.color);
    setName(i.name);
    setDesc(i.description);
    setEdit(true);
  }

  function onChangeValue(e){
    setName(e.target.value);
    if(e.target.value){
      setNameFlag(false);
    }else{
      setNameFlag(true);
    }
  }

  function createSign(){
    const c = Math.random().toString(16).substr(-6);
    c && setDefaultColor(`#${c}`);
    setEdit(true);
  }
  return(
    <div>
      <DelBox 
        visible={delVisible} 
        onCancel={()=>setDelVisible(false)} 
        onSuccess={deleteFunc}
        title="删除标记"
        content={<div style={{paddingTop:"3px"}}><p className="font-15 mb20">您确定要删除当前标记？</p></div>}
      />
      <div className="between mt30 mb25">
        <span><Link to={`/${owner}/${projectsId}/issues`}>疑修</Link> / 项目标记</span>
        <a className="operateButton" onClick={createSign}><img src={create} alt="" className="mr5"/>创建标记</a>
      </div>
      {
        edit &&
        <div className="editbar">
          <div>
            <Input style={{width:"163px"}} className={nameFlag ?"inputred":""} value={name} onChange={onChangeValue} placeholder="名称15字以内"/>
            { nameFlag && <p className="red">请输入标记名称</p>}
          </div>
          <Input style={{width:"276px"}} value={desc} onChange={(e)=>setDesc(e.target.value)} placeholder="描述30字以内"/>
          <ColorCard 
            getColor={getColor}
            defaultColor={defaultColor}
          />
          <span>
            <Button type="primary" ghost onClick={sureSave}>确定</Button>
            <Button ghost className="ml15" onClick={cancel}>取消</Button>
          </span>
        </div>
      }
      <div className="between bluebar">
        <span className="font-17">项目标记({total || 0})</span>
        <Dropdown overlay={menu} trigger={["click"]} placement="bottomRight">
          <span className="cursor">{arrayName}<Icon type="caret-down" className="ml5 color-grey-6" /></span>
        </Dropdown>
      </div>
      {
        list && list.length > 0 ?
        <ul className="signlist">
          {
            list.map((i,k)=>{
              return(
                <li>
                  <p>
                    <span className="square mr10" style={{backgroundColor:`${i.color}`}}></span>
                    <i className="iconfont icon-biaoji mr3 font-12 " style={{color:`${i.color}`}}></i>
                    <span className="task-hide" title={i.name} style={{maxWidth:210}}>{i.name}</span>
                  </p>
                  <p style={{flex:2}} className="task-hide">{i.description}</p>
                  <p>
                    <span className="mr12">{i.issues_count || 0} 疑修</span>
                    <span className="line">{i.pull_requests_count || 0} 合并请求</span>
                  </p>
                  <p>
                    <a className="color-blue mr12" onClick={()=>editFunc(i)}>编辑</a>
                    <a className="color-red line" onClick={()=>{setEditId(i.id);setDelVisible(true);}}>删除</a>
                  </p>
                </li>
              )
            })
          }
        </ul>
        :""
      }
      {
        total > limit &&
        <div style={{paddingBottom:"30px",textAlign:"center"}}>
          <Pagination total={total} current={page} onChange={(p)=>setPage(p)} pageSize={limit}/>
        </div>
      }
      {total === undefined && <div style={{height:344,display:"flex",alignItems:"center",justifyContent:"center"}}><Spin /></div> }
    </div>
  )
}
export default Sign;