import React, { useCallback, useEffect, useState } from 'react';
import { Tabs, Input, } from 'antd';
import StatusNav from '../../components/statusNav';
import ItemListMyTask from '../components/itemListMyTask';
import JoinTask from './joinTask';
import { taskStatusAllArr, } from '../static';
import { getTaskCategory, getMyTaskList } from '../api';
import './index.scss';
const Search = Input.Search;
const { TabPane } = Tabs;

const publishStatusArr = taskStatusAllArr.slice(3, 9);
const unpublishStatusArr = taskStatusAllArr.slice(0, 3);
unpublishStatusArr.push({ dicItemCode: '9', name: "待修缮", dicItemName: "待修缮" });

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

export default ({ location, history, current_user, showNotification }) => {
  console.log(current_user);
  let defaultValue = decodeURI(location.search.split("=")[1] || "");

  const [identity, setIdentity] = useState('1');
  const [taskCategoryValueArr, setTaskCategoryValueArr] = useState([]);

  const [statusType, setStatusType] = useState(() => {
    return defaultValue === 'false' ? '2' : '1';
  });
  const [statusString, setStatusString] = useState(() => {
    return defaultValue === 'false' ? '0,1,2,9' : '3,4,5,6,7,8';
  });

  const [searchInput, setSearchInput] = useState('');
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [myTaskList, setMyTaskList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [reload, setReload] = useState(0);

  // 获取任务领域数组
  useEffect(() => {
    getTaskCategory().then(data => {
      if (data) {
        const taskCategoryValueArr = [];
        for (const item of data) {
          taskCategoryValueArr[item.id] = item.name;
        }
        setTaskCategoryValueArr(taskCategoryValueArr);
      }
    });
  }, []);

  useEffect(() => {
    const params = {
      statusString,
      searchInput,
      orderBy: 'createdAtDesc',
      curPage,
      pageSize: 10,
    };
    setLoading(true);
    getMyTaskList(params).then(data => {
      if (data) {
        for (const item of data.rows) {
          item.delayTime = surplusTime(item);
        }
        setMyTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })
  }, [statusString, searchInput, curPage, reload]);

  function taskClick(id) {
    history.push(`/task/taskDetail/${id}`);
  }
  
  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;
    }

    return surplus ;
  }

  const changeOptionId = useCallback((option, type) => {
    if (type === 'publishStatus') {
      setStatusString(option.dicItemCode.toString() || '3,4,5,6,7,8');
    } else if (type === 'unpublishStatus') {
      setStatusString(option.dicItemCode.toString() || '0,1,2,9');
    }
    setCurPage(1);
  }, [])

  function changeIdentity(key) {
    setIdentity(key);
    if (key === '1') {
      setStatusString('3,4,5,6,7,8');
    } else {
      setStatusString('0,1,2,9');
    }
    setCurPage(1);
  }

  function changeStatusType(key) {
    if (key === '1') {
      setStatusString('3,4,5,6,7,8');
    } else {
      setStatusString('0,1,2,9');
    }
    setCurPage(1);
    setStatusType(key);
  }

  const reloadList = useCallback(() => {
    setReload(Math.random());
  }, []);

  return (
    <div className="centerbox my-task">
      <Tabs defaultActiveKey={identity} onChange={changeIdentity}>
        <TabPane tab="我是雇主" key="1">

          <Tabs className="childTab"
            activeKey={statusType}
            onChange={changeStatusType}
            tabBarExtraContent={
              <Search
                maxLength={20}
                style={{ width: "300px" }}
                placeholder="请输入任务编号/任务名称关键字"
                onSearch={(value) => { setSearchInput(value); setCurPage(1) }}
              />
            }
          >
            <TabPane tab="我发布的任务" key="1">
              {
                identity === '1' && statusType === '1' && <StatusNav
                  key={'publishStatus'}
                  type={'publishStatus'}
                  options={publishStatusArr}
                  changeOptionId={changeOptionId}
                />
              }

              <ItemListMyTask
                list={myTaskList}
                itemClick={taskClick}
                curPage={curPage}
                total={total}
                taskCategoryValueArr={taskCategoryValueArr}
                changePage={(page) => { setCurPage(page) }}
                loading={loading}
                publish={true}
                showNotification={showNotification}
                reloadList={reloadList}
              />
            </TabPane>

            <TabPane tab="任务草稿" key="2">
              {
                identity === '1' && statusType === '2' && <StatusNav
                  key={'unpublishStatus'}
                  type={'unpublishStatus'}
                  options={unpublishStatusArr}
                  changeOptionId={changeOptionId}
                />
              }

              <ItemListMyTask
                list={myTaskList}
                itemClick={taskClick}
                curPage={curPage}
                total={total}
                taskCategoryValueArr={taskCategoryValueArr}
                changePage={(page) => { setCurPage(page) }}
                loading={loading}
                showNotification={showNotification}
                reloadList={reloadList}

              />
            </TabPane>
          </Tabs>

        </TabPane>


        <TabPane tab="我是创客" key="2">

          <JoinTask
            taskCategoryValueArr={taskCategoryValueArr}
            showNotification={showNotification}
          />
        </TabPane>

      </Tabs>

    </div>
  )
}