import React, {useState} from "react";
import { Table, Modal, Button, message } from 'antd';
import { Link } from "react-router-dom";
import gitHub1 from '../../img/github2.svg';
import gitee1 from '../../img/gitee1.svg';
import anniu from '../../img/anniu.png';
import anniu2 from '../../img/anniu2.png';
import '../index.scss';
import { useEffect } from "react";
import axios from "axios";
import CreateJobModal from './createJobModal';
import Nodata from "../../../Nodata";

function RecordList(props){
  const { owner , projectsId, type } = props.match.params;
  const { storeDetail} = props;
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  // table
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [deleteRecordId, setDeleteRecordId] = useState(undefined);
  const [visible, setVisible] = useState(false);
  const [reload, setReload] = useState(undefined);
  const [visibleNew, setVisibleNew] = useState(false);
  const [branchOptions, setBranchOptions] = useState([]);
  const [logInfo, setLogInfo]= useState([]);

  useEffect(()=>{
    axios.get(`/${owner}/${projectsId}/pulls/get_branches.json`, {}).then(res=>{
      res && setBranchOptions(res.data);
    })
  }, [])

  useEffect(()=>{
    // 获取仓库同步记录
    axios.get(`/${owner}/${projectsId}/synchronizes/jobs.json`, {params: {type: type, limit: pageSize, page: current}}).then(res=>{
      if(res && res.data && res.data.message === "success"){
        // 处理从后往前删除
        if(current !== 1 && res.data.data.length === 0){
          setCurrent(current-1);
        }else{
          res.data.data.map(item=>{
            item.create_time = item.create_time.replace('T', ' ')
          })
          setData(res.data.data);
          setTotal(res.data.count);
        }
      }
    })
  },[reload, pageSize, current])

  // 同步状态errorBox
  let columns = [
    { title: '序号', dataIndex: 'index', className:"recordColumns", render: (text, item, index) => <span>{(current-1)*pageSize+index + 1}</span> },
    { title: type === 'github' ? 'Github分支' : 'Gitee分支', dataIndex: type === 'github' ? 'github_branch': 'gitee_branch', className:"recordColumns taskName"},
    { title: 'GitLink分支', dataIndex: 'gitlink_branch', className:"recordColumns"},
    { title: '创建时间', dataIndex: 'create_time', className:"primaryColor recordColumns"},
    { title: '同步状态', dataIndex: 'status', className:"recordColumns", render: ()=><span className="accomplish statusBox">开启中</span>},
    { title: '操作', dataIndex: 'action', align: 'center', className:"primaryColor recordColumns", render: (text, item)=><span className="deleteRecord" onClick={()=>{setVisible(true);setDeleteRecordId(item.id);}}>删除</span>},
  ]

  const customExpandIcon = (props) => {
    if (props.expanded) {
      return <a className='primaryColor' onClick={e => {
        props.onExpand(props.record, e);
      }}>查看日志<img alt="" src={anniu2} style={{width: '18px'}} className="ml5"/></a>
    } else {
      return <a className='primaryColor' onClick={e => {
        axios.get(`/${owner}/${projectsId}/synchronizes/job_logs.json`, {params:{job_id: props.record.id}}).then(res=>{
          if(res && res.data){
            setLogInfo(res.data.data);
            props.onExpand(props.record, e);
          }
        })
      }}>查看日志<img alt="" src={anniu} style={{width: '18px'}} className="ml5"/></a>
    }
  }

  const expandRow = (record) => {
    return logInfo  && logInfo.length > 0 ? <div className="expandBox">
      {logInfo.map(item=>{
        return <div className="expandCont" key={item.id}>
          {item.create_time + ' [' + item.log_type + '] ' + item.log}
        </div>
      })}
    </div> : <Nodata _html="暂无数据"/>}

  // 展开收起行回调
  function onExpand(expanded, record){
    const keys = new Set(expandedRowKeys);
    if(expanded){
      keys.add(record.id);
    }else{
      keys.delete(record.id);
    }
    setExpandedRowKeys(Array.from(keys));
  }

  // 改变pagesize
  function onShowSizeChange(current, pageSize){
    window.scrollTo(0, 0);
    setCurrent(1);
    setPageSize(pageSize);
  }

  // 切换页数
  function changePage(page, pageSize){
    window.scrollTo(0, 0);
    setCurrent(page);
  }

  // 删除同步分支
  function deleteRecord(){
    deleteRecordId && axios.delete(`/${owner}/${projectsId}/synchronizes/delete_job.json`, {data: {job_id: deleteRecordId}}).then(res=>{
      if(res && res.data.message === "success"){
        setReload(Math.random());
        message.success('删除成功');
        setVisible(false);
      }
    })
  }

  return <div className="storeListBox">
    <div className="font-16">
      <Link to={`/${owner}/${projectsId}/service/reposyncer`} className="blueSpan">仓库绑定</Link>
      <span> &gt; 同步分支</span>
    </div>
    <div className="headBox font-16 pl15 mt20 mb10">
      <img src={type === 'github' ? gitHub1 : gitee1} alt="" className="mr10 mb5"/>
      <span>{type === 'github' ? 'Github' : 'Gitee'}仓库地址</span>
      {storeDetail && <a className="ml15 blueSpan" href={type === 'github' ? storeDetail.github_address : storeDetail.gitee_address} target="_blank">{type === 'github' ? storeDetail.github_address : storeDetail.gitee_address}</a>}
      <Button style={{width: '94px', height:'36px', padding: 0}} className="blue_border_but createJobBut" onClick={()=>{setVisibleNew(true);}}>新建同步分支</Button>
    </div>
    <Table
      className="storeListTable"
      loading={loading}
      columns={columns}
      dataSource={data}
      expandedRowRender={expandRow}
      expandIconColumnIndex={5}
      expandIconAsCell={false}
      expandIcon={customExpandIcon}
      rowKey={'id'}
      expandedRowKeys={expandedRowKeys}
      onExpand={onExpand}
      pagination={{current: current, pageSize: pageSize, total: total, showSizeChanger: true, onShowSizeChange:onShowSizeChange, showQuickJumper: true, onChange: changePage}}
    />
    <Modal
      title="删除同步分支"
      visible={visible}
      onCancel={()=>{setVisible(false)}}
      footer={<div><Button style={{width: '90px', height:'36px'}} onClick={()=>{setVisible(false)}}>取消</Button><Button className="okBut" style={{width: '90px', height:'36px'}} onClick={deleteRecord}>确认删除</Button></div>}
      width={535}
      className="cancelBound"
    >
      <div className="bTilModal font-16"><span className="errorRedSpan font-18 mr20 mt20 ml15">!</span>确认删除此同步分支？</div>
      <div className="sTilModal">  删除同步分支后，系统将清除此条同步数据及日志，对应分支也将停止自动同步</div>
    </Modal>
    <CreateJobModal owner={owner} projectsId={projectsId} visible={visibleNew} setVisible={setVisibleNew} createJobBy={type === 'github' ? 'Github' : 'Gitee'} branchOptions={branchOptions} reload={setReload}/>
  </div>
}
export default RecordList;