import React, { useState, useEffect } from 'react';
import { history, useRequest, useAccess, Access } from 'umi'
import classname from "classnames";
import QRCode from "qrcode.react";
import { Button, Modal, message } from "antd";
import { DownloadOutlined, EnvironmentOutlined, PrinterOutlined } from "@ant-design/icons";
import Description from "@/components/Customized/Description";
import { fetchDeviceUpdate } from '@/services/device'
import style from "./style.less";
import moment from "moment";
import useDownLoad from "@/useHooks/useDownLoad";

const isBigScreenScale = window.innerWidth / 1600 > 1;
const { confirm } = Modal

type InfoTabProps = {
  type: 'account' | 'meter';
  deviceInfo: API.Store;
  update?: () => void
}

const InfoTab: React.FC<InfoTabProps> = (props) => {
  const { deviceInfo, type = 'account', update } = props;
  const access = useAccess();
  const [isFrameReady, setIsFrameReady] = useState(false);
  const [isBarFrameReady, setIsBarFrameReady] = useState(false);

  const deviceAction = useRequest(fetchDeviceUpdate, {
    manual: true,
    onSuccess: () => {
      message.success('修改成功', 1)
      update?.()
    }
  });

  const deviceUpdate = (takeEffectIs: boolean) => {
    confirm({
      centered: true,
      title: `${takeEffectIs ? '停用' : '启用'}提示`,
      icon: null,
      content: `是否${takeEffectIs ? '停用' : '启用'}此设备`,
      onOk() {
        deviceAction.run({ statusCode: 'deactivate', deviceId: deviceInfo.id, takeEffectIs })
      }
    })
  }

  const mapJump = () => {
    if (deviceInfo?.longitude && deviceInfo?.latitude) {
      history.push(`/home/map?longitude=${deviceInfo.longitude}&latitude=${deviceInfo.latitude}`)
    }
  }

  const data = [
    { label: '设备名称', name: 'name' },
    { label: '设备编号', name: 'code' },
    { label: '财产编码', name: 'belongingsCode' },
    { label: '唯一标识码', name: 'uniqueCode' },

    { label: '类型', name: 'typeName' },
    { show: deviceInfo.type === 'camera', label: '通道号', name: 'channelNumber' },
    { show: deviceInfo.type === 'camera', label: '设备序列号', name: 'deviceSerial' },

    {
      show: type === 'meter', label: '上级支路', name: 'superMeter',
      render: (val: any) => val?.name || ''
    },
    { show: type === 'meter', label: '采集来源', name: 'collectionSourceName' },


    {
      label: '所属系统', name: 'systemNode',
      render: (val: any) => val?.fullName || ''
    },
    {
      label: '所属能源站', name: 'energyStation',
      render: (val: any) => val?.name || ''
    },


    { label: '型号规格', name: 'modelSpecification' },
    { label: '单位', name: 'unitName' },

    {
      label: '负责人', name: 'principal',
      render: (val: any) => val?.name || ''
    },
    {
      label: '所属部门', name: 'organization',
      render: (val: any) => val?.name || ''
    },
    {
      label: '在用客户', name: 'activeCustomers',
      render: (val: any) => val?.name || ''
    },
    { label: '供应商', name: 'supplierName' },

    { label: '品牌', name: 'brandName' },
    {
      label: '购置日期', name: 'purchaseDate',
      render: (val: any) => val && moment(val).format("YYYY-MM-DD")
    },
    { label: '购置金额(元)', name: 'purchaseAmount' },
    {
      label: '保修期', name: 'warrantyDate',
      render: (val: any) => val && moment(val).format("YYYY-MM-DD")
    },

    {
      label: '投产日期', name: 'productionDate',
      render: (val: any) => val && moment(val).format("YYYY-MM-DD")
    },
    {
      label: '预计报废日期', name: 'expectedScrapDate',
      render: (val: any) => val && moment(val).format("YYYY-MM-DD")
    },
    {
      label: '所属区域', name: 'area',
      render: (val: any) => val?.name || ''
    },
    { label: '所属建筑', name: 'buildingName' },

    { label: '安装位置', name: 'installationLocationName' },
    {
      label: '设备坐标', auto:
        <a onClick={mapJump}>
          {deviceInfo?.longitude && deviceInfo?.latitude && <EnvironmentOutlined style={{ marginRight: 5 }} />}
          {deviceInfo?.longitude && deviceInfo?.latitude && `( ${deviceInfo.longitude}, ${deviceInfo.latitude} )`}
        </a>
    },
  ];

  const downloadQrCode = () => {
    const canvas: HTMLCanvasElement | null = document.getElementById("qrCode") as HTMLCanvasElement;
    if (!canvas) return;
    const pngUrl = canvas
      ?.toDataURL("image/png")
      ?.replace("image/png", "image/octet-stream");
    const downloadLink = document.createElement("a");
    downloadLink.href = pngUrl;
    downloadLink.download = "qrCode.png";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  };

  const printQrcode = () => {
    // window.print();
    const oPrintFrame = document.getElementById('printFrame') as HTMLIFrameElement;
    oPrintFrame?.contentWindow?.print();
  };

  const printBarQrcode = () => {
    const oPrintFrame = document.getElementById('printBarFrame') as HTMLIFrameElement;
    oPrintFrame?.contentWindow?.print();
  }

  useEffect(() => {
    const oPrintFrame = document.getElementById('printFrame');
    const oPrintBarFrame = document.getElementById('printBarFrame');
    oPrintFrame?.addEventListener("load", function () {
      setIsFrameReady(true);
    });
    oPrintBarFrame?.addEventListener("load", function () {
      setIsBarFrameReady(true);
    });
  }, []);

  useEffect(() => {
    const oPrintFrame = document.getElementById('printFrame') as HTMLIFrameElement;
    setTimeout(() => {
      oPrintFrame?.contentWindow?.postMessage?.(JSON.stringify([deviceInfo]), '*');
    }, 1000);
  }, [deviceInfo, isFrameReady]);

  //打印条形码

  useEffect(() => {
    const oPrintBarFrame = document.getElementById('printBarFrame') as HTMLIFrameElement;
    isBarFrameReady && setTimeout(() => {
      oPrintBarFrame?.contentWindow?.postMessage?.(JSON.stringify([deviceInfo]), '*');
    }, 1000);
  }, [deviceInfo, isBarFrameReady]);

  const recordDownload = useDownLoad(
    { url: '/operation-service/m-task/exportEquipmentResume', method: 'POST' },
    { name: `${deviceInfo?.name}履历表`, downloadType: 'xlsx' },
  )

  return (
    <div>
      <Description
        columns={isBigScreenScale ? 4 : 3}
        dataSource={deviceInfo}
        data={data}
      />
      <iframe src='/print/index.html' width='100%' height='100%' frameBorder={0} id='printFrame' style={{ display: 'none' }} />
      <iframe src='/print/printBar.html' width='100%' height='100%' frameBorder={0} id='printBarFrame' style={{ display: 'none' }} />
      {/* <div className={ style.printTable }> */}
      {/*   <table width="100%" className={style.tableInfo}> */}
      {/*     <thead> */}
      {/*     <tr> */}
      {/*       <th colSpan = {3} >设备标签卡</th> */}
      {/*     </tr> */}
      {/*     </thead> */}
      {/*     <tbody> */}
      {/*     <tr> */}
      {/*       <th>设备编号</th> */}
      {/*       <td colSpan={2}>{deviceInfo?.code}</td> */}
      {/*     </tr> */}
      {/*     <tr> */}
      {/*       <th>设备名称</th> */}
      {/*       <td colSpan={2}>{deviceInfo?.name}</td> */}
      {/*     </tr> */}
      {/*     <tr> */}
      {/*       <th>规格型号</th> */}
      {/*       <td valign="top">{deviceInfo?.modelSpecification}</td> */}
      {/*       <td rowSpan={3} valign="top" className={style.noPad}> */}
      {/*         <QRCode id="qrCode2" size={100} value={deviceInfo?.uniqueCode || ''} /> */}
      {/*       </td> */}
      {/*     </tr> */}
      {/*     <tr> */}
      {/*       <th>管制编号</th> */}
      {/*       <td valign="top">22</td> */}
      {/*     </tr> */}
      {/*     <tr> */}
      {/*       <th>管理单位</th> */}
      {/*       <td valign="top"> */}
      {/*         {deviceInfo?.principal?.department?.name} */}
      {/*       </td> */}
      {/*     </tr> */}
      {/*     </tbody> */}
      {/*   </table> */}
      {/* </div> */}

      <div className={classname("pos_btw")} style={{ padding: 10 }}>
        <div>
          <div className={classname("pos_btw", style.qr_box)}>
            <QRCode id="qrCode" size={51} value={deviceInfo?.uniqueCode || ''} />
            <a onClick={downloadQrCode} style={{ marginLeft: 10 }}><DownloadOutlined /> 下载</a>
            <a onClick={printQrcode} style={{ marginLeft: 10 }}><PrinterOutlined /> 打印设备标签卡</a>
            <a onClick={printBarQrcode} style={{ marginLeft: 10 }}><PrinterOutlined /> 打印设备条形码</a>
          </div>
          <p className={style.qr_code}>唯一识别码:{deviceInfo?.uniqueCode || ''}</p>
        </div>
        <div>
          <Access accessible={access.insideAccess('npIvqshvYic')}>
            <Button
              type="primary"
              className={style.btn_r_20}
              onClick={() => history.push(`/ops/maintenance/order/add?type=1&equipmentId=${deviceInfo.id}`)}
            >报 修</Button>
          </Access>
          <Access accessible={access.insideAccess('xWuWZqPMPJK')}>
            <Button
              type="primary"
              className={style.btn_r_20}
              onClick={() => history.push(`/ops/equipDisposition/equipTransfer/add?equipmentId=${deviceInfo.id}`)}
            >转 移</Button>
          </Access>
          <Access accessible={access.insideAccess('AdAeoBOtnMY')}>
            <Button
              type="primary"
              className={style.btn_r_20}
              onClick={() => history.push(`/ops/equipDisposition/equipScrapped/add?equipmentId=${deviceInfo.id}`)}
            >报 废</Button>
          </Access>
          <Access accessible={access.insideAccess('KerJNFcaEjp')}>
            <Button
              type="primary"
              className={style.btn_r_20}
              onClick={() => deviceUpdate(deviceInfo?.highestPriorityStatusCode !== 'deactivate')}
            >{deviceInfo?.highestPriorityStatusCode !== 'deactivate' ? '停 用' : '启 用'}</Button>
          </Access>
          <Access accessible={access.insideAccess('bwUGDSNQXdZ')}>
            <Button
              type="primary"
              className={style.btn_r_20}
              onClick={() => recordDownload.run({ deviceId: deviceInfo.id })}
            >导出履历表</Button>
          </Access>
        </div>
      </div>
    </div>
  );
};

export default InfoTab;