//空间作业

import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import {
  Table,
  Form,
  Input,
  Button,
  Divider,
  Modal,
  Tabs,
  Select,
  Empty,
  DatePicker,
  AutoComplete,
} from 'antd';
import moment from 'moment';
import { downloadFile, UnityAction } from '@/utils/utils';
import styles from './LimitedSpace.less';
import SaveModal from './SaveModal';

function Operation(props) {
  const {
    dispatch,
    currentUser,
    loading,
    form,
    rescue,
    config,
    spaceList,
    rescueDetail,
    spaceDetail,
  } = props;
  const { projectId } = props.match.params;
  const { RangePicker } = DatePicker;
  const { getFieldsValue, getFieldDecorator } = form;
  const [selectVisible, setSelectVisible] = useState(false);
  const [createVisible, setCreateVisible] = useState(false);
  const [isDetail, setIsDetail] = useState(false);
  const [selectedSpace, setSelectedSpace] = useState();
  const [selectedRecord, setSelectedRecord] = useState({});

  const columns = [
    { title: '序号', dataIndex: 'saveId' },
    { title: '时间', dataIndex: 'r_time' },
    { title: '空间名称', dataIndex: 'name' },
    {
      title: '操作',
      render: record => (
        <>
          <a onClick={() => onDetail(record)}>详情</a>
          <Divider type="vertical" />
          {/* <a onClick={() => onDownload(record)}>下载</a> */}
          {/* <a>下载应急处置卡</a> */}
          {/* <Divider type="vertical" /> */}
          <a onClick={() => onDownload(record)}>下载应急预案</a>
          <Divider type="vertical" />
          <a onClick={() => onDelete(record)}>删除</a>
        </>
      ),
    },
  ];
  const temp = [
    { id: 1, operation: '测试1' },
    { id: 2, operation: '测试2' },
  ];

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

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

    dispatch({
      type: 'limitedSpace/queryRescue',
      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/queryRescue',
      payload: { project_id: projectId, ...filter },
      callback: data => {
        setTimeout(() => {
          UnityAction.sendMsg('SpaceDatasFromWeb', data);
        }, 800);
      }
    });
  };

  const onDetail = record => {
    console.log(record);
    dispatch({
      type: 'limitedSpace/queryRescueDetail',
      payload: {
        id: record.id,
      },
    });
    setIsDetail(true);
    setSelectedRecord(record);
    setCreateVisible(true);
  };
  const onDownload = record => {
    console.log(record);
    dispatch({
      type: 'limitedSpace/queryDownloadRescue',
      payload: {
        project_id: projectId,
        id: record.id,
      },
      callback: url => downloadFile(url, `应急处置预案_${record.name}`),
    });
  };

  const onDownloadCard = () => {
    dispatch({
      type: 'limitedSpace/queryDownloadCard',
      payload: {
        project_id: projectId,
        id: selectedRecord.id,
      },
      callback: url => downloadFile(url, `应急处理卡_${selectedRecord.name}`),
    });
  };
  const onDelete = record => {
    Modal.confirm({
      title: '提醒',
      content: `确认删除作业？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'limitedSpace/deleteRescue',
          payload: {
            id: record.id,
            project_id: projectId,
          },
        });
      },
    });
  };

  const onCancel = () => {
    setCreateVisible(false);
    setSelectVisible(false);
    setIsDetail(false);
    setSelectedSpace();
    setSelectedRecord({});
  };
  const onSelectOk = () => {
    setSelectVisible(false);
    setCreateVisible(true);
    dispatch({
      type: 'limitedSpace/querySpaceDetail',
      payload: { id: selectedSpace },
    });
  };
  const onCreateOk = () => {
    dispatch({
      type: 'limitedSpace/createRescue',
      payload: { space_id: Number(selectedSpace), project_id: Number(projectId) },
    });

    setCreateVisible(false);
    setSelectedSpace();
    form.resetFields();
  };

  const onChange = value => {
    setSelectedSpace(value);
  };

  const createRescue = () => {
    setSelectVisible(true);
  };

  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={() => createRescue()} type="primary">
          创建应急处置卡
        </Button>
      </div>
      <Table
        loading={loading}
        columns={columns}
        dataSource={rescue.list}
        pagination={rescue.pagination}
        onChange={pagination => onQueryList(pagination)}
      />
      <Modal
        title="选择空间"
        visible={selectVisible}
        onCancel={() => onCancel()}
        onOk={() => onSelectOk()}
      >
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} layout="horizontal">
          <Form.Item label="救援空间：">
            <Select
              showSearch
              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>
      <SaveModal
        visible={createVisible}
        spaceDetail={isDetail ? rescueDetail : spaceDetail}
        onOk={() => (isDetail ? onDownloadCard() : onCreateOk())}
        onCancel={() => onCancel()}
        okText={isDetail ? '下载' : '确定'}
      />
    </div>
  );
}

export default connect(({ limitedSpace, user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.limitedSpace,
  config: limitedSpace.config,
  spaceList: limitedSpace.space.list,
  rescue: limitedSpace.rescue,
  rescueDetail: limitedSpace.rescueDetail,
  spaceDetail: limitedSpace.spaceDetail,
}))(Form.create()(Operation));
