import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import ScrollLoading from '@/components/ScrollLoading';
import { getVarValues } from '@/services/DeviceInfo';
import { useNavigate, useParams, useRequest } from '@umijs/max';
import { Button, DatePicker, Select, Table } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

const OperationRecord = (props) => {
  const { projectId } = useParams();
  const navigate = useNavigate();

  const convertObject2FormData = (params) => {
    const formData = new FormData();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== null && value !== undefined && value !== NaN) {
        formData.append(key, value);
      }
    });
    return formData;
  };

  const defaultParams = {
    project_id: Number(projectId),
    s_time: '',
    e_time: '',
    cause_type: '',
    currentPage: 1,
    pageSize: 20,
  };
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({});
  const [queryParams, setQueryParams] = useState(defaultParams);

  const [formData, setFormData] = useState(
    convertObject2FormData(defaultParams),
  );

  const { run: getList, loading } = useRequest(
    (params = formData) => getVarValues(params),
    {
      onSuccess: (res) => {
        if (res.pagination?.current == 1) {
          setData(res?.list);
        } else {
          setData([...data, ...res?.list]);
        }
        setPagination(res.pagination);
      },
    },
  );

  const columns = [
    {
      title: '操作时间',
      dataIndex: 'c_time',
      key: 'c_time',
      align: 'center',
      render: (value) => {
        return <div>{dayjs(value).format('YYYY-MM-DD HH:mm')}</div>;
      },
    },
    {
      title: '来源',
      dataIndex: 'cause_type',
      key: 'cause_type',
      render: (text) => {
        if (Number(text) === 0) {
          return '自主操作';
        }
        return '工况建议';
      },
    },
    {
      title: '点位名称',
      dataIndex: 'item_alias',
      key: 'item_alias',
      align: 'center',
      render: (text) => {
        if (!text) {
          return '--';
        }
        return text;
      },
    },
    {
      title: '设备名称',
      dataIndex: 'device_name',
      key: 'device_name',
      align: 'center',
      render: (text) => {
        if (!text) {
          return '--';
        }
        return text;
      },
    },

    {
      title: '操作前数值',
      dataIndex: 'old_value',
      key: 'old_value',
      align: 'center',
      render: (text) => {
        if (!text) {
          return '--';
        }
        return text;
      },
    },

    {
      title: '操作后数值',
      dataIndex: 'new_value',
      key: 'new_value',
      align: 'center',
      render: (text) => {
        if (!text) {
          return '--';
        }
        return text;
      },
    },
    {
      title: '操作人',
      dataIndex: 'operator_name',
      key: 'operator_name',
      align: 'center',
      render: (text) => {
        if (!text) {
          return '--';
        }
        return text;
      },
    },
  ];

  const handleParamsChange = (key, value) => {
    const tempParams = {
      project_id: Number(projectId),
      s_time: queryParams.s_time || '',
      e_time: queryParams.e_time || '',
      cause_type: queryParams.cause_type || '',
      currentPage: 1,
      pageSize: queryParams.pageSize || 20,
    };
    switch (key) {
      case 'cause_type':
        tempParams[key] = value;
        break;
      case 'date':
        tempParams.currentPage = 1;
        if (value?.length === 2) {
          tempParams.s_time = dayjs(value[0]).format('YYYY-MM-DD 00:00:00');
          tempParams.e_time = dayjs(value[1]).format('YYYY-MM-DD 23:59:59');
        } else {
          tempParams.s_time = '';
          tempParams.e_time = '';
        }
        break;
      case 'page':
        tempParams.currentPage = value;
        handleSearch(convertObject2FormData(tempParams));
      default:
        break;
    }
    setQueryParams(tempParams);
  };

  const handleSearch = (params) => {
    if (params !== undefined) {
      getList(params);
      return;
    }
    getList(formData);
  };

  useEffect(() => {
    const tempFormData = convertObject2FormData(queryParams);
    // page变更自动请求接口
    setFormData(tempFormData);
  }, [queryParams]);

  return (
    <PageContent>
      <PageTitle returnable>操作记录</PageTitle>

      <div className={styles.searchContent}>
        {/* <Button
            className={styles.marginRight}
            type="primary"
            onClick={() => navigate(-1)}
          >
            返回
          </Button> */}
        日期：
        <RangePicker
          inputReadOnly
          className={[styles.timePicker, styles.marginRight].join(' ')}
          onChange={(value) => handleParamsChange('date', value)}
        />
        <span style={{ marginLeft: '20px' }}>来源:</span>
        <Select
          placeholder="请选择来源"
          style={{ width: 250 }}
          onChange={(value) => handleParamsChange('cause_type', value)}
          allowClear
        >
          <Option value="0">自主操作</Option>
          <Option value="1">工况建议</Option>
        </Select>
        <Button
          className={styles.marginLeft}
          type="primary"
          onClick={() => handleSearch()}
        >
          查询
        </Button>
      </div>
      <ScrollLoading
        height={182}
        loading={loading}
        pagination={pagination}
        handleLoadData={(current) => handleParamsChange('page', current)}
      >
        <Table dataSource={data || []} columns={columns} pagination={false} />
      </ScrollLoading>
    </PageContent>
  );
};
export default OperationRecord;
