/*
 * @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, Radio } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import React, { useEffect, useState, useContext } from 'react';
import './index.less';

const { RangePicker } = DatePicker;

const dateList = [
  {
    key: 'roundClock',
    name: '近24小时',
  },
  {
    key: 'thisWeek',
    name: '本周',
  },
  {
    key: 'thisMonth',
    name: '本月',
  },
  {
    key: 'thisQuarter',
    name: '本季度',
  },
  {
    key: 'thisYear',
    name: '今年',
  },
  {
    key: 'customer',
    name: '自定义',
  },
];

const startFormat = 'YYYY-MM-DD 00:00:00';
const endFormat = 'YYYY-MM-DD HH:mm:ss';

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(24, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    moment().format('YYYY-MM-DD HH:mm:ss'),
  ]);
  const [dateValue, setDateValue] = useState('roundClock');
  const [userName, setUserName] = useState('');
  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,
      render: (record) => (record ? moment(record).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    {
      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: '等待时间(ms)',
      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 userChange = (e) => {
    setUserName(e.target.value);
  };

  const userEnter = (e) => {
    setParams({
      ...params,
      pageIndex: 1,
      dateFrom: time[0],
      dateTo: time[1],
      userName: e.target.value,
    });
  };

  const timeChange = (dates) => {
    onDateChange('customer', dates);
  };

  const onRadioChange = (e) => {
    onDateChange(e.target.value);
  };

  const onDateChange = (key, data = []) => {
    let start = '',
      end = '';
    switch (key) {
      case 'roundClock':
        start = moment().subtract(24, 'hour').format('YYYY-MM-DD HH:mm:ss');
        end = moment().format('YYYY-MM-DD HH:mm:ss');
        break;
      case 'thisWeek':
        start = moment().startOf('week').format(startFormat);
        end = moment().endOf('week').format(endFormat);
        break;
      case 'thisMonth':
        start = moment().startOf('month').format(startFormat);
        end = moment().endOf('month').format(endFormat);
        break;
      case 'thisQuarter':
        start = moment().startOf('quarter').format(startFormat);
        end = moment().endOf('quarter').format(endFormat);
        break;
      case 'thisYear':
        start = moment().startOf('year').format(startFormat);
        end = moment().endOf('year').format(endFormat);
        break;
      case 'customer':
        if (data && data.length > 0) {
          start = moment(data[0]).format(startFormat);
          end = moment(data[1]).format(endFormat);
        } else {
          return setDateValue(key);
        }
        break;
    }
    setDateValue(key);
    setTime([start, end]);
    if (data && data.length > 0) return false;
    setParams({
      ...params,
      pageIndex: 1,
      dateFrom: start,
      dateTo: end,
      userName: userName,
    });
  };

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

  const operateBtn = () => {
    const _params = {
      pageIndex: 1,
      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')}>
          <Radio.Group value={dateValue} onChange={onRadioChange}>
            {dateList.map((item) => (
              <Radio.Button key={item.key} value={item.key}>
                {item.name}
              </Radio.Button>
            ))}
          </Radio.Group>
          {
            <RangePicker
              showTime
              allowClear={false}
              value={[moment(time[0], dateFormat), moment(time[1], dateFormat)]}
              onChange={timeChange}
              disabled={dateValue !== 'customer'}
              style={{ marginLeft: '10px' }}
            />
          }
          <span className={classNames('operateName')}>操作人：</span>
          <Input
            placeholder="请输入操作人"
            allowClear
            onChange={userChange}
            onPressEnter={userEnter}
            style={{ width: 150 }}
          />
          <Button type="primary" className={classNames('operateName')} onClick={operateBtn}>
            确定
          </Button>
        </div>
        <div className={classNames('recordsHeaderInfo')}>{`设备编码：${bindList?.code || ''}`}</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;
