import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, Modal } from 'antd';
import moment from 'moment';
import { formatDuring, getUrlToken } from 'educoder';
import ChooseNav from '../../components/chooseNav';
import SortBox from '../../components/sortBox';
import ItemListTask from '../components/itemListTask';
import { taskTimeArr, taskStatusArr, sortArr, taskModeIdArr } from '../static';
import { getTaskList, getTaskCategory, getCompanyInfo } from '../api';
import '../index.scss';
const Search = Input.Search;


export default ({ history, current_user, showLoginDialog, location, mygetHelmetapi }) => {
  // console.log(current_user);

  let initType = getUrlToken('type', location.search) || '';

  const [loading, setLoading] = useState(false);
  const [taskCategoryArr, setTaskCategoryArr] = useState([]);
  const [categoryId, setCategoryId] = useState(initType);
  const [taskModeId, setTaskModeId] = useState('');
  const [expiredStartTime, setExpiredStartTime] = useState('');
  const [expiredEndTime, setExpiredEndTime] = useState('');
  const [statusString, setStatusString] = useState('3,4,5,6,7,8');
  const [searchInput, setSearchInput] = useState('');
  const [orderBy, setOrderBy] = useState('');
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);

  // 获取分类数据
  useEffect(() => {
    getTaskCategory().then(data => {
      if (data) {
        for (const item of data) {
          item.dicItemCode = item.id;
          item.dicItemName = item.name;
        }
        setTaskCategoryArr(data);
      }
    });
  }, []);

  // 获取任务列表
  useEffect(() => {
    const params = {
      categoryId,
      taskModeId,
      expiredStartTime,
      expiredEndTime,
      statusString,
      searchInput,
      orderBy,
      curPage,
      pageSize: 10,
    };
    setLoading(true);
    getTaskList(params).then(data => {
      if (data) {
        for (const item of data.rows) {
          item.delayTime = surplusTime(item);
        }
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })
  }, [categoryId, taskModeId, expiredStartTime, expiredEndTime, statusString, searchInput, orderBy, curPage]);

  // 改变选项
  const changeOptionId = useCallback((option, type) => {
    if (type === 'taskCategory') {
      setCategoryId(option.dicItemCode);
    } else if (type === 'taskModeId') {
      setTaskModeId(option.dicItemCode);
    } else if (type === 'taskTime') {
      if (option.dicItemCode) {
        let nowTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        let nextTime = moment(new Date().setDate(new Date().getDate() + option.dicItemCode)).format('YYYY-MM-DD HH:mm:ss');
        setExpiredStartTime(nowTime);
        setExpiredEndTime(nextTime);
      } else {
        setExpiredStartTime('');
        setExpiredEndTime('');
      }
    } else if (type === 'taskStatus') {
      setStatusString(option.dicItemCode || '3,4,5,6,7,8');
    }
  }, []);

  function surplusTime(item) {
    let surplus;
    switch (item.status) {
      case 3:
        surplus = item.collectingDays * 24 * 3600 - (new Date() - new Date(item.publishedAt || item.createdAt)) / 1000;
        break;
      case 4:
        surplus = item.choosingDays * 24 * 3600 - (new Date() - new Date(item.collectingCompleteAt)) / 1000;
        break;
      case 5:
        surplus = item.makePublicDays * 24 * 3600 - (new Date() - new Date(item.makePublicAt)) / 1000;
        break;
      case 6:
        surplus = item.signingDays * 24 * 3600 - (new Date() - new Date(item.publicityCompleteAt)) / 1000;
        break;
      case 7:
        surplus = item.payingDays * 24 * 3600 - (new Date() - new Date(item.signingCompleteAt)) / 1000;
        break;
      default:
        surplus = 0;
    }

    let surplusTimetext = formatDuring(surplus);
    return surplus > 0 ? '剩余' + surplusTimetext : '延期' + surplusTimetext;
  }

  // 改变排序
  const changeSort = useCallback((sortType) => {
    let sortValue = '';
    if (sortType.type !== 'default') {
      if (sortType.desc) {
        sortValue = sortType.type + 'Desc';
      } else {
        sortValue = sortType.type + 'Asc';
      }
    }
    setOrderBy(sortValue);
    setCurPage(1);
  }, []);

  function taskClick(id) {
    if (!current_user.user_id) {
      showLoginDialog();
      return;
    }
    history.push(`/task/taskDetail/${id}`);
  }

  // 新增校验
  function goAdd() {
    if (!current_user.user_id) {
      showLoginDialog();
      return;
    }
    getCompanyInfo().then(res => {
      if (res) {
        if (res.message === 'success') {
          history.push("/task/taskAdd");
        } else if (res.message === '未进行实体认证') {
          Modal.info({
            title: '因为以下原因，您暂时不能进行本操作',
            content: <div className="mt10">
              <p>完成条件后，重新点击查看您的最新参与资格</p>
              <div className="inline mt10">
                <span className="mr30"> <i className="iconfont icon-mingpian"></i> <span className="color-red">主体信息未认证</span> </span>
              </div>
            </div>,
            onOk: () => {
              window.location.href = mygetHelmetapi && mygetHelmetapi.main_web_site_url + `/users/${current_user.login}/profiles`;
            },
            okText: '立即完善',
            className: 'go_profiles'
          });
        } else {
          Modal.info({
            content: '您没有权限需求提报',
            className:'failByPression'
          });
        }
      }
    });
  }

  return (
    <div className="centerbox" style={{ marginTop: '20px' }}>
      <div className="nav-content">
        <ChooseNav
          key={'taskCategory'}
          type={'taskCategory'}
          title={'任务领域：'}
          options={taskCategoryArr}
          changeOptionId={changeOptionId}
          size='big'
          defaultOption={{ code: initType || "", dicItemName: "", dicItemCode: initType || "" }}
        />

        <ChooseNav
          key={'taskModeId'}
          type={'taskModeId'}
          title={'任务模式：'}
          options={taskModeIdArr}
          changeOptionId={changeOptionId}
          size='big'
        />

        <ChooseNav
          key={'taskTime'}
          type={'taskTime'}
          title={'任务时限：'}
          options={taskTimeArr}
          changeOptionId={changeOptionId}
          size='big'
        />

        <ChooseNav
          key={'taskStatus'}
          type={'taskStatus'}
          title={'任务状态：'}
          options={taskStatusArr}
          changeOptionId={changeOptionId}
          size='big'
        />
      </div>

      <div className="center-content">
        <div className="centerScreen" >

          <SortBox
            options={sortArr}
            changeOptionId={changeSort}
          />

          <div className="center-right-but">
            <Search
              maxLength={20}
              style={{ width: "300px" }}
              placeholder="请输入任务编号/任务名称关键字"
              onSearch={(value) => { setSearchInput(value); setCurPage(1); }}
            />

            <Button className="mr20 font-12 demand_submission" type="primary" onClick={goAdd}><i className="iconfont icon-zaibianji font-12 mr3"></i>需求提报</Button>

          </div>
        </div>

        <ItemListTask
          list={taskList}
          itemClick={taskClick}
          curPage={curPage}
          total={total}
          changePage={(page) => { setCurPage(page) }}
          loading={loading}
        />

      </div>


    </div>
  )
}