import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Tabs, Input, Table, Pagination, Modal, Button } from 'antd';
import { Link } from "react-router-dom";
import ChooseNav from '../../components/chooseNav';
import ItemListMyTask from '../components/itemListMyTask';
import AgreementModal from '../components/agreementModal';
import ComplainModal from '../components/complainModal';
import { applyStatusAllArr, paperCheckStatusArr, applyStatusArr, publishModeArr, taskStatusAllArr } from '../static';
import { getJoinTaskList, myPapers, confirmReceipt } from '../api';
import './index.scss';
const Search = Input.Search;
const { TabPane } = Tabs;

const publishStatusArr = taskStatusAllArr.slice(3, 9);

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

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

export default ({ taskCategoryValueArr, showNotification }) => {

  const [paperStatusString, setPaperStatusString] = useState('0,1,2,3,4');
  const [taskStatusString, setTaskStatusString] = useState('3,4,5,6,7,8');

  const [requirePaper, setRequirePaper] = useState('1');
  const [searchInput, setSearchInput] = useState('');
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);
  const [loading, setLoading] = useState(false);

  const [curPagePaper, setCurPagePaper] = useState(1);
  const [totalPaper, setTotalPaper] = useState(0);
  const [paperList, setPaperList] = useState([]);

  const [checkedItem, setCheckedItem] = useState({});
  const [complainVisible, setComplainVisible] = useState(false);
  const [agreeVisible, setAgreeVisible] = useState(false);

  const [reload, setReload] = useState(0);

  useEffect(() => {
    if (requirePaper === '1') {
      const params = {
        paperStatusString,
        taskStatusString,
        searchInput,
        curPage,
        pageSize: 10,
      };
      setLoading(true);
      getJoinTaskList(params).then(data => {
        if (data) {
          setTaskList(data.rows);
          setTotal(data.total);
        }
        setLoading(false);
      });
    }
  }, [requirePaper, paperStatusString, taskStatusString, searchInput, curPage]);

  useEffect(() => {
    if (requirePaper === '2') {
      const params = {
        status: paperStatusString,
        searchInput,
        curPage,
        pageSize: 10,
      };
      setLoading(true);
      myPapers(params).then(data => {
        if (data) {
          setPaperList(data.rows);
          setTotalPaper(data.total);
        }
        setLoading(false);
      })
    }
  }, [requirePaper, paperStatusString, searchInput, curPagePaper, reload]);


  const columns = useMemo(() => {
    return [
      {
        title: '任务编号',
        dataIndex: 'name',
        render: (text, record) => {
          return <Link className="color-grey3 font-16 font-bd" to={`/task/taskDetail/${record.task.id}`}>{record.task.number}</Link>
        }
      },
      {
        title: '任务名称',
        dataIndex: 'name',
        width: '20%',
        render: (text, record) => {
          return record.task.name
        }
      },
      {
        title: '成果编号',
        dataIndex: 'number',
      },
      {
        title: '上传文件',
        dataIndex: 'files',
        render: (text) => {
          return text ? text.split(',').length : 0
        }
      },
      {
        title: '提交时间',
        dataIndex: 'createdAt',
      },
      {
        title: '应征状态',
        dataIndex: 'status',
        render: (text, record) => {
          return text === 0 ? paperCheckStatus[record.checkStatus] : statusArr[text]
        }
      },
      {
        title: '操作',
        key: 'action',
        className: 'action-td',
        render: (text, record) => (
          <React.Fragment>
            {/* <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.task.id}`}>查看详情</Link> */}
            <Button size="small" onClick={() => { window.location.href = `/task/taskDetail/${record.task.id}` }}>查看详情</Button>

            {((record.needComplain && record.task.status === 3) || (record.task.status === 5 && record.publicTaskComplain && record.status !== 2)) &&
              <Button type="danger" size="small" onClick={() => { setComplainVisible(true); setCheckedItem(record) }}>申诉</Button>
            }

            {record.status === 2 && record.task.status === 6 && (!record.sign) && (record.canApplicantSign || record.canApplicantSignByPlatform) &&
              < Button type="primary" size="small" onClick={() => { setAgreeVisible(true); setCheckedItem(record) }}>签订协议</Button>
            }

            {
              record.status === 2 && (!record.pay) && record.task.status === 7 && record.task.agreementSigning === 1 &&
              <Button type="primary" size="small" onClick={() => { confirmReceiptModal(record.id) }}>确认收款</Button>
            }
          </React.Fragment >
        ),
      },
    ];
  }, [taskCategoryValueArr, publishModeArr, statusArr]);


  function confirmReceiptModal(paperId) {
    Modal.confirm({
      title: '确认收款',
      content: '确认已经收到任务报酬',
      onOk: () => {
        confirmReceipt(paperId).then(res => {
          if (res && res.message === "success") {
            showNotification("您已确认收款！");
            reloadList();
          }
        })
      }
    })
  }


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

  function changeRequirePaper(key) {
    if (key === '1') {
      setPaperStatusString('0,1,2,3,4');
    } else {
      setTaskStatusString('3,4,5,6,7,8');
      setPaperStatusString('0,1,2,3,4');
    }
    setCurPage(1);
    setRequirePaper(key);
  }

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

  return (

    <Tabs className="childTab"
      activeKey={requirePaper}
      onChange={changeRequirePaper}
      tabBarExtraContent={
        <Search
          maxLength={20}
          style={{ width: "300px" }}
          placeholder="请输入任务编号/任务名称关键字"
          onSearch={(value) => { setSearchInput(value); setCurPage(1); }}
        />
      }
    >
      <TabPane tab="我参加的任务" key="1">

        {requirePaper === '1' &&
          <React.Fragment>
            <ChooseNav
              key={'taskStatus'}
              type={'taskStatus'}
              title={'任务状态：'}
              options={publishStatusArr}
              changeOptionId={changeOptionId}
            />

            <ChooseNav
              key={'applyStatus'}
              type={'applyStatus'}
              title={'应征状态：'}
              options={applyStatusArr}
              changeOptionId={changeOptionId}
            />
          </React.Fragment>
        }


        <ItemListMyTask
          list={taskList}
          curPage={curPage}
          total={total}
          taskCategoryValueArr={taskCategoryValueArr}
          changePage={(page) => { setCurPage(page) }}
          loading={loading}
          joinTask={true}
        />
      </TabPane>

      <TabPane tab="我的成果" key="2">
        {
          requirePaper === '2' && <ChooseNav
            key={'applyStatus'}
            type={'applyStatus'}
            title={'应征状态：'}
            options={applyStatusArr}
            changeOptionId={changeOptionId}
          />
        }

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

        <ComplainModal
          visible={complainVisible}
          setVisible={setComplainVisible}
          checkedItem={checkedItem}
          detailStatus={checkedItem.task && checkedItem.task.status}
          showNotification={showNotification}
          reloadList={reloadList}
        />

        {agreeVisible && <AgreementModal
          checkedItem={checkedItem}
          visible={agreeVisible}
          setVisible={setAgreeVisible}
          showNotification={showNotification}
          reloadList={reloadList}
        />}

      </TabPane>
    </Tabs>

  )
}