import PageContent from '@/components/PageContent';
import TabsContent from '@/components/TabsContent';
import { queryMainChartList } from '@/services/StorageManagement';
import {
  queryDeviceList,
  queryMaintainRecord,
  queryRepairRecord,
} from '@/services/device';
import { UnityAction } from '@/utils/utils';
import { RightOutlined } from '@ant-design/icons';
import { useNavigate, useParams, useRequest } from '@umijs/max';
import { Collapse, List, Space, Spin, Table } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import styles from './index.less';

const deviceIcon = require('@/assets/deviceManager/deviceIcon.png');
const spareIcon = require('@/assets/deviceManager/spareIcon.png');
// const chartIcon = require('@/assets/deviceManager/chartIcon.png');

export const PageType = {
  in: 0, //入库管理
  out: 1, //出库管理
  scrap: 2, //报废处置
  warning: 3, //报警数量
  base: 4, //基础库存
};

const DeviceManager = () => {
  const { projectId } = useParams();
  const [defaultActiveKey, setDefaultActiveKey] = useState(
    localStorage.deviceTab || '1',
  );

  useEffect(() => {
    // 重置默认显示tab
    localStorage.deviceTab = '1';
  }, []);
  return (
    <PageContent tabs>
      <TabsContent
        defaultActiveKey={defaultActiveKey}
        onChange={setDefaultActiveKey}
        items={[
          {
            label: `设备管理`,
            key: '1',
            children: <Device projectId={projectId} />,
          },
          {
            label: `备品管理`,
            key: '2',
            children: <SparePart projectId={projectId} />,
          },
        ]}
      />
    </PageContent>
  );
};
const Device = ({ projectId }) => {
  const [type, setType] = useState(0); //0 全部  1维修  2保养
  const [activeCode, setActiveCode] = useState();

  const columnsRepair = [
    {
      title: '设备位号',
      dataIndex: 'DeviceCode',
      key: 'DeviceCode',
      align: 'center',
    },
    {
      title: '设备名称',
      dataIndex: 'DeviceName',
      key: 'DeviceName',
      align: 'center',
    },
    {
      title: '维修时间',
      dataIndex: 'RepairTime',
      key: 'RepairTime',
      align: 'center',
      render: (text) => {
        return text ? dayjs(text).format('YYYY-MM-DD HH:mm') : null;
      },
    },
    {
      title: '维修状态',
      dataIndex: 'AcceptanceStatus',
      render: (text) => {
        switch (text) {
          case 0:
            return '维修中';
          case 1:
            return '已提交';
          case 2:
            return '已维修';
          default:
            return '';
        }
      },
    },
  ];

  const columns = [
    {
      title: '设备位号',
      dataIndex: 'DeviceCode',
    },
    {
      title: '设备名称',
      dataIndex: 'DeviceName',
    },
    {
      title: '保养日期',
      dataIndex: 'MaintainTime',
      render: (text) => {
        return text ? dayjs(text).format('YYYY-MM-DD HH:mm') : null;
      },
    },
    {
      title: '保养人',
      dataIndex: 'Operators',
      width: 300,
      render: (text) => {
        let arr = [];
        if (text && text.length > 0) {
          text.map((item) => {
            if (item && item.Operator && item.Operator.CName) {
              arr.push(item.Operator.CName);
            }
          });
        }
        return arr && arr.join(',');
      },
    },
  ];

  //请求 全部设备列表
  const {
    data,
    run: runDevice,
    loading: loadingDevice,
  } = useRequest(queryDeviceList, {
    defaultParams: [projectId],
  });

  const allData = useMemo(() => {
    const total = data?.reduce((total, item) => item.Count, 0);
    const items = data?.map((item, idx) => {
      const itemLen = item?.List?.length;
      return {
        key: `${idx + 1}`,
        label: (
          <div className={styles.lineContent}>
            <span>{item.Type}</span>
            <span>{itemLen}个</span>
          </div>
        ),
        children: (
          <div style={{ position: 'relative' }}>
            <List
              header={null}
              footer={null}
              dataSource={item.List}
              renderItem={(cur) => (
                <List.Item
                  className={`${styles.itemText} ${
                    activeCode == cur.Code ? styles.itemTextActive : ''
                  }`}
                  onClick={() => handleItemClick(cur.Code)}
                >
                  <span style={{ width: '30%', textAlign: 'left' }}>
                    {cur.Code}
                  </span>
                  <span> {cur.Name} </span>
                </List.Item>
              )}
            />
          </div>
        ),
      };
    });
    return { total, items };
  }, [data, activeCode]);

  //请求维修中设备列表queryRepairRecord
  const {
    data: repairData,
    run: runRepair,
    loading: repairLoading,
  } = useRequest(
    () =>
      queryRepairRecord({
        pageSize: 9999,
        recordId: Number(projectId),
      }),
    {
      manual: true,
    },
  );

  //请求保养记录
  const {
    data: maintainData,
    run: runMaintain,
    loading: maintaiLoading,
  } = useRequest(
    () =>
      queryMaintainRecord({
        pageSize: 9999,
        recordId: Number(projectId),
      }),
    {
      manual: true,
    },
  );

  const handleItemClick = (code) => {
    UnityAction.sendMsg('deviceCode', code);
    console.log(code);
    setActiveCode(code);
  };

  const handleBtnClick = (type) => {
    setType(type);
    switch (type) {
      case 0:
        runDevice(projectId);
        break;
      case 1:
        runRepair();
        break;
      case 2:
        runMaintain();
        break;
    }
  };

  return (
    <div className={`content-tab ${styles.sparePart}`}>
      <Spin spinning={loadingDevice}>
        <div className={`card-box ${styles.titleContent}`}>
          <img className={styles.img} src={deviceIcon} />
          <div>
            <div className={styles.num}>{allData?.total}</div>
            <div className={styles.text}>设备总数（个）</div>
          </div>
        </div>
        <Space className={styles.btns} size={28}>
          <div
            className={`${styles.btn} ${type == 0 ? styles.active : ''}`}
            onClick={() => handleBtnClick(0)}
          >
            <span style={{ lineHeight: '60px' }}>全部</span>
          </div>
          <div
            className={`${styles.btn} ${type == 1 ? styles.active : ''}`}
            onClick={() => handleBtnClick(1)}
          >
            <span style={{ lineHeight: '60px' }}>维修</span>
          </div>
          <div
            className={`${styles.btn} ${type == 2 ? styles.active : ''}`}
            onClick={() => handleBtnClick(2)}
          >
            <span style={{ lineHeight: '60px' }}>保养</span>
          </div>
        </Space>
      </Spin>
      {type == 0 && <Collapse bordered={false} items={allData?.items} />}
      {type == 1 && (
        <Table
          loading={repairLoading}
          style={{ marginTop: '10px' }}
          dataSource={repairData?.filter((item) => item.DeviceCode)}
          columns={columnsRepair}
          pagination={false}
        />
      )}
      {type == 2 && (
        <Table
          loading={maintaiLoading}
          style={{ marginTop: '10px' }}
          dataSource={maintainData?.filter((item) => item.DeviceCode)}
          columns={columns}
          pagination={false}
        />
      )}
    </div>
  );
};
const SparePart = ({ projectId }) => {
  const navigate = useNavigate();
  const year = dayjs().format('YYYY');
  const currentMonth = dayjs().format('MM');
  const defaultParams = {
    project_id: Number(projectId),
    month: Number(currentMonth),
    year: Number(year),
  };
  //请求备品列表
  const { data, loading } = useRequest(() => queryMainChartList(defaultParams));

  const changePage = (type) => {
    navigate(`/device/detail/${projectId}/${type}`);
    // 设置默认显示tab为备品管理
    localStorage.deviceTab = '2';
  };

  const handleTotalPage = () => {
    navigate(`/device/storage/${projectId}`);
    // 设置默认显示tab为备品管理
    localStorage.deviceTab = '2';
  };

  const list = useMemo(() => {
    const result = [
      {
        title: '基础库存',
        type: PageType.base,
      },
      {
        title: '入库数量',
        type: PageType.in,
        num: data?.in_amount || 0,
      },
      {
        title: '出库数量',
        type: PageType.out,
        num: data?.out_amount || 0,
      },
      {
        title: '报废数量',
        type: PageType.scrap,
        num: data?.scrap_amount || 0,
      },
      {
        title: '报警数量',
        type: PageType.warning,
        num: data?.warning_stat || 0,
      },
    ];
    return result;
  }, [data]);
  return (
    <Spin spinning={loading}>
      <div className="content-tab">
        <Space direction="vertical" size={16} className={styles.sparePart}>
          <div className={`card-box ${styles.titleContent}`}>
            <img className={styles.img} src={spareIcon} />
            <div>
              <div className={styles.num}>{data?.on_amount || 0}</div>
              <div className={styles.text}>在库数量（个）</div>
            </div>
            <div
              onClick={handleTotalPage}
              className={styles.iconFundFilled}
            ></div>
          </div>
          {list.map((item) => (
            <div
              className={`card-box ${styles.cardItem}`}
              onClick={() => changePage(item.type)}
            >
              <span className={styles.spareText}>{item.title}</span>
              <Space size={30}>
                {/* <span className={styles.spareText}>{item.num}个</span> */}
                <RightOutlined style={{ fontSize: '28px' }} />
              </Space>
            </div>
          ))}
        </Space>
      </div>
    </Spin>
  );
};

export default DeviceManager;
