import React, { useState, useEffect, useMemo } from "react";
import { Tabs, Input, Select, Button, Modal, Form, message, Popconfirm } from 'antd';
import { professionalType, reviewArea } from '../static.js';
import { assignExperts, deleteExperts, expertList, selectExpertList } from "../api.js";
import Paginationtable from "../../components/paginationTable";
import './index.scss';
import '../index.scss';
import { Link } from "react-router-dom";
import { queryString } from "educoder";

const { TabPane } = Tabs;
const { Option } = Select;
const { Search } = Input;

function SelectExpert(props) {
  const { history, form, current_user, match, mygetHelmetapi } = props;
  const {main_web_site_url} = mygetHelmetapi;
  //id：竞赛或者创客任务id，containerType，1创客2竞赛
  const {containerId, containerType} = match.params;
  const {identifier, name} = queryString.parse(window.location.search.slice(1));
  const { getFieldDecorator, setFieldsValue } = form;
  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [curPage, setCurPage] = useState(1);
  const [dataList, setDataList] = useState([]);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [searchInput, setSearchInput] = useState('');
  const [expertType, setExpertType] = useState('');
  const [reviewAreaSel, setReviewAreaSel] = useState('');
  //专家多选确认框
  const [okConfirmExps, setOkConfirmExps] = useState(false);
  //批量删除专家确认框
  const [okConfirmDelete, setOkConfirmDelete] = useState(false);
  //批量添加 选择专家编号
  const [selectedRowKeys, setSelectedRowKeys] = useState(undefined);
  //随机抽取专家确认框
  const [okConfirmExtract, setOkConfirmExtract] = useState(false);
  //随机抽取 用户输入数
  const [randomCount, setRandomCount] = useState(undefined);
  //随机抽取错误提示语句
  const [randomErrorMessage, setRandomErrorMessage] = useState(undefined);
  //tab栏
  const [activeKey, setActiveKey] = useState(0);
  //已选专家列表
  const [selectedExperts, setSelectExperts] = useState([]);
  const [selectedExpertTotal, setSelectedExpertTotal] = useState(0);
  //全部已选专家
  const [allSelectedExpertsId, setAllSelectedExpertsId] = useState();

  const columns = useMemo(() => {
    return [
      {
        title: '编号',
        dataIndex: 'index',
        width: 80,
        align: 'center',
      },
      {
        title: '专家姓名',
        dataIndex: 'expertName',
        key: 'expertName',
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        width: 150,
        key: 'phone',
      },
      {
        title: '最高学历',
        dataIndex: 'highestDegree',
        key: 'highestDegree',
      },
      {
        title: '专业职称',
        dataIndex: 'professionalTitle',
        width: 120,
      },
      {
        title: '专家类别',
        dataIndex: 'expertType',
      },
      {
        title: '评审领域',
        dataIndex: 'reviewAreas',
        align: 'center',
      },
      {
        title: '专家评估',
        dataIndex: 'expertScore',
        align: 'center',
        render:(text,record)=>{
          return record.expertScore || '--';
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 180,
        align: 'center',
        render: (text, record) => {
          return <React.Fragment>
            {activeKey == "1" && <a className="select" onClick={()=>{SelectExperts([record.id])}}>添加</a>}
            {activeKey == "0" && <Popconfirm placement="bottom" title="你确认要删除此专家吗？" onConfirm={() => { deleteExpert(record.taskExpertId, record.id)}} okText="是" cancelText="否"><Button className="mr5 font-12" type="danger" size="small">删除</Button></Popconfirm>}
          </React.Fragment>
        }
      }
    ];
  }, [activeKey, allSelectedExpertsId]);

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
    }
  };

  const ExpertDetail = (record)=>{
    return <div className="expert_detail_div df">
      <div>
        <p>工作单位：{record.workplace}</p>
        <p>单位类别：{record.workplaceType}</p>
        <p>工作性质：{record.workNature}</p>
        <p>职称职级：{record.titleRank}</p>
      </div>
      <div>
        <p>邮箱地址：{record.expertEmail || '--'}</p>
        <p>毕业院校：{record.graduatedFrom || '--'}</p>
        <p>院校专业：{record.major || '--'}</p>
      </div>
      <div>
        <p>身份证号：{record.idNumber || '--'}</p>
        <p>开户银行：{record.bankName || '--'}</p>
        <p>银行账号：{record.bankAccount || '--'}</p>
      </div>
    </div>
  }

  const TaskMess = ()=>{
    return <div>
      <div className="box"></div>
      <p className="font-16 pt15 font-w color-grey3">任务信息</p>
      <p className="mt10"><span className="font-w color-grey3">{containerType ==1 ? '任务':'竞赛'}名称</span><span className="ml10 color-grey3">{decodeURI(name)}</span></p>
      <p className="mt10 pb20">
        <span className="font-w color-grey3">{containerType ==1 ? '任务':'竞赛'}链接</span>
        {containerType == 1 && <Link className="taskLink ml10" target="_blank" to={`/task/taskDetail/${containerId}`} >{`${window.location.origin}/task/taskDetail/${containerId}`}</Link>}
        {containerType == 2 && <a href={`${main_web_site_url}/competitions/${identifier}/home`} target="_blank" className="taskLink ml10">{`${main_web_site_url}/competitions/${identifier}/home`}</a>}
      </p>
  </div>
  }

  //全部已选专家
  useEffect(()=>{
    setLoading(true);
    const params = {
      containerId,
      containerType,
      curPage:curPage,
      pageSize: 10000,
      curPage: 1,
    }
    selectExpertList(params).then(response=>{
      if (response && response.data && Array.isArray(response.data.rows)) {
        const ids = new Set();
        response.data.rows.map((item)=>{
          ids.add(item.id);
        })
        setAllSelectedExpertsId(ids);
      }
    }).finally(()=>{
      setLoading(false);
    })
  },[])

  // 专家列表
  useEffect(() => {
    setLoading(true);
    let params = {
      searchInput,
      expertType: expertType === 'all' ? '' : expertType,
      reviewArea: reviewAreaSel === 'all' ? '' : reviewAreaSel,
      pageSize,
      curPage,
      statusString: '1',
      selectedExpertIds: allSelectedExpertsId && Array.from(allSelectedExpertsId).toString()
    };
    expertList(params).then(data => {
      if (data && Array.isArray(data.rows)) {
        if(data.rows.length === 0 && curPage > 1 && activeKey == 1){
          // 当前页数据为空跳转到前一页
          setCurPage(curPage-1);
        }else{
          let index = 1;
          for (const item of data.rows) {
            item.reviewAreas = `${item.reviewAreaOne} ${item.reviewAreaTwo ? `、${item.reviewAreaTwo}`:''} ${item.reviewAreaThree ? `、${item.reviewAreaThree}`:''}`;
            item.index = (index++) + (curPage > 1 ? (curPage - 1) * 10 : 0);
          }
        }
        
      }
      setDataList(data && data.rows);
      setLoading(false);
      setTotal(data && data.total);
    });
  }, [curPage, reload, searchInput, expertType, reviewAreaSel, allSelectedExpertsId]);

  //已选专家列表
  useEffect(()=>{
    setLoading(true);
    const params = {
      containerId,
      containerType,
      curPage,
      pageSize,
    }
    selectExpertList(params).then(response=>{
      if (response && response.data && Array.isArray(response.data.rows)) {
        if(response.data.rows.length === 0 && curPage > 1 && activeKey == 0){
          // 当前页数据为空跳转到前一页
          setCurPage(curPage-1);
        }else{
          let index = 1;
          for (const item of response.data.rows) {
            item.reviewAreas = `${item.reviewAreaOne} ${item.reviewAreaTwo ? `、${item.reviewAreaTwo}`:''} ${item.reviewAreaThree ? `、${item.reviewAreaThree}`:''}`;
            item.index = (index++) + (curPage > 1 ? (curPage - 1) * 10 : 0);
          }
          setSelectExperts(response && response.data.rows);
          setSelectedExpertTotal(response && response.data.total);
        }
      }
    }).finally(()=>{
      setLoading(false);
    })
  },[curPage, reload])

  //随机抽取专家
  function random(){
    setRandomErrorMessage('');
    if(!randomCount){
      setRandomErrorMessage('请输入随机抽取的专家数量!');
    }else if(isNaN(randomCount)){
      setRandomErrorMessage('请输入数字!');
    }else if(randomCount.indexOf('.')!==-1 || randomCount.indexOf('-')!==-1){
      setRandomErrorMessage('请输入正整数!');
    }else{
      let params = {
        searchInput,
        expertType: expertType === 'all' ? '' : expertType,
        reviewArea: reviewAreaSel === 'all' ? '' : reviewAreaSel,
        randomCount,
        curPage:1,
        pageSize: 10000,
        selectedExpertIds: Array.from(allSelectedExpertsId).toString(),
      };
      expertList(params).then(response=>{
        if(response && Array.isArray(response.rows)){
          const randomIds = [];
          response.rows.map(item=>{
            randomIds[randomIds.length] = item.id;
          })
          SelectExperts([...randomIds]);
          setOkConfirmExtract(false);
        }
      })
    }
  }

  //为创客任务添加评审专家
  const SelectExperts = (id) =>{
    const params = {
      assignorId: parseInt(current_user.user_id),
      containerId,
      containerName: decodeURI(name),
      containerType,
      expertIds: id.toString(),
      status: 3
    }
    assignExperts(params).then(response=>{
      if(response && response.message === '专家指派成功'){
        id.map(i=>setAllSelectedExpertsId(allSelectedExpertsId.add(i)));
        setOkConfirmExps(false);
        message.success(response.message);
        setSelectedRowKeys([]);
        setReload(Math.random());
      }
    })
  }

  //删除评审专家
  const deleteExpert=(taskExpertId, expertId)=>{
    setLoading(true);
    deleteExperts(taskExpertId,1).then(response=>{
      if(response && response.message === "删除成功"){
        message.success("删除成功");
        allSelectedExpertsId.delete(expertId);
        setReload(Math.random());
      }else{
        message.error("删除失败");
      }
    }).finally(()=>{
      setLoading(false);
    })
  }

  return (
    <div className="centerbox select_expert">
      <div className="df">
        <p className="title_one font-16 font-w font-color-18">评审专家选取</p>
        <button className="but41_border goback_but mr25" onClick={()=>{history.goBack()}}>返回上一页</button>
      </div>
      <Tabs defaultActiveKey="0" type="card" onChange={(activeKey)=>{setActiveKey(activeKey);setSelectedRowKeys([]);setCurPage(1);}}>
        <TabPane tab="已选专家" key="0">
          <TaskMess/>
          <div className="df mb20">
            <p className="font-16 font-w color-grey3 select_title">已选取评审专家</p>
            <div>
              {/* <button className="but41_fill" onClick={() => {selectedRowKeys && selectedRowKeys.length>0 && setOkConfirmDelete(true)}}>批量删除</button> */}
              <Modal
                title="批量删除"
                visible={okConfirmDelete}
                onOk={() => { history.go(-1) }}
                onCancel={() => setOkConfirmDelete(false)}
                wrapClassName="expert_modal"
              >
                <p className='weight_bold warning'>您确定要删除选中的{selectedRowKeys && selectedRowKeys.length}个专家吗？</p>
                <p className='ml_40'>此操作将删除选中的{selectedRowKeys && selectedRowKeys.length}个专家，请进行确认以防数据丢失。</p>
              </Modal>
            </div>
          </div>
          <Paginationtable
            loading={loading}
            dataSource={selectedExperts}
            columns={columns}
            total={selectedExpertTotal}
            setCurPage={setCurPage}
            current={curPage}
            // rowSelection={rowSelection}
            expandedRowRender={ExpertDetail}
            expandIconColumnIndex={8}
            expandIconAsCell={false}
          />
        </TabPane>
        <TabPane tab="专家选取" key="1">
          <TaskMess/>
          <div className="df mb20">
            <p className="font-16 font-w color-grey3 select_title">添加评审专家</p>
            <div>
              <button className="but41_fill" onClick={() => {selectedRowKeys && selectedRowKeys.length>0 && setOkConfirmExps(true)}}>批量添加</button>
              {allSelectedExpertsId && allSelectedExpertsId.size === total ? <button className="invalid_extraction butE3_border ml20">随机抽取</button> : <button className="but41_fill ml20" onClick={() => setOkConfirmExtract(true)}>随机抽取</button>}
              <Modal
                title="批量添加"
                visible={okConfirmExps}
                onOk={() => SelectExperts(selectedRowKeys)}
                onCancel={() => setOkConfirmExps(false)}
                wrapClassName="expert_modal"
              >
                <p className='weight_bold warning'>您确定要添加选中的{selectedRowKeys && selectedRowKeys.length}个专家吗？</p>
                <p className='ml30'>此操作将添加选中的{selectedRowKeys && selectedRowKeys.length}个专家，请进行确认。</p>
              </Modal>

              <Modal
                title="随机抽取"
                visible={okConfirmExtract}
                onOk={random}
                onCancel={() => setOkConfirmExtract(false)}
                wrapClassName="expert_modal extract"
              >
                <div><span>请输入数量：</span><Input placeholder="请输入" onChange={(e)=>{setRandomCount(e.target.value)}}></Input></div>
                <p>{randomErrorMessage}</p>
              </Modal>
            </div>
          </div>
          <div className="df search">
            <Form className="df">
              <Form.Item label="查询条件：">
                {getFieldDecorator('searchInput', {})(<Search
                  maxLength={20}
                  style={{ width: "200px" }}
                  placeholder="请输入专家姓名或手机号"
                  onSearch={(value) => { setSearchInput(value); setCurPage(1); }}
                />)}
              </Form.Item>
              <Form.Item label="专家类别：">
                {getFieldDecorator('expertType', {})(
                  <Select placeholder="所有类别" style={{ width: 220 }} onChange={(value) => { setExpertType(value);setCurPage(1); }}>
                    <Option value='all'>所有类别</Option>
                    {professionalType.map(item => {
                      return <Option key={item.value} value={item.value}>{item.label}</Option>
                    })}
                  </Select>)}
              </Form.Item>
              <Form.Item label="评审领域：">
                {getFieldDecorator('reviewAreaSel', {})(
                  <Select placeholder="所有领域" style={{ width: 220 }} onChange={value => {setReviewAreaSel(value);setCurPage(1);}}>
                    <Option value='all'>所有领域</Option>
                    {reviewArea.map(item => {
                      return <Option key={item.value} value={item.value}>{item.label}</Option>
                    })}
                  </Select>)}
              </Form.Item>
            </Form>
            <button className="butE3_border ml120 mb25" onClick={() => {
              setSearchInput('');
              setExpertType('');
              setReviewAreaSel('');
              setFieldsValue({
                searchInput: '',
                expertType: 'all',
                reviewAreaSel: 'all'
              });
            }}>清除</button>
          </div>
          <Paginationtable
            loading={loading}
            dataSource={dataList}
            columns={columns}
            total={total}
            setCurPage={(curPage)=>{setCurPage(curPage++);setSelectedRowKeys([])}}
            current={curPage}
            rowSelection={rowSelection}
            expandedRowRender={ExpertDetail}
            expandIconColumnIndex={9}
            expandIconAsCell={false}
          />
        </TabPane>
      </Tabs>
    </div>)
}
export default Form.create()(SelectExpert);