import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';
import { UploadOutlined } from '@ant-design/icons';
import { getToken, setAuthority } from '@/utils/auth';
import { Button, Space, Popconfirm, Tag, Image, Select, Upload, message } from 'antd';
import {
  PageContainer,
  ProTable,
  ProFormSelect,
} from '@ant-design/pro-components';

import AuthConsumer from '@/components/Authority';
import SetinfoFormModal from './components/SetinfoFormModal';

import Reportkw from '../../components/Reportkw';

import services from '@/services/admin';

import dayjs from 'dayjs';

const { deviceItems, deviceSetinfo, deviceCreate } = services.DeviceController;
const { shopItems } = services.ShopController;

export default () => {

  const [setinfoFormModal, setSetinfoFormModal] = useState(false);

  const [reportkwModal, setReportkwModal] = useState(false);

  const [selectedRows, setSelectedRows] = useState(false);

  const actionRef = useRef();

  const initRow = {
    id: '',
    shop_id: '',
    store_id: '',
    num: 1,
  };

  const [row, setRow] = useState(initRow);
  const [shopOption, setShopOption] = useState([]);


  const handleSetinfo = async (value) => {
    const { success } = await deviceSetinfo(value);
    if (success) {
      setSetinfoFormModal(false);
      actionRef.current?.reload();
    }
  };

  const searchShop = (value) => {
    shopItems({
      username: value
    }).then(({ data }) => {
      const arr = [];
      data?.data?.map((item) => {
        item.label = `${item.username}   ${item.mobile}`;
        arr.push(item);
      });
      setShopOption(arr);
    });
  }

  const props = {
    name: 'file',
    action: process.env.API_URL + '/admin/device/import1',
    headers: {
      Authorization: `Bearer ` + getToken(),
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 导入成功`);
        actionRef.current?.reload();
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };


  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      search: true,
      render: (_, record) => {
        const time = [];
        return <div>{record?.id}</div>
        // return <>
        //   <Button
        //     type="link"
        //     onClick={() => {
        //       setRow({ device_id: record.device_id });
        //       setReportkwModal(true);
        //     }}
        //   >{record?.id}</Button>
        // </>;
      },
    },
    {
      title: '安装时间',
      dataIndex: 'install_time',
      search: true,
      render: (_, record) => {
        return record?.install_time ? dayjs(record?.install_time * 1000).format('YYYY-MM-DD HH:mm:ss') : '未安装'
      }
    },
    // {
    //   title: '补贴天数',
    //   dataIndex: 'help_day',
    //   search: true,
    // },
    {
      title: '同步时间',
      dataIndex: 'sync_time',
      search: false,
      render: (_, record) => {
        return record?.sync_time ? dayjs(record?.sync_time * 1000).format('YYYY-MM-DD HH:mm:ss') : ''
      }
    },
    {
      title: '桩主',
      dataIndex: 'shop_id',
      search: true,
      render: (_, record) => {
        return <>
          <div><Image
            preview={false}
            width={50}
            src={record?.shop?.avatar_url}
          /></div>
          <div>{record?.shop?.username}</div>
          <div>{record?.shop?.mobile}</div>
        </>;
      },
      renderFormItem: (
        _,
        { type, defaultRender, formItemProps, fieldProps, ...rest },
        form,
      ) => {
        return <Select
          {...fieldProps}
          allowClear
          showSearch
          placeholder="请输入用户名"
          style={{ width: "100%" }}
          filterOption={false}
          onSearch={
            (e) => {
              if (!e) {
                return;
              }
              searchShop(e);
            }
          }
          fieldNames={{
            label: "label",
            value: "id"
          }}
          options={shopOption}
        />
      },
    },
    {
      title: '设备信息',
      dataIndex: 'site_name',
      search: true,
      render: (_, record) => {
        return <>
          <div>设备号：{record?.device_no}</div>
          <div>小区：{record?.site_name}</div>
          <div>地址：{record?.address}</div>
        </>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          {
            <AuthConsumer action={'admin/device/setinfo'} key="admin/device/setinfo">
              <Button
                type="link"
                onClick={() => {
                  setRow(record);
                  setSetinfoFormModal(true);
                }}
              >
                设置地址
              </Button>
            </AuthConsumer>
          }

        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <Reportkw
          values={row}
          type={0}
          modalOpenState={reportkwModal}
          onModalOpenState={setReportkwModal}
        />
        <SetinfoFormModal
          values={row}
          modalOpenState={setinfoFormModal}
          onModalOpenState={setSetinfoFormModal}
          onSubmit={handleSetinfo}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            defaultCollapsed: false,
          }}
          // headerTitle={
          //   <AuthConsumer action={'admin/device/create'} key="admin/device/create">
          //     <Button
          //       type="primary"
          //       onClick={() => {
          //         setCreateFormModal(true);
          //       }}
          //     >
          //       批量生成
          //     </Button>
          //   </AuthConsumer>
          // }
          toolBarRender={() => [
            <AuthConsumer action={'admin/device/import1'} key="admin/device/import1">
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>导入数据</Button>
              </Upload>
            </AuthConsumer>,
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await deviceItems({
              ...params,
              sorter,
              filter,
            });
            //setDeviceRedis(data.redis);
            return {
              data: data?.items?.data || [],
              total: data?.items?.total,
              success,
            };
          }}
          columns={columns}
          rowSelection={{
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRowKeys)
            },
          }}
          tableAlertRender={({
            selectedRowKeys,
            selectedRows,
            onCleanSelected,
          }) => {
            return (
              <Space size={24}>
                <span>已选 {selectedRowKeys.length} 项</span>
                <span>
                  <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            );
          }}
          tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
            return (
              <Space size={16}>

              </Space>
            );
          }}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </>
    </PageContainer>
  );
};
