import React, { useEffect, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Avatar,
  Badge,
  Button,
  Card,
  Divider,
  Dropdown,
  Icon,
  List,
  Menu,
  message,
  Popconfirm,
  Spin,
  Tooltip,
  Upload,
} from 'antd';
import { connect } from 'dva';
import { ConnectState, Dispatch } from '@/models/connect';
import { router } from 'umi';
import encodeQueryParam from '@/utils/encodeParam';
import cardStyles from './index.less';
import productImg from '@/pages/device/product/img/product.png';
import Save from './save';
import { downloadObject } from '@/utils/utils';
import SearchForm from '@/components/SearchForm';
import apis from '@/services';
import numeral from 'numeral';
import AutoHide from '@/pages/device/location/info/autoHide';
import { getAccessToken } from '@/utils/authority';

interface Props {
  dispatch: Dispatch;
  metadataCommon: any;
  location: Location;
  loading: boolean;
}

interface State {
  data: any;
  searchParam: any;
  saveVisible: boolean;
}

const DeviceModel: React.FC<Props> = props => {
  const { result } = props.metadataCommon;
  const { dispatch, location } = props;

  const initState: State = {
    data: result,
    searchParam: {
      pageSize: 8,
      terms: location?.query.iop && JSON.parse(location?.query.iop)?.terms,
      sorts: { field: 'id', order: 'desc' },
    },
    saveVisible: false,
  };

  // 消息协议
  const [categoryList, setCategoryList] = useState([]);
  const [searchParam, setSearchParam] = useState(initState.searchParam);
  const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
  const [spinning, setSpinning] = useState(true);
  const [basicInfo, setBasicInfo] = useState<any>();

  const handleSearch = (params?: any) => {
    setSearchParam(params);
    dispatch({
      type: 'metadataCommon/query',
      payload: encodeQueryParam(params),
    });
  };

  const handleDelete = (params: any) => {
    dispatch({
      type: 'metadataCommon/remove',
      payload: params.id,
      callback: response => {
        if (response.status === 200) {
          message.success('删除成功');
          handleSearch(searchParam);
        }
      },
    });
  };

  useEffect(() => {
    apis.deviceProdcutCommon
      .deviceCategory({ paging: false })
      .then((response: any) => {
        if (response.status === 200) {
          setCategoryList(
            response.result.map((item: any) => ({
              id: item.id,
              pId: item.parentId,
              value: item.id,
              title: item.name,
            })),
          );
        }
      })
      .catch(() => { });

    handleSearch(searchParam);
  }, []);

  useEffect(() => {
    setSpinning(false);
  }, [result]);

  const handleSave = (record: any) => {
    dispatch({
      type: 'metadataCommon/insert',
      payload: record,
      callback: response => {
        if (response.status === 200) {
          setSaveVisible(false);
          message.success('保存成功');
          router.push(`/device/metadata/save/${record.id}`);
        }
      },
    });
  };

  const onChange = (page: number, pageSize: number) => {
    handleSearch({
      pageIndex: page - 1,
      pageSize,
      terms: searchParam.terms,
      sorts: searchParam.sorts,
    });
  };

  const onShowSizeChange = (current: number, size: number) => {
    handleSearch({
      pageIndex: current - 1,
      pageSize: size,
      terms: searchParam.terms,
      sorts: searchParam.sorts,
    });
  };

  const uploadProps = (item: any) => {
    dispatch({
      type: 'metadataCommon/insert',
      payload: item,
      callback: (response: any) => {
        if (response.status === 200) {
          message.success('导入成功');
          handleSearch(searchParam);
        }
      },
    });
  };
  /*  const uploadProps: UploadProps = {
    accept: '.json',
    action: '/jetlinks/file/static',
    headers: {
      'X-Access-Token': getAccessToken(),
    },
    showUploadList: false,
    onChange(info) {
      if (info.file.status === 'done') {
        const fileUrl = info.file.response.result;
        request(fileUrl, {method: 'GET'}).then(e => {
          if (e || e !== null) {
            dispatch({
              type: 'metadataCommon/insert',
              payload: e,
              callback: (response: any) => {
                if (response.status === 200) {
                  message.success('导入成功');
                  handleSearch(searchParam);
                }
              },
            });
          }
        }).catch(() => {
          message.error('导入配置失败');
        });
      }
    },
  };*/

  const cardInfoTitle = {
    fontSize: 14,
    color: 'rgba(0, 0, 0, 0.85)',
  };

  return (
    <PageHeaderWrapper title="产品管理">
      <Spin spinning={spinning}>
        <Card bordered={false}>
          <div>
            <div>
              <SearchForm
                search={(params: any) => {
                  handleSearch({
                    terms: { ...params },
                    pageSize: 8,
                    sorts: searchParam.sorts,
                  });
                }}
                formItems={[
                  {
                    label: '物模型名称',
                    key: 'name$LIKE',
                    type: 'string',
                  },
                  {
                    label: '所属品类',
                    key: 'classifiedId$LIKE',
                    type: 'treeSelect',
                    props: {
                      data: categoryList,
                      dropdownStyle: { maxHeight: 500 },
                      showSearch: true
                    },
                  }
                ]}
              />
            </div>
            <div>
              <Button
                icon="plus"
                type="primary"
                onClick={() => {
                  router.push('/device/metadata/add');
                }}
              >
                新建
              </Button>
            </div>
          </div>
        </Card>
        <br />
        <div className={cardStyles.filterCardList}>
          {result.data && (
            <List<any>
              rowKey="id"
              loading={props.loading}
              grid={{ gutter: 24, xl: 4, lg: 3, md: 3, sm: 2, xs: 1 }}
              dataSource={(result || {}).data}
              pagination={{
                current: result?.pageIndex + 1,
                total: result?.total,
                pageSize: result?.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                hideOnSinglePage: true,
                pageSizeOptions: ['8', '16', '40', '80'],
                style: { marginTop: -20 },
                showTotal: (total: number) =>
                  `共 ${total} 条记录 第  ${result.pageIndex + 1}/${Math.ceil(
                    result.total / result.pageSize,
                  )}页`,
                onChange,
                onShowSizeChange,
              }}
              renderItem={item => {
                if (item && item.id) {
                  return (
                    <List.Item key={item.id}>
                      <Card
                        hoverable
                        bodyStyle={{ paddingBottom: 20 }}
                        actions={[
                          <Tooltip key="seeProduct" title="查看">
                            <Icon
                              type="eye"
                              onClick={() => {
                                router.push(`/device/metadata/save/${item.id}`);
                              }}
                            />
                          </Tooltip>,
                          <Tooltip key="update" title="编辑">
                            <Icon
                              type="edit"
                              onClick={() => {
                                setBasicInfo(item);
                                setSaveVisible(true);
                              }}
                            />
                          </Tooltip>,
                          <Tooltip key="delete" title="删除">
                            <Popconfirm
                              placement="topRight"
                              title="确定删除此组件吗？"
                              onConfirm={() => {
                                handleDelete(item);
                              }}
                            >
                              <Icon
                                type="delete"

                              />
                            </Popconfirm>

                          </Tooltip>,
                        ]}
                      >
                        <Card.Meta
                          avatar={<Avatar size={40} src={item.photoUrl || productImg} />}
                          title={
                            <AutoHide title={item.name} style={{ width: '95%', fontWeight: 600 }} />
                          }
                          description={<AutoHide title={item.id} style={{ width: '95%' }} />}
                        />
                        {/* <div className={cardStyles.cardItemContent}>
                          <div className={cardStyles.cardInfo}>
                            <div style={{ width: '100%' }}>
                              <p style={cardInfoTitle}>所属品类</p>
                              <AutoHide
                                title={item.deviceType?.text}
                                style={{ fontSize: 14, fontWeight: 600, width: '95%' }}
                              />
                              <p style={{ fontSize: 14, fontWeight: 600 }}>{item.deviceType?.text}</p>
                            </div>
                          </div>
                        </div> */}
                      </Card>
                    </List.Item>
                  );
                }
                return '';
              }}
            />
          )}
        </div>
      </Spin>
      {saveVisible && (
        <Save
          data={basicInfo}
          close={() => {
            setBasicInfo({});
            setSaveVisible(false);
          }}
          save={item => handleSave(item)}
        />
      )}
    </PageHeaderWrapper>
  );
};
export default connect(({ metadataCommon, loading }: ConnectState) => ({
  metadataCommon,
  loading: loading.models.metadataCommon,
}))(DeviceModel);
