//空间台账

import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'dva';
import {
  Table,
  Form,
  Input,
  Button,
  Upload,
  Modal,
  Select,
  AutoComplete,
  Alert,
  Divider,
  message,
} from 'antd';
import router from 'umi/router';
import { UnityAction, getToken, GetTokenFromUrl } from '@/utils/utils';
import styles from './LimitedSpace.less';
import project from '@/models/project';
import SearchModal from './SearchModal';
import EditModal from './EditModal';
import { downloadFile } from '@/utils/utils';
import { downloadQRCode } from '@/services/limitedSpace';

function List(props) {
  const { dispatch, loading, currentUser, form, config, space, pagination, areaList } = props;
  const { projectId } = props.match.params;
  const { group_id } = props.location.query;
  const { getFieldDecorator, getFieldsValue } = form;
  const [currentItem, setCurrentItem] = useState(null);
  const [multiQuery, setMultiQuery] = useState([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const multiQueryRef = useRef([]);

  const clickDetail = record => {
    setCurrentItem(record);
    let url = `/unity/limitedSpace/detail/${projectId}/${record.id}?JWT-TOKEN=${GetTokenFromUrl()}`;

    if (!group_id) UnityAction.sendMsg('SpaceDatasFromWeb', JSON.stringify([record]));
    else url = url.concat(`&group_id=${group_id}`);

    UnityAction.sendMsg('SelectSpaceFromWeb', record.id);
    router.push(url);
  };

  const token = getToken();
  const uploadProps = {
    name: 'file',
    action: `/api/limitedspace/v1/space/upload`,
    headers: {
      'JWT-TOKEN': token,
    },
    data: {
      project_id: projectId,
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
        dispatch({
          type: 'limitedSpace/querySpace',
          payload: { project_id: projectId },
        });
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onRemove() {
      return new Promise((resolve, reject) => {
        Modal.confirm({
          title: '提醒',
          content: `确认删除图片？`,
          okText: '确认',
          cancelText: '取消',
          onOk: resolve,
          onCancel: reject,
        });
      });
    },
  };

  const editUploadProps = {
    name: 'files',
    action: `/api/v1/common/file-upload?path=${projectId}/运营平台/设计文档/其他资料/&project_id=${projectId}`,
    headers: {
      'JWT-TOKEN': token,
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(` 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onRemove() {
      return new Promise((resolve, reject) => {
        Modal.confirm({
          title: '提醒',
          content: `确认删除图片？`,
          okText: '确认',
          cancelText: '取消',
          onOk: () => resolve(),
          onCancel: () => reject(),
        });
      });
    },
  };
  const onBack = () => {
    router.go(-1);
    if (group_id) UnityAction.sendMsg('BackToOverallFromWeb');
    UnityAction.sendMsg('BackToIndex');
  };

  const onQueryList = (pagination = {}) => {
    const { name, area } = getFieldsValue();
    let query = [...multiQueryRef.current];
    let filter = { name: name, group_id, ...pagination };
    if (area) {
      query.push({ k: 'data1', v: area });
    }
    filter = { ...filter, query: JSON.stringify(query) };
    dispatch({
      type: 'limitedSpace/querySpace',
      payload: { project_id: projectId, ...filter },
    });
  };

  const onEdit = record => {
    setCurrentItem(record);
    setEditVisible(true);
  };

  const onCancel = () => {
    setCurrentItem(null);
    setSearchVisible(false);
    setEditVisible(false);
  };

  const onOk = (query = []) => {
    multiQueryRef.current = query;
    onQueryList();
    setSearchVisible(false);
  };

  const onEditOk = data => {
    dispatch({
      type: 'limitedSpace/updateSpace',
      payload: {
        x: currentItem.x,
        y: currentItem.y,
        z: currentItem.z,
        gif_id: currentItem.gif_id,
        group_id: currentItem.group_id,
        type: currentItem.type,
        name: currentItem.name,
        id: currentItem.id,
        project_id: Number(projectId),
        extend: data,
      },
      callback: () => {
        onQueryList();
        setCurrentItem(null);
        setEditVisible(false);
      },
    });
  };

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

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

    if (group_id) {
      dispatch({
        type: 'limitedSpace/querySpace',
        payload: { project_id: projectId, group_id: group_id },
        callback: list => {
          UnityAction.sendMsg(
            'SpaceDatasFromWeb',
            JSON.stringify(list.filter(item => item.group_id == group_id))
          );

          UnityAction.addEventListener('SelectSpaceFromUnity', e => {
            let record = list.find(item => item.id == e);
            setCurrentItem(record);
            let url = `/unity/limitedSpace/detail/${projectId}/${
              record.id
            }?JWT-TOKEN=${GetTokenFromUrl()}`;
            if (group_id) url = url.concat(`&group_id=${group_id}`);
            router.push(url);
          });
        },
      });
      return () => {
        UnityAction.off('SelectSpaceFromUnity');
      };
    } else {
      dispatch({
        type: 'limitedSpace/querySpace',
        payload: { project_id: projectId },
      });
    }
  }, []);

  const columns = [
    { title: '序号', dataIndex: 'spaceId' },
    { title: '存在区域', dataIndex: 'data1' },
    { title: '空间名称', dataIndex: 'name' },
    {
      title: '深度',
      render: record => {
        return `${record.data8 || '-'} 米`;
      },
    },
    {
      title: '操作',
      width: 200,
      render: record => (
        <>
          <a onClick={() => onEdit(record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => clickDetail(record)}>详情</a>
        </>
      ),
    },
  ];

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

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

  return (
    <div className={styles.page}>
      <div style={{ display: 'flex' }}>
        <Form layout="inline" labelAlign="left" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
          <Form.Item className={styles.searchItem} label="空间名称:">
            {getFieldDecorator('name')(
              <AutoComplete
                style={{ display: 'block' }}
                dataSource={space.list.map(item => item.name)}
                filterOption={(value, option) => nameFilter(value, option)}
                children={
                  <Input placeholder="请选择空间名称" style={{ borderRadius: '8px', width: 180 }} />
                }
              />
            )}
          </Form.Item>
          {!group_id && (
            <Form.Item className={styles.searchItem} label="存在区域:">
              {getFieldDecorator('area')(
                <AutoComplete
                  style={{ display: 'block' }}
                  dataSource={areaList.map(item => item.name)}
                  filterOption={(value, option) => areaFilter(value, option)}
                  children={
                    <Input
                      placeholder="请选择存在区域"
                      style={{ borderRadius: '8px', width: 180 }}
                    />
                  }
                />
              )}
            </Form.Item>
          )}
        </Form>
        <div style={{ display: 'flex' }}>
          <Button onClick={() => onQueryList()} type="primary" style={{ marginRight: 20 }}>
            搜索
          </Button>
          <Button onClick={() => setSearchVisible(true)} type="primary">
            高级搜索
          </Button>
        </div>
      </div>

      <div style={{ marginBottom: 20, marginTop: 10 }}>
        {group_id && (
          <Button onClick={() => onBack()} type="primary" style={{ marginRight: 20 }}>
            返回
          </Button>
        )}
        <Button onClick={() => downloadQRCode(projectId, group_id)} type="primary">
          下载全部二维码
        </Button>
      </div>
      <div>
        <Alert
          message={`共有空间${space.statistics.total || 0}个，其中，地上${space.statistics.num1 ||
            0}个，地下${space.statistics.num2 || 0}个，密闭容器${space.statistics.num3 || 0}个`}
          type="info"
        />
      </div>
      <Table
        dataSource={space.list}
        loading={loading}
        columns={columns.filter(item => (group_id ? item.title != '存在区域' : item))}
        rowKey="id"
        pagination={space.pagination}
        onChange={pagination => onQueryList(pagination)}
        onRow={record => {
          return {
            onClick: () => {
              setCurrentItem(record);
              UnityAction.sendMsg('SelectSpaceFromWeb', record.id);
            },
          };
        }}
        rowClassName={record => (record == currentItem ? 'table-row-active' : null)}
      />
      {!group_id && (
        <Upload {...uploadProps}>
          <Button type="primary">导入空间信息</Button>
        </Upload>
      )}
      <SearchModal
        config={config}
        visible={searchVisible}
        onCancel={() => onCancel()}
        onOk={onOk}
      />
      <EditModal
        groupId={group_id}
        config={config}
        currentItem={currentItem}
        loading={loading}
        visible={editVisible}
        onCancel={onCancel}
        onOk={onEditOk}
        uploadProps={editUploadProps}
      />
    </div>
  );
}

export default connect(({ limitedSpace, user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.limitedSpace,
  config: limitedSpace.config,
  space: limitedSpace.space,
  pagination: limitedSpace.space.pagination,
  areaList: limitedSpace.areaList,
}))(Form.create()(List));
