import React, { useState, useMemo, useEffect } from "react";
import { Input, Select, Button, Form, Table, Upload, Modal, Popconfirm, message } from 'antd';
import cookie from 'react-cookies';
import { exportExcel } from '../components/exportExcel.js';
import Paginationtable from "../../components/paginationTable";
import { Info } from '../../components/ModalFun';
import { expertList, deleteExpert } from "../api";
import { professionalType, reviewArea } from "../static";
import { httpUrl } from '../fetch';

import './index.scss';
import '../index.scss';
const { Search } = Input;
const Option = Select.Option;

function RegisterList({ showNotification }) {
  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [curPage, setCurPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dataList, setDataList] = useState([]);
  const [total, setTotal] = useState(0);

  const [searchInput, setSearchInput] = useState('');
  const [searchReviewArea, setSearchReviewArea] = useState('');
  const [expertType, setExpertType] = useState('')
  const [dataAll, setDataAll] = useState([]);
  const [download, setDownload] = useState();
  const [downloading, setDownloading] = useState(false);
  const [visible, setVisible] = useState(false);

  function onShowSizeChange(current, pageSize) {
    setCurPage(current);
    setPageSize(pageSize);
  }

  const columns = useMemo(() => {
    return [{
      title: '姓名',
      dataIndex: 'expertName',
      width: 85,
      key: 'expertName',
      fixed: 'left',
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '最高学历',
      dataIndex: 'highestDegree',
      key: 'highestDegree',
      width: 80,
    },
    {
      title: '专家评估',
      dataIndex: 'expertScore',
      key: 'expertScore',
      width: 80,
      render: (text, record) => {
        return text || '--'
      }
    },
    {
      title: '工作单位',
      dataIndex: 'workplace',
      key: 'workplace',
      // width: 250,
    },
    {
      title: '单位类别',
      dataIndex: 'workplaceType',
      key: 'workplaceType',
      width: 80,
    },
    {
      title: '工作性质',
      dataIndex: 'workNature',
      key: 'workNature',
      width: 80,
    },
    {
      title: '专业职称',
      dataIndex: 'professionalTitle',
      key: 'professionalTitle',
      width: 120,
    },
    {
      title: '职称职级',
      dataIndex: 'titleRank',
      key: 'titleRank',
      width: 80,
    },
    {
      title: '专家类别',
      dataIndex: 'expertType',
      key: 'expertType',
      width: 80,
    },
    {
      title: '评审领域1',
      dataIndex: 'reviewAreaOne',
      key: 'reviewAreaOne',
      width: 100,
    },
    {
      title: '评审领域2',
      dataIndex: 'reviewAreaTwo',
      key: 'reviewAreaTwo',
      width: 100,
    },
    {
      title: '评审领域3',
      dataIndex: 'reviewAreaThree',
      key: 'reviewAreaThree',
      width: 100,
    },
    {
      title: '毕业院校',
      dataIndex: 'graduatedFrom',
      key: 'graduatedFrom',
    },
    {
      title: '院校专业',
      dataIndex: 'major',
      key: 'major',
    },
    {
      title: '身份证号',
      dataIndex: 'idNumber',
      key: 'idNumber',
      width: 170,
    },
    {
      title: '邮箱地址',
      dataIndex: 'expertEmail',
      key: 'expertEmail',
      width: 200,
    },
    {
      title: '开户银行',
      dataIndex: 'bankName',
      key: 'bankName',
      width: 110,
    },
    {
      title: '银行账号',
      dataIndex: 'bankAccount',
      key: 'bankAccount',
      render: (text, record) => {
        return '\t' + text
      }
    },
    {
      title: '个人简介',
      dataIndex: 'resumeAttachments',
      key: 'resumeAttachments',
      render: (text, record) => {
        return text && text.map(item => {
          return <a key={item.id} className="link" onClick={() => { downFile(item.id) }}>{item.fileName}</a>
        })
      }
    },
    {
      title: '职称证明',
      dataIndex: 'titleCertificateAttachments',
      key: 'titleCertificateAttachments',
      render: (text, record) => {
        return text && text.map(item => {
          return <a key={item.id} className="link" onClick={() => { downFile(item.id) }}>{item.fileName}</a>
        })
      }
    },
    {
      title: '学术成果',
      dataIndex: 'academicAchievementsAttachments',
      key: 'academicAchievementsAttachments',
      render: (text, record) => {
        return text && text.map(item => {
          return <a key={item.id} className="link" onClick={() => { downFile(item.id) }}>{item.fileName}</a>
        })
      }
    },
    {
      title: '荣誉称号',
      dataIndex: 'honorsAttachments',
      key: 'honorsAttachments',
      render: (text, record) => {
        return text && text.map(item => {
          return <a key={item.id} className="link" onClick={() => { downFile(item.id) }}>{item.fileName}</a>
        })
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'action',
      fixed: 'right',
      render: (text, record)=>{
        return <Popconfirm placement="bottom" title="你确认要删除此专家吗？" onConfirm={() => { delExpert(text);}} okText="是" cancelText="否"><Button size="small" type="primary">删除</Button></Popconfirm>
      }
    }
    ];
  }, []);

  function downFile(id) {
    let url = httpUrl + '/busiAttachments/download/' + id;
    window.open(url);
  }

  // 获取列表
  useEffect(() => {
    setLoading(true);
    let params = {
      searchInput,
      reviewArea: searchReviewArea,
      expertType,
      pageSize,
      curPage,
      statusString: '1',
    };
    expertList(params).then(data => {
      setDataList(data.rows || []);
      setLoading(false);
      setTotal(data && data.total);
    });
  }, [curPage, reload, searchInput, searchReviewArea, expertType, pageSize]);

  // 获取下载数据的列表
  useEffect(() => {
    if (!download) {
      return;
    }
    setDownloading(true);
    let params = {
      searchInput,
      reviewArea: searchReviewArea,
      expertType,
      pageSize: 10000000,
      curPage: 1,
      statusString: '1',
    };
    expertList(params).then(data => {
      setDataAll(data.rows || []);
      setDownloading(false);
      exportExcel("#exportList .ant-table-scroll", "专家列表");
    });
  }, [download]);

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

  function beforeUpload(file) {
    const isExcel = file.type.indexOf('xlsx') || file.type.indexOf('xls') || file.type.indexOf('sheet');
    if (!isExcel) {
      showNotification(`只支持.xlsx、xls格式!`);
    }
    return isExcel;
  }

  function handleChange(info) {
    if (info.file.status === 'uploading' || info.file.status === 'done') {
      if (info.file.response) {
        let resData = info.file.response.data;
        if (resData) {
          Info({
            title: '提示',
            content: <div className="import-important">
              {resData.successMessage && <div>
                <p>导入成功：</p>
                <p dangerouslySetInnerHTML={{ __html: `导入成功! 登录账号为手机号码，默认密码为12345678` }} className="mess"></p>
              </div>}
              {resData.failMessage && <div>
                <p>导入失败：</p>
                <p dangerouslySetInnerHTML={{ __html: resData.failMessage }} className="mess fail"></p>
              </div>}
            </div>,
          });
          setReload(Math.random());
          setVisible(false);
        } else {
          showNotification(info.file.response.message || '系统错误');
        }
      }
    }
    if (info.file.status === 'error') {
      showNotification(info.file.response.message || '系统错误');
    }
  }

  const upload = {
    name: 'file',
    action: `${httpUrl}/api/experts/registerByExcel`,
    onChange: handleChange,
    beforeUpload: beforeUpload,
    accept: ".xlsx,.xls",
    showUploadList: true,
    withCredentials: true,
    headers: {
      Authorization: cookie.load('autologin_trustie') || sessionStorage.osredmToken,
    },
  };
  
  return (
    <div className="expert-list centerbox">
      <div className="center-screen" >
        <div className="center-right-but">
          <Form.Item label={"姓名/手机"}>
            <Search
              maxLength={20}
              style={{ width: "300px" }}
              placeholder="请输入专家姓名或手机号"
              onSearch={(value) => { setSearchInput(value); setCurPage(1); }}
            />
          </Form.Item>

          <Form.Item label={"专家类别"}>
            <Select
              style={{ width: "150px" }}
              placeholder="所有类别"
              dropdownClassName="expert_register"
              onChange={(value) => { setExpertType(value) }}>
              <Option key={'all'} value="">所有类别</Option>
              {professionalType.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          </Form.Item>

          <Form.Item label={"评审领域"}>
            <Select
              style={{ width: "150px" }}
              placeholder="所有领域"
              dropdownClassName="expert_register"
              onChange={(value) => { setSearchReviewArea(value) }}>
              <Option key={'all'} value="">所有领域</Option>
              {reviewArea.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          </Form.Item>
        </div>
        <div className="btn-group">
          <Button type="primary" className="ml10 but41_fill" onClick={() => { setVisible(true) }}>导入</Button>
          <Button type="primary" loading={downloading} className="ml10 but41_fill" onClick={() => { setDownload(Math.random()) }}>导出</Button>
        </div>
      </div>
      <Paginationtable
        loading={loading}
        dataSource={dataList}
        columns={columns}
        total={total}
        setCurPage={setCurPage}
        current={curPage}
        scroll={{ x: 2700 }}
        onShowSizeChange={onShowSizeChange}
        showSizeChanger
      />

      <Table
        id="exportList"
        style={{ display: "none" }}
        columns={columns.slice(0,columns.length-2)}
        dataSource={dataAll}
        pagination={false}
        rowKey={(row) => row.id}
      />

      <Modal
        title="上传"
        visible={visible}
        // onOk={refuse}
        onCancel={() => { setVisible(false) }}
        className="upload-modal"
        footer={<Button onClick={() => { setVisible(false) }}>取消</Button>}
        key={Math.random()}
      >
        <Upload
          {...upload}
        >
          <button className="but41_fill">导入</button>
        </Upload>
        <p className="link" onClick={() => { window.open(`${httpUrl}/busiAttachments/download/${window.location.host.indexOf('osredm') === -1 ? '171' : '137'}`) }}>专家注册表模板.xlsx</p>
        <p className='hint'>提示：只能在导入模版上增减数据，才能导入成功！</p>
      </Modal>
    </div>)
}
export default RegisterList;