import { useState, useEffect, useMemo } from 'react';
import { Button, Table, Space, Pagination } from 'antd';

import TaskDetail from './TaskDetail';
import UpdateTask from './UpdateTask';
import AuditTask from './AuditTask';
import CheckTask from './CheckTask';
import { dispatch } from '../../../model';
import { paginate } from '../../../util';

export const status = {
  'tobeDistributed': '待分发',
  'checking': '盘点中',
  'tobeReviewed': '待审核',
  'finished': '已完成',
  '1': '通过',
  '-1': '未通过',
}

const FC = (props) => {
  const [loading, setLoading] = useState(false);
  const [tasks, setTasks] = useState();
  const [ pagination, setPagination ] = useState({ pageNum: 1, pageSize: 20 });
  const { pageNum, pageSize } = pagination;
  const [taskDetailParams, setTaskDetailParams] = useState({
    visible: false,
    task: undefined,
  });
  const [updateTaskParams, setUpdateTaskParams] = useState({
    visible: false,
    task: undefined,
    action: 'add',
  });
  const [auditTaskParams, setAuditTaskParams] = useState({
    visible: false,
    task: undefined,
    action: undefined,
  });
  const [checkTaskParams, setCheckTaskParams] = useState({
    visible: false,
    task: undefined,
  });

  const onActionClick = (task, action) => {
    if (action === '详情') {
      setTaskDetailParams({...taskDetailParams, task, visible: true});
    } else if (action === '修改') {
      setUpdateTaskParams({...updateTaskParams, task, visible: true, action: 'edit'});
    } else if (action === '盘点') {
      setCheckTaskParams({...checkTaskParams, task, visible: true});
    } else {
      setAuditTaskParams({...auditTaskParams, action, task, visible: true});
    }
  }

  const columns = useMemo(() => {
    return (
      [
        {
          title: '任务ID',
          dataIndex: 'id',
          ellipsis: true,
        },
        {
          title: '任务标题',
          dataIndex: 'title',
          ellipsis: true,
        },
        {
          title: '任务说明',
          dataIndex: 'comment',
          ellipsis: true,
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          ellipsis: true,
          render: (state, _, __) => status[state],
        },
        {
          title: '所属部门',
          dataIndex: 'department',
          ellipsis: true,
          render: (department, _, __) => department?.groupDisplayName??department?.groupName,
        },
        {
          title: '资产专员',
          dataIndex: 'specialist',
          ellipsis: true,
          render: (user, _, __) => user?.userDisplayName??user?.userName,
        },
        {
          title: '更新日期',
          dataIndex: 'updateTime',
          ellipsis: true,
        },
        {
          title: '更新人',
          dataIndex: 'updateUser',
          ellipsis: true,
          render: (user, _, __) => user?.userDisplayName??user?.userName,
        },
        {
          title: '创建日期',
          dataIndex: 'createTime',
          ellipsis: true,
        },
        {
          title: '创建人',
          dataIndex: 'createUser',
          ellipsis: true,
          render: (user, _, __) => user?.userDisplayName??user?.userName,
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          render: (_,record) => (
            <Space size='small'>
            {
              record.actionList?.map((action, index) => <a key={index} onClick={() => {onActionClick(record, action.title)}}>{action.title}</a>)
            }
            </Space>
          )
        }
      ]
    )
  }, [onActionClick])

  const _tasks = useMemo(() => {
    return paginate(tasks, pagination.pageNum, paginate.pageSize
      )
  }, [pagination, tasks])

  useEffect(() => {
    getTasks();
  }, [])

  const getTasks = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.listTasks',
      callback: (data) => {
        setLoading(false);
        setTasks(data);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onAddClick = () => {
    setUpdateTaskParams({...updateTaskParams, action: 'add', visible: true});
  }

  const onTaskDetailCancel = () => {
    setTaskDetailParams({...taskDetailParams, visible: false});
  }

  const onUpdateTaskCancel = (refresh = false) => {
    setUpdateTaskParams({...updateTaskParams, visible: false});
    refresh && getTasks();
  }

  const onAuditTaskCancel = (refresh = false) => {
    setAuditTaskParams({...auditTaskParams, visible: false});
    refresh && getTasks();
  } 

  const onCheckTaskCancel = (refresh = false) => {
    setCheckTaskParams({...checkTaskParams, visible: false});
    refresh && getTasks();
  } 

  return (
    <div style={{ backgroundColor: '#fff', height: '100%' }}>
      <div
        className='d-flex p-3'
        style={{
          borderBottom: '1px solid #EFEFEF',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}
      >
        <Button onClick={onAddClick}>新增</Button>
      </div>
      <div className='p-3'>
        <Table
          rowKey='id'
          loading={loading}
          columns={columns}
          dataSource={_tasks||[]}
          pagination={false}
          scroll={{ y: (_tasks||[]).length===0?null:'calc(100vh - 121px - 57px - 24px - 38px - 44px)' }}
        />
        {
          (tasks||[]).length>0 && <Pagination
            className="text-center mt-3"
            showSizeChanger
            showQuickJumper
            onChange={(_pageNum, _pageSize) => {
              setPagination({ pageNum: _pageNum, pageSize: _pageSize || 20 });
            }}
            onShowSizeChange={(_pageNum, _pageSize) => {
              setPagination({ pageNum: 1, pageSize: _pageSize });
            }}
            current={pageNum}
            pageSize={pageSize}
            defaultCurrent={1}
            total={(tasks||[]).length}
            pageSizeOptions={[10,20,50]}
            showTotal={total => `共 ${(tasks||[]).length} 条`}
          />
        }
      </div>

      <TaskDetail
        visible={taskDetailParams.visible}
        task={taskDetailParams.task}
        onCancel={onTaskDetailCancel}
      />

      <UpdateTask
        visible={updateTaskParams.visible}
        task={updateTaskParams.task}
        action={updateTaskParams.action}
        onCancel={onUpdateTaskCancel}
      />

      <AuditTask
        visible={auditTaskParams.visible}
        task={auditTaskParams.task}
        action={auditTaskParams.action}
        onCancel={onAuditTaskCancel}
      />

      <CheckTask
        visible={checkTaskParams.visible}
        task={checkTaskParams.task}
        onCancel={onCheckTaskCancel}
      />
    </div>
  )
}

export default FC;