/*
 * @Author: ljiwen
 * @Date: 2024-12-30 13:50:03
 * @Description:
 * @FilePath: \wisdom-components\packages\extend-components\EC_ConfigurationView\src\components\ControlRecords\index.js
 */
import { getRemoteOperationLog } from '../../apis';
import BasicTable from '@wisdom-components/basictable';
import LoadBox from '@wisdom-components/loadbox';
import { Button, DatePicker, Input, Tag, Tooltip, ConfigProvider } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import React, { useEffect, useState, useContext } from 'react';
import './index.less';

const { RangePicker } = DatePicker;

const ControlRecords = ({ nodeData, bindList }) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('ec-configuration-control-records');
  const dateFormat = 'YYYY-MM-DD HH:mm:ss';
  const [time, setTime] = useState([
    moment().subtract(7, 'day').format('YYYY-MM-DD 00:00:00'),
    moment().format('YYYY-MM-DD HH:mm:ss'),
  ]);
  const [userName, setUserName] = useState('');
  const [deviceCode, setDeviceCode] = useState(bindList?.code);
  const [tableData, setTableData] = useState([]);
  const [tableLoading, setTableLoading] = useState(true);
  const [totalNum, setTotalNum] = useState(0);
  const [params, setParams] = useState({
    pageIndex: 1,
    pageSize: 20,
    controlPoint: nodeData?.ctName,
    deviceType: bindList?.type,
    deviceCode: bindList?.code,
    dateFrom: time[0],
    dateTo: time[1],
    userName: '',
    userTName: '',
  });

  const column = [
    {
      title: '序号',
      dataIndex: 'rowOrder',
      align: 'center',
      width: 60,
      render: (text, row, index) => (params.pageIndex - 1) * params.pageSize + index + 1,
    },
    {
      title: '操作人',
      width: 100,
      dataIndex: 'opreationName',
      align: 'center',
    },
    {
      title: '操作时间',
      dataIndex: 'opreationTime',
      align: 'center',
      width: 100,
      ellipsis: true,
    },
    {
      title: '控制点位',
      dataIndex: 'controlPoint',
      align: 'center',
      width: 140,
      ellipsis: true,
      onCell: () => ({
        style: {
          maxWidth: 140,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: (record) => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '初始状态',
      dataIndex: 'initStatus',
      align: 'center',
      width: 80,
      ellipsis: true,
    },
    {
      title: '目标状态',
      dataIndex: 'targetStatus',
      align: 'center',
      width: 80,
      ellipsis: true,
    },
    {
      title: '实际状态',
      dataIndex: 'realStatus',
      align: 'center',
      width: 80,
      ellipsis: true,
    },
    {
      title: '服务返回信息',
      dataIndex: 'backContent',
      align: 'center',
      width: 200,
      ellipsis: true,
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
        },
      }),
      render: (record) => (
        <Tooltip placement="topLeft" title={record}>
          {record}
        </Tooltip>
      ),
    },
    {
      title: '等待时间',
      dataIndex: 'controlWatiTime',
      width: 80,
      align: 'center',
    },

    {
      title: '控制结果',
      dataIndex: 'controlResult',
      align: 'center',
      width: 80,
      ellipsis: true,
      render: (record) => {
        if (record === '成功') {
          return <Tag color="green">{record}</Tag>;
        }
        return <Tag color="orange">{record}</Tag>;
      },
    },
  ];

  const getControlRecords = () => {
    setTableLoading(true);
    getRemoteOperationLog(params)
      .then((res) => {
        setTableLoading(false);
        const data = res?.data?.list || [];
        const total = res?.data?.totalCount || 0;
        setTableData(data);
        setTotalNum(total);
      })
      .catch((err) => {
        setTableLoading(false);
        setTableData([]);
        setTotalNum(0);
      });
  };

  const timeChange = (dates, dateStrings) => {
    setTime(dateStrings);
  };

  const userChange = (e) => {
    setUserName(e.target.value);
  };

  const pageChange = (pageIndex, pageSize) => {
    // 分页改变
    params.pageIndex = pageIndex;
    params.pageSize = pageSize;
    setParams({ ...params });
  };

  const operateBtn = () => {
    const _params = {
      pageIndex: 1,
      deviceCode: deviceCode,
      dateFrom: time[0],
      dateTo: time[1],
      userName: userName,
    };
    setParams({
      ...params,
      ..._params,
    });
  };

  useEffect(() => {
    getControlRecords();
  }, [params]);

  return (
    <div className={classNames(prefixCls)}>
      <div className={classNames('recordsHeaderWrap')}>
        <div className={classNames('recordsHeader')}>
          <span className={classNames('operateName', 'operateTime')}>设备类型：</span>
          <Input
            placeholder="请输入设备类型"
            readOnly
            value={bindList?.type || ''}
            style={{ width: 150 }}
          />
          <span className={classNames('operateName')}>设备编码：</span>
          <Input
            placeholder="请输入设备编码"
            readOnly
            value={bindList?.code || ''}
            style={{ width: 150 }}
          />
          <span className={classNames('operateName')}>操作时间：</span>
          <RangePicker
            showTime
            allowClear={false}
            value={[moment(time[0], dateFormat), moment(time[1], dateFormat)]}
            onChange={timeChange}
          />
          <span className={classNames('operateName')}>操作人：</span>
          <Input
            placeholder="请输入操作人"
            allowClear
            onChange={userChange}
            style={{ width: 150 }}
          />
          <Button type="primary" className={classNames('operateName')} onClick={operateBtn}>
            确定
          </Button>
        </div>
      </div>
      <div className={classNames('recordscontent')}>
        <BasicTable
          columns={column}
          bordered
          scroll={{ y: 'calc(100% - 40px)' }}
          pagination={{
            total: totalNum,
            onChange: pageChange,
            current: params.pageIndex,
            pageSize: params.pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          dataSource={tableData}
        />
      </div>
      {tableLoading && (
        <div className={classNames('loadBox')}>
          <LoadBox spinning={tableLoading} />
        </div>
      )}
    </div>
  );
};

export default ControlRecords;
