import { PlusOutlined,CopyOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm,Typography } from 'antd';
import React, { useState, useRef, useEffect} from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import PushFrom from './components/PushFrom';
import Field from '@ant-design/pro-field';
import {
    GetDevicePushRecodePage,
    DevicePushRecodeAdd,
    DevicePushRecodeDelete,
    DevicePushRecodeUpdate
} from './services';



const goodspush = () => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const { Paragraph, Text } = Typography;
  /** 国际化修改 */
  useEffect(() => {
   
    
  }, []);

  /**
   * 批量删除
   *
   * @param selectedRows
   */
   
  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    await DevicePushRecodeDelete(selectedRows.map((row) => row.id)).then((r) => {
      if (r.succeeded) {
        message.success('删除成功');
        actionRef.current.reloadAndRest();
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  };
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '下发设备',
      dataIndex: 'deviceName',
      valueType: 'textarea',
      ellipsis: true,
    },

    {
      title: '下发状态',
      dataIndex: 'status',
      ellipsis: true,
      valueEnum: {
        0: {
            text: '成功',
            status: 'Success',
        },
        1: {
          text: '失败',
          status: 'Processing',
      },
      },
    },
    {
      title: '下发时间',
      dataIndex: 'createAt',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setShowDetail(true);
            setCurrentRow(record);
          }}
        >
          下发详情
        </a>,
         <a
         key="config"
         onClick={() => {
           DevicePushRecodeUpdate(record.id).then((r)=>{
             if(r.data){
               message.success('操作成功');
               actionRef.current.reloadAndRest();
             }else{
               message.error('操作失败');
             }
           })
         }}
       >
         重发
         </a>,
        // <Popconfirm
        //   type="primary"
        //   key="primary"
        //   title="确认删除吗？"
        //   okText="是"
        //   cancelText="否"
        //   onConfirm={async () => {
        //     await DeleteGoodsType(record.id).then((r) => {
        //       if (r.succeeded) {
        //         message.success('删除成功');
        //         actionRef.current.reloadAndRest();
        //       } else {
        //         message.error(r.errors);
        //       }
        //     });
        //   }}
        //   onCancel={() => {}}
        // >
        //   <a href="#">删除</a>
        // </Popconfirm>,
      ],
    },
  ];
const HandleOk= async(values)=>{
  await DevicePushRecodeAdd(values).then((res)=>{
    if(res.data){
      message.success('操作成功');
      handleModalVisible(false);
      actionRef.current.reloadAndRest();
    }else{
      message.error(res.errors);
    }
  })
}

  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 下发数据
          </Button>,
        ]}
        request={async (params) => {
          var goodsData = [];
          var total = 0;
          params.type=2
          await GetDevicePushRecodePage(params).then((r) => {
            goodsData = r.data.data;
            total = r.data.total;
          });
          return {
            data: goodsData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <PushFrom
        onFinish={async (value) => {
         
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        HandleOk={HandleOk}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.deviceName && (
          <ProDescriptions
            column={1}
            title="下发详情"
         
          >
              <ProDescriptions.Item label="下发设备" valueType="text">
              {currentRow?.deviceName}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="topic" copyable valueType="text">
          {currentRow?.topic}
          </ProDescriptions.Item>
          <ProDescriptions.Item label="下发状态" valueType="text">
          {currentRow?.description}
          </ProDescriptions.Item>
          <ProDescriptions.Item contentStyle={{ maxWidth: '85%'}} label="下发数据">
          <a
              onClick={() => {
                let oInput = document.createElement('input');
                oInput.value = currentRow.dataResore;
                document.body.appendChild(oInput);
                oInput.select(); // 选择对象
                document.execCommand('Copy'); // 执行浏览器复制命令
                message.success('复制成功');
                oInput.remove();
              }}
            >
              <CopyOutlined />
         
            <div style={{  overflow: 'scroll', overflowX: 'auto' }}>
              <Field text={currentRow?.dataResore} valueType="jsonCode" />
            </div>
            </a>
          </ProDescriptions.Item>
            </ProDescriptions>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default goodspush;
