import React, { useCallback, useEffect, useState, useMemo } from 'react';
import classNames from 'classnames';
import { Input, Select, Button, Form, DatePicker, Table, Pagination, Modal, message } from 'antd';
import { Link } from 'react-router-dom';

import { paperCheckStatusArr, publishModeArr, taskStatusAllArr, showUserModeArr, main_web_site_url, expertReviewArr } from '../static';
import { getTaskAdminList, changeShowUserMode, deleteTask, recommendTask, addExpertReview, publishExpertsAndRules } from '../api';
import '../index.scss';
import './index.scss';
import { getRules, selectExpertList } from 'src/military/expert/api';
import PaginationTable from '../../../../src/military/components/paginationTable';
const format = "YYYY-MM-DD HH:mm:ss";
const Option = Select.Option;

const statusArr = [];
for (const item of taskStatusAllArr) {
  statusArr[item.dicItemCode] = item.dicItemName;
}
const checkStatusArr = [];
for (const item of paperCheckStatusArr) {
  checkStatusArr[item.dicItemCode] = item.dicItemName;
}


export default Form.create()(({ form, showNotification, match, history, state }) => {
  const { getFieldDecorator, setFieldsValue, getFieldsValue } = form;
  const { hash} = history && history.location;
  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [statusString, setStatusString] = useState('');
  const [publishMode, setPublishMode] = useState('');
  const [showUserMode, setShowUserMode] = useState('');
  const [isDelete, setIsDelete] = useState('0');
  const [recommend, setRecommend] = useState('');

  const [sort, setSort] = useState('Desc');
  const [order, setOrder] = useState('createdAt');
  const [searchObj, setSearchObj] = useState({});
  const [curPage, setCurPage] = useState(hashDate(hash) || 1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);
  const [expertReview, setExpertReview] = useState('');

  //查看评审规则、查看选取专家、发布评审任务
  const [lookRules, setLookRules] = useState(false);
  const [lookExperts, setLookExperts] = useState(false);
  const [pulicReview, setPublicReview] = useState(false);
  const [rules, setRules] = useState(undefined);
  const [selectedExperts, setSelectedExperts] = useState(undefined);
  const [publicTaskId, setPublicTaskId] = useState(undefined);

  useEffect(()=>{
    setCurPage(hashDate(hash) || 1);
  },[hash])

  useEffect(() => {
    const params = {
      ...searchObj,
      statusString,
      publishMode: publishMode.length > 1 ? '' : publishMode,
      showUserMode: showUserMode.length > 1 ? '' : showUserMode,
      curPage,
      pageSize: 10,
      orderBy: order + sort,
      isDelete,
      recommend,
      expertReview: expertReview==='-1'?"":expertReview,
    };
    setLoading(true);
    getTaskAdminList(params).then(data => {
      if (data) {
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })
  }, [statusString, order, sort, publishMode, showUserMode, curPage, searchObj, isDelete, reload, recommend, expertReview]);


  const helper = useCallback(
    (label, name, rules, widget, initialValue) => (
      <Form.Item label={label}>
        {getFieldDecorator(name, { rules, initialValue, validateFirst: true, })(widget)}
      </Form.Item>
    ), []);

  function hashDate(hash) {
    return parseInt(hash.split("&")[0].substring(hash.split("&")[0].indexOf("=")+1));
  }
  function onSearch() {
    let values = getFieldsValue(['nameInput', 'endTime', 'startTime', 'enterpriseNameInput']);
    if (values.startTime) values.startTime = values.startTime.format(format);
    if (values.endTime) values.endTime = values.endTime.format(format);
    if (values.checkStatus === '0,1,2') values.checkStatus = '';
    setSearchObj(values);
    setCurPage1(1);
    // window.location.href=`/task/taskAdmin`;
  }

  function clearSearch() {
    setFieldsValue({
      startTime: '',
      endTime: '',
      nameInput: '',
      enterpriseNameInput: ''
    });
    setSearchObj({});
  }

  const columns = useMemo(() => {
    return [
      {
        title: '任务名称',
        dataIndex: 'name',
        width: "13%",
        render: (text, record) => (
          <Link className="line_1 primary-link" target="_blank" to={`/task/taskDetail/${record.id}`} >{text}</Link>
        ),
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={'-1'}
          onChange={(value)=>{setExpertReview(value);setCurPage1(1);}}
        >
          <Option key={'-1'} >专家评审</Option>
          <Option key={'1'} >已提交评审</Option>
          <Option key={'0'} >未提交评审</Option>
        </Select>,
        dataIndex: 'expertReview',
        render: (text, record) => {
          return <Select
            className="column-select"
            showArrow
            defaultValue={text?1:-1}
            onChange={(key) => { changeExpertReviewStatus(key, record.id) }}
            disabled={record.assignRuleAndExperts || !(record.status == 1 || record.status == 3)}
          >
            {
              expertReviewArr.map(item => {
                return <Option key={item.dicItemCode} value={item.dicItemCode}>{item.dicItemName}</Option>
              })
            }
          </Select>
        }
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={'0,1'}
          onChange={(value)=>{setPublishMode(value);setCurPage1(1);}}
        >
          <Option key={'0,1'} >发布方式</Option>
          <Option key={'0'} >自主提交</Option>
          <Option key={'1'} >统筹任务</Option>
        </Select>,
        dataIndex: 'publishMode',
        render: (text, record) => {
          return publishModeArr[text]
        }
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={'0,1,2,3,4,5,6,7,8,9'}
          onChange={(value)=>{setStatusString(value);setCurPage1(1);}}
        >
          <Option key={'0,1,2,3,4,5,6,7,8,9'} >任务状态</Option>
          {
            taskStatusAllArr.map(item => {
              return <Option key={item.dicItemCode} >{item.dicItemName}</Option>
            })
          }
        </Select>,
        width: '6%',
        dataIndex: 'status',
        render: (text, record) => {
          return record.exceptClosedBoolean ? '已关闭' : statusArr[text]
        }
      },
      {
        title: '发布主体',
        dataIndex: 'enterpriseName',
        width: '9%',
      },
      {
        title: '发布时间',
        dataIndex: 'publishedAt',
        width: '7%',
        render: (text, record) => {
          return text || '--'
        }
      },
      {
        // title: '应征者名单公示',
        title: <Select
          className="column-select"
          showArrow
          placeholder="请选择审核状态"
          defaultValue={'0,1,2'}
          onChange={setShowUserMode}
        >
          <Option key={'0,1,2'}>应征者公示</Option>
          {
            showUserModeArr.map(item => {
              return <Option key={item.dicItemCode}>{item.dicItemName}</Option>
            })
          }
        </Select>,
        dataIndex: 'showUserMode',
        width:'8%',
        render: (text, record) => {
          return <Select
            className="column-select"
            showArrow
            placeholder="请选择审核状态"
            defaultValue={text}
            onChange={(key) => { changeStatus(key, record.id) }}
          >
            {
              showUserModeArr.map(item => {
                return <Option key={item.dicItemCode} value={item.dicItemCode}>{item.dicItemName}</Option>
              })
            }
          </Select>
        }
      },
      {
        title: '评审规则',
        dataIndex: 'ruleEditedCount',
        render: (text, record) => {
          return record.assignRuleAndExperts ? <Button size='small' type="primary" onClick={()=>{viewRules(record)}}>查看</Button> : record.expertReview && (record.status === 1 || record.status === 3) ? <Link className="line_1 primary-link" to={`/managements/expert/task/review/rules/${1}/${record.id}/?status=${record.status}&name=${record.name}&createdAt=${record.createdAt}&collectingEndTime=${record.collectingEndTime}&choosingDays=${record.choosingDays}`}>编辑</Link> : <span className='gary_span'>编辑</span>
        }
      },
      {
        title: '专家选取',
        dataIndex: 'expertSelectedCount',
        render: (text, record) => {
          return record.assignRuleAndExperts ? <Button size='small' type="primary" onClick={()=>{viewExperts(record)}}>查看</Button> : record.expertReview && (record.status === 1 || record.status === 3) ? <Link className="line_1 primary-link" to={`/managements/expert/task/review/select/${1}/${record.id}/?name=${record.name}`}>选择</Link> : <span className='gary_span'>选择</span>
        }
      },
      {
        title: '评审任务',
        dataIndex: 'expertReview1',
        render: (text, record) => {
          return record.assignRuleAndExperts ? <span className='gary_span'>已发布</span> : record.expertReview && (record.status === 1 || record.status === 3) ? <Button size='small' type="primary" onClick={()=>{publishTaskReview(record)}}>发布</Button> : <span className='gary_span'>发布</span>
        }
      },
      {
        title: '评审结果',
        dataIndex: 'expertReview2',
        render: (text, record) => {
          return record.assignRuleAndExperts ? <Link className="line_1 primary-link" to={`/managements/expert/task/review/results/${1}/${record.id}/#status=${record.status}&name=${record.name}&taskModeId=${record.taskModeId}`}>查看</Link>:<span className='gary_span'>查看</span>
        }
      },
      {
        title: '操作',
        key: 'action',
        width: '6%',
        render: (text, record) => (
          <React.Fragment>

            {
              isDelete == '0' ? <Button className="mr5 font-12" type="danger" size="small" onClick={() => { deleteItem(record.id, '1') }}>隐藏</Button>
                : <Button className="mr5 font-12" type="primary" size="small" onClick={() => { deleteItem(record.id, '0') }}>恢复</Button>
            }

            {
              !record.recommend && [3, 4, 5, 6, 7, 8].includes(record.status) && <Button className="mr5 font-12" type="primary" size="small" onClick={() => { recommendItem(record.id, '1') }}>首页推荐</Button>
            }

            {
              record.recommend && <Button className="mr5 font-12" type="danger" size="small" onClick={() => { recommendItem(record.id, '0') }}>撤销推荐</Button>
            }

            {/* <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>查看</Link> */}
          </React.Fragment>
        ),
      },
    ]
  }, [isDelete, curPage]);

  //已选取专家
  const columnsExperts = useMemo(() => {
    return [
      {
        title: '编号',
        dataIndex: 'index',
        width: 80,
        align: 'center',
      },
      {
        title: '专家姓名',
        dataIndex: 'expertName',
        key: 'expertName',
        width: 120,
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        width: 130,
        key: 'phone',
      },
      {
        title: '最高学历',
        dataIndex: 'highestDegree',
        key: 'highestDegree',
      },
      {
        title: '专业职称',
        dataIndex: 'professionalTitle',
      },
      {
        title: '专家类别',
        dataIndex: 'expertType',
      },
      {
        title: '评审领域',
        dataIndex: 'reviewAreas',
        align: 'center',
        width: 260,
      },
      {
        title: '专家评估',
        dataIndex: 'expertScore',
        align: 'center',
        render:(text,record)=>{
          return record.expertScore || '--';
        }
      }
    ];
  }, []);

  function recommendItem(id, recommend) {
    Modal.confirm({
      title: "警告",
      content: recommend == '0' ? "确认撤销该推荐吗 ？撤销后首页中将不再展示该任务" : "确认推荐吗？推荐后，用户可以在首页看到推荐任务中点击量前三的任务！",
      okText: '确定',
      cancelText: '取消',
      onOk() {
        recommendTask(id, recommend).then(res => {
          if (res.message === 'success') {
            showNotification('操作成功!');
            setReload(Math.random());
          }
        });
      },
    });
  }

  function deleteItem(id, isDelete) {
    Modal.confirm({
      title: "警告",
      content: isDelete == '0' ? "确认恢复该任务吗？恢复后用户可以重新看到该任务！" : "确认隐藏？隐藏后用户无法看到该任务！",
      okText: '确定',
      cancelText: '取消',
      onOk() {
        deleteTask(id, isDelete).then(res => {
          if (res.message === 'success') {
            showNotification('操作成功!');
            setReload(Math.random());
          }
        });
      },
    });
  }

  //监听lookRules,lookExperts,pulicReview的变化，弹框
  useEffect(()=>{

    //评审规则
    lookRules && rules && Modal.info({
      className: 'publishReview',
      title: "评审规则",
      content:
        <React.Fragment>
          <div>{rules && rules.rule}</div>
          <p>评分标准</p>
          <div>
            {rules.criterias.map(item=>{return <p key={Math.random()}>{item}</p>})}
          </div>
          <p>评审时间</p>
          <div>{rules.reviewData}</div>
        </React.Fragment>
      ,
    });
    lookRules && setLookRules(false);

    //已选取评审专家
    lookExperts && selectedExperts && Modal.info({
      className: 'publishReview',
      title: "已选取评审专家",
      content:
        <PaginationTable
        dataSource={selectedExperts}
        columns={columnsExperts}
        scroll={{ y: 395 }}/>,
    });
    lookExperts && setLookExperts(false);

    //发布评审任务
    pulicReview && rules && selectedExperts && Modal.confirm({
      className: 'publishReview',
      title: "发布评审任务",
      centered: true,
      content:
        <React.Fragment>
          <div className='tip'>
            <i className='iconfont icon-erciqueren_icon'></i>
            <span className='publicTitle'>确定发布此评审任务？确定发布后评审规则与评审专家信息将无法重新编辑</span>
          </div>
          <p>评审规则</p>
          <div>{rules && rules.rule}</div>
          <p>评分标准</p>
          <div>
            {rules.criterias.map(item=>{return <p key={Math.random()}>{item}</p>})}
          </div>
          <p>评审时间</p>
          <div>{rules.reviewData}</div>
          <p>已选取评审专家</p>
          <PaginationTable
            dataSource={selectedExperts}
            columns={columnsExperts}
            scroll={{ y: 230 }}/>
        </React.Fragment>
      ,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        publishExpertsAndRules(publicTaskId,1).then(response=>{
          if(response && response.message==="发布成功"){
            setReload(Math.random());
          }
        })
      },
    });
    pulicReview && setPublicReview(false);
  },[lookRules,lookExperts,pulicReview])

  //发布评审任务
  function publishTaskReview(record){
    if(!record.ruleEditedCount || !record.expertSelectedCount){
      message.error("请先编辑评审规则以及选取评选专家再发布此任务");
    }else{
      getRules({containerId: record.id, containerType: 1, statusString: 3}).then(response=>{
        if(response && response.message === "success"){
          setRules(response.data);
        }
      })
      selectExpertList({containerId: record.id, containerType: 1, curPage:curPage, pageSize: 10000, curPage: 1,}).then(response=>{
        if(response && response.message === "success" && Array.isArray(response.data.rows)){
          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);
          }
          setPublicTaskId(record.id);
          setSelectedExperts(response.data.rows);
          setPublicReview(true);
        }
      });
    }
  }

  //已发布任务  查看评审规则
  function viewRules(record){
    getRules({containerId: record.id, containerType: 1, statusString: '-1,1,2'}).then(response=>{
      if(response && response.message === "success"){
        setRules(response.data);
        setLookRules(true);
      }
    });
  }

  //已发布任务  查看已选专家
  function viewExperts(record){
    selectExpertList({containerId: record.id, containerType: 1, curPage:curPage, pageSize: 10000, curPage: 1,}).then(response=>{
      if(response && response.message === "success" && Array.isArray(response.data.rows)){
        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);
        }
        setSelectedExperts(response.data.rows);
        setLookExperts(true);
      }
    });
  }

  function changeStatus(showUserMode, taskId) {
    changeShowUserMode({
      taskId,
      showUserMode
    }).then(res => {
      if (res && res.message === 'success') {
        showNotification('修改成功!');
      }
    })
  }

  function changeExpertReviewStatus(expertReviewStatus, taskId) {
    addExpertReview(taskId,expertReviewStatus).then(res => {
      if (res && res.message === 'success') {
        showNotification('操作成功!');
        setReload(Math.random());
      } else {
        showNotification('操作失败');
      }
    })
  }

  function setCurPage1(page){
    setCurPage(page);
    window.location.href=`/managements/task/taskAdmin#page=${page}`;
  }

  // 改变排序字段
  const changeSortName = useCallback((sortType) => {
    setOrder(sortType);
    setCurPage1(1);
  }, []);

  // 改变排序
  const changeSort = useCallback((sort) => {
    setSort(sort);
    setCurPage1(1);
  }, []);

  const changeShow = useCallback((isDelete) => {
    setIsDelete(isDelete);
    setCurPage1(1);
  });

  const changeRecommend = useCallback((recommend) => {
    if (recommend === 'all') {
      setRecommend('');
    } else {
      setRecommend(recommend);
    }
    setCurPage1(1);
  });

  const ExpertDetail = (record)=>{
    return <div className="expert_detail_div">
      <div> 任务编号：{record.number} </div>
      <div> 截稿时间：{record.collectingEndTime || '--'} </div>
      <div> 稿件数：{record.papersCount || '--'} </div>
    </div>
  }

  function downloadFile() {
    window.open(main_web_site_url + '/admin/tasks.xlsx');
  }

  return (
    <div className="centerbox task-manage-all ">
      
      <div className="search-screen" >
        {helper(
          "任务名称",
          "nameInput",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="输入任务名称进行检索"
          />
        )}

        {helper(
          "发布主体名称",
          "enterpriseNameInput",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="输入发布主体名称进行检索"
          />
        )}

        <div className="center-right-but">

          {helper(
            "发布时间:",
            "startTime",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择开始时间"
            />
          )}

          {helper(
            "",
            "endTime",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择结束时间"
            />
          )}
        </div>
        <div className="button-div">
          {/* <a href="/admin/tasks.xlsx" class="fr edu-default-btn edu-blueback-btn plr30">导出</a> */}
          <Button className="mr10" type="primary" onClick={onSearch}>搜索</Button>
          <Button className="mr10" onClick={clearSearch}>清除</Button>
          <Button className="mr10" type="primary" onClick={downloadFile}>导出</Button>
        </div>
      </div>

      <div className="select-box">
        <Form.Item className="inline-form" label="显示状态">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeShow}
            defaultValue='0'
          >
            <Option key={'0'} >正常显示（默认）</Option>
            <Option key={'1'} >已隐藏</Option>
          </Select>
        </Form.Item>

        <Form.Item className="inline-form" label="是否推荐">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeRecommend}
            defaultValue='all'
          >
            <Option key={'all'} >全部</Option>
            <Option key={'0'} >未推荐</Option>
            <Option key={'1'} >已推荐</Option>
          </Select>
        </Form.Item>

        <Form.Item className="inline-form" label="排序">
          <Select
            style={{ width: '200px' }}
            showArrow
            onChange={changeSortName}
            defaultValue='createdAt'
          >
            <Option key={'createdAt'} >创建时间</Option>
            <Option key={'publishedAt'} >发布时间</Option>
          </Select>

          <span className={classNames({ "sort-active": sort === 'Desc', 'sort-icon': true, 'ml10': true })} onClick={() => { changeSort('Desc') }}>
            <i className="fa fa-long-arrow-down font-16  "></i>
          </span>
          <span className={classNames({ "sort-active": sort === 'Asc', 'sort-icon': true })} onClick={() => { changeSort('Asc') }}>
            <i className="fa fa-long-arrow-up font-16 "></i>
          </span>

        </Form.Item>
      </div>

      <div className="center-content">

        <Table
          loading={loading}
          rowKey={(row) => row.id}
          dataSource={taskList}
          columns={columns}
          pagination={false}
          className="mt10"
          expandedRowRender={ExpertDetail}
        />
        {total > 10 &&
          <Pagination
            onChange={(page) => { setCurPage1(page) }}
            current={curPage}
            total={total}
          />}

      </div>


    </div>
  )
}
)