//空间作业

import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import {
  Table,
  Form,
  Input,
  Button,
  Divider,
  Modal,
  Select,
  DatePicker,
  AutoComplete,
  message,
} from 'antd';
import moment from 'moment';
import { downloadFile, UnityAction } from '@/utils/utils';
import ReactZmage from 'react-zmage';
import styles from './LimitedSpace.less';
import OperationDetail from './OperationDetail.js';

function Operation(props) {
  const { dispatch, currentUser, loading, form, operation, spaceList } = props;
  const { projectId } = props.match.params;
  const { RangePicker } = DatePicker;
  const { getFieldsValue, getFieldDecorator } = form;
  const [selectVisible, setSelectVisible] = useState(false);
  const [createVisible, setCreateVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [selectedSpace, setSelectedSpace] = useState([]);

  const columns = [
    { title: '序号', dataIndex: 'opId' },
    { title: '空间名称', dataIndex: 'name' },
    { title: '作业内容', dataIndex: 'op_content' },
    { title: '时间', render: record => moment(record.op_time).format('YYYY-MM-DD HH:mm') },
    {
      title: '操作',
      render: record => (
        <>
          <a onClick={() => onDetail(record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => onDownload(record)}>下载</a>
          <Divider type="vertical" />
          <a onClick={() => onDelete(record)}>删除</a>
        </>
      ),
    },
  ];

  useEffect(() => {
    dispatch({
      type: 'limitedSpace/querySpace',
      payload: { project_id: projectId },
    });

    dispatch({
      type: 'limitedSpace/queryOperation',
      payload: { project_id: projectId },
      callback: data => {
        setTimeout(() => {
          UnityAction.sendMsg('SpaceDatasFromWeb', data);
        }, 800);
      },
    });
  }, []);

  const onQueryList = (pagination = {}) => {
    const { date, name } = getFieldsValue();
    let s_time, e_time;
    if (date) {
      s_time = date[0].format('yyyy-MM-DD');
      e_time = date[1].format('yyyy-MM-DD');
    }
    let filter = { s_time, e_time, space_name: name, ...pagination };
    dispatch({
      type: 'limitedSpace/queryOperation',
      payload: { project_id: projectId, ...filter },
      callback: data => {
        setTimeout(() => {
          UnityAction.sendMsg('SpaceDatasFromWeb', data);
        }, 800);
      },
    });
  };

  const onDetail = record => {
    setCurrentRecord(record);
    setCreateVisible(true);
  };

  const onDownload = record => {
    dispatch({
      type: 'limitedSpace/queryDownloadOperation',
      payload: {
        project_id: projectId,
        id: record.id,
      },
      callback: url => downloadFile(url, `空间作业_${record.name}`),
    });
  };

  const onDelete = record => {
    Modal.confirm({
      title: '提醒',
      content: `确认删除作业？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'limitedSpace/deleteOperation',
          payload: {
            id: record.id,
            project_id: projectId,
          },
        });
      },
    });
  };

  const onCancel = () => {
    setCreateVisible(false);
    setSelectVisible(false);
    setSelectedSpace([]);
    setCurrentRecord(null);
  };

  const onSelectOk = () => {
    setSelectVisible(false);
    setCreateVisible(true);
  };

  const onOk = () => {
    setCreateVisible(false);
    setSelectedSpace([]);
    setCurrentRecord(null);
  };

  const onChange = value => {
    if (value.length <= 5) setSelectedSpace([...value]);
    else message.error('最多选择5个作业空间');
  };

  const nameFilter = (value, option) => {
    return option.key.indexOf(value) != -1;
  };

  return (
    <div className={styles.page}>
      <Form layout="inline" labelAlign="right">
        <Form.Item className={styles.searchItem} label="作业时间:">
          {getFieldDecorator('date')(<RangePicker style={{ width: '35vw' }} />)}
        </Form.Item>
        <Form.Item className={styles.searchItem} label="空间名称:">
          {getFieldDecorator('name')(
            <AutoComplete
              style={{ width: '25vw', display: 'block' }}
              dataSource={spaceList.map(item => item.name)}
              filterOption={(value, option) => nameFilter(value, option)}
              children={<Input style={{ borderRadius: '8px' }} />}
            />
          )}
        </Form.Item>
      </Form>

      <div style={{ marginBottom: 20, marginTop: 10 }}>
        <Button style={{ marginRight: 20 }} onClick={() => onQueryList()} type="primary">
          搜索
        </Button>
        <Button onClick={() => setSelectVisible(true)} type="primary">
          创建空间作业
        </Button>
      </div>

      <Table
        columns={columns}
        loading={loading}
        dataSource={operation.list}
        pagination={operation.pagination}
        onChange={pagination => onQueryList(pagination)}
      />
      <Modal
        className={styles.selectModal}
        title="选择空间"
        visible={selectVisible}
        onCancel={() => onCancel()}
        onOk={() => onSelectOk()}
      >
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} layout="horizontal">
          <Form.Item label="作业空间：">
            <Select
              mode="multiple"
              onChange={value => onChange(value)}
              placeholder="请选择空间"
              loading={loading}
              style={{ width: '100%' }}
              value={selectedSpace}
              optionFilterProp="label"
            >
              {spaceList?.map(item => (
                <Select.Option key={item.id} label={`${item.data1}-${item.name}`}>
                  {`${item.data1}-${item.name}`}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      <OperationDetail
        visible={createVisible}
        selectedSpace={selectedSpace}
        currentRecord={currentRecord}
        projectId={projectId}
        onOk={onOk}
        onCancel={onCancel}
        loading={loading}
      />
    </div>
  );
}

export default connect(({ limitedSpace, user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.limitedSpace,
  spaceList: limitedSpace.space.list,
  operation: limitedSpace.operation,
  operationList: limitedSpace.operation.list,
  pagination: limitedSpace.operation.pagination,
}))(Form.create()(Operation));
