import react from "react";
import { useState } from "react";
import requests from "../../../utils/requests";
import { doPost } from "../../../utils/requests";
import {
  PlayIcon,
  StopIcon,
  PauseIcon,
  BellIcon,
  ViewListIcon,
} from "@heroicons/react/outline";

import { BellIcon as BellIconS } from "@heroicons/react/solid";
import { PuzzleIcon } from "@heroicons/react/solid";
import VLabel from "../Header/VLabel";
import eqs from "../../../utils/eqs";
import {  Tooltip } from 'antd';
const { eqstatus, orderstatus } = eqs;

function Card({
  eq,
  popHandle,
  alartPopHandle,
  classNamez,
  typecode,
  selectedTab,
  alertData,
}) {
  if (!eq) {
    eq = {};
  }

  const [status, setStatus] = useState(eqstatus[0]);
  const [alertcount, setAlertcount] = useState(0);
  const [fieldValueMap, setFieldValueMap] = react.useState({});
  const [imgUrl, setImgUrl] = react.useState(null);
  // const [fields, setFields] = react.useState([]);

  react.useEffect(() => {
    if (eq.runningstatus === undefined) eq.runningstatus = 0;
    setStatus(eqstatus.filter((item) => item.key === eq.runningstatus)[0]);
    // console.log(eq.code,eq.runningstatus)
  }, [eq.runningstatus]);
  // eq.updatestatus=(statuscur)=>{
  //   setStatus(eqstatus.filter((item) => item.key === statuscur)[0]);
  // }
  react.useEffect(() => {
    //updatefields();
    // if (eq.operationCode === typecode) {
    //   setFields(eq.bmIotEquipmentRelationshipList);
    // }
    async function async1() {
      if (typecode === "1002") {
        let item = eq?.bmIotEquipmentRelationshipList.filter(
          (x) => x.iotField.indexOf("IoStatus") > -1
        );
        if (item && item.length > 0) {
          eq.runningstatus =
            item[0].iotFieldValue || item[0].iotFieldValue === 1 ? 2 : 4;
        }
      }
    }
    async1();
  }, [typecode]);

  react.useEffect(() => {
    if (alertData && alertData.length > 0) {
      eq.alert = alertData.filter((al) => {
        if (al.equipCode === eq.code) {
          return al;
        }
      });
      if(eq.alert.length>0)
      {
        let alertcout = eq?.alert?.filter((aa) => {
          if (!aa?.eliminationTime) {
            return aa;
          }
        });
        eq.alertcount = alertcout.length;
        setAlertcount(alertcout.length);
      }
    }
  }, [alertData, selectedTab]);
  //   react.useEffect(() => {
  //     if(!eq.alertcount){
  //       eq.alertcount=0;
  //       eq.alert= [];
  //     }
  //    else{
  //     setAlertcount(eq.alertcount);
  //    }
  // }, [eq.alertcount, selectedTab]);
    react.useEffect(() => {
  }, [eq.alert]);
  react.useEffect(() => {
    if (eq.Img) {
      setImgUrl(eq.Img);
    }
  }, [eq.Img]);
  react.useEffect(() => {}, [eq.runningstatus]);
  react.useEffect(() => {
    // setTimeout(() => {
    //   setFields(eq.bmIotEquipmentRelationshipList);
    // }, 100);
  }, [eq.bmIotEquipmentRelationshipList]);
  eq.updateFields = () => {
    //  updatefields();
  };

  let updatefields = () => {
    if (!eq?.bmIotEquipmentRelationshipList) {
      if (!eq.code) {
        return;
      }
      doPost(requests.fetchEquipFields.url, [eq.code])
        .then((res) => res.json())
        .then((data) => {
          if (data.success) {
            // var fileGroupIds = curdata.map((zz) => zz.fileGroupId);
            //获取图片信息
            if (data.data.length > 0) {
              var eqcur = data.data[0][0];
              eq.bmIotEquipmentRelationshipList =
                eqcur.bmIotEquipmentRelationshipList;
              updateonlyfields();
            }
          }
        });
    } else {
      updateonlyfields();
    }
  };

  let updateonlyfields = () => {
    //接口请求物联网influxdb查询服务
    doPost(requests.fetchLastFieldsValue.url, {
      equipCode: eq.code,
      fields: eq.bmIotEquipmentRelationshipList
        .filter((re) => {
          if (re.status && !re.iotIsalarm) {
            return re;
          }
        })
        .map((field) => field.iotField),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          if (data.data !== null && data.data !== []) {
            var _fieldValueMap = data.data[0];
            if (!_fieldValueMap) return;
            eq.bmIotEquipmentRelationshipList.map((field) => {
              field.iotFieldValue = !(field.iotField in _fieldValueMap)
                ? null
                : _fieldValueMap[field.iotField];
              if (field.iotIsalarm) {
                if (!field.iotFieldValue) field.iotFieldValue = 0;
                if (field.iotField.indexOf("IoStatus") > -1) {
                  field.iotFieldValue =
                    field.iotFieldValue === 1 ? true : false;
                } else {
                  field.iotFieldValue =
                    field.iotFieldValue === 0 ? false : true;
                }
              }
            });

            if (eq.bmIotEquipmentRelationshipList) {
              var _alertcount = eq.bmIotEquipmentRelationshipList.filter(
                (re) => {
                  if (re.iotIsalarm && re.status && re.iotFieldValue) {
                    return re;
                  }
                }
              ).length;
              // setAlertcount(_alertcount);
              setFieldValueMap(_fieldValueMap);
            }
          }
        } else {
          // console.log(data);
        }
      })
      .catch((ex) => {
        console.log(ex);
      });
  };
  react.useEffect(() => {
    if (eq.code === null) return;
    //updatefields();
  }, [eq]);
  react.useEffect(() => {
    //updatefields();
  }, [eq.iotFieldValue]);
  let togglePop = () => {
    popHandle(eq);
    // setState((prevState) => ({
    //   ...prevState,
    // }));
  };
  let alartPop = () => {
    alartPopHandle(eq);
    // setState((prevState) => ({
    //   ...prevState,
    // }));
  };
  return (
    <div className={` bg-white  h-fit  rounded  w-64  `}>
      {/* 第一行 */}
      <div className={`group flex flex-raw h-6   rounded-t  ${status.bg}`}>
        <div
          className={`flex-0  inline-flex items-center   text-white justify-center`}
        >
          {/* <div className="w-2"></div> {orderstatus[0].title} */}
          <div className="w-2"></div>
          <p className="truncate w-28 text-left cardP" alt={eq.code}>
            {" "}
            {eq.code}
          </p>
          {/* {eq?.typeName} */}
        </div>
        <div className="flex-auto"></div>
        <div className=" flex-0   inline-flex items-center   text-white justify-center  ">
          <p className="truncate w-28 text-right cardP" alt={eq.name}>
            {" "}
            {eq.name}
          </p>
          <div className="w-2"></div>
        </div>
      </div>
      <div className="relative flex">
        {!imgUrl ? (
          <img
            src={`../img/eqimg.jpeg`}
            alt={eq.name}
            className="  w-full h-20  bg-gray-500 "
          />
        ) : (
          // eslint-disable-next-line
          <img
            src={imgUrl}
            alt={eq.name}
            className="  w-full h-20  bg-gray-500 "
          />
        )}
        <Tooltip
          placement="top"
          title={eq?.bmIotEquipmentRelationshipList?.length>0?eq?.bmIotEquipmentRelationshipList[0].updateTime:""}
          mouseEnterDelay={1}
        >
          <button
            className={` absolute top-1 left-2	inline-block  px-1   text-xs  ${status.bg}-txt  text-white   ${status.bg}-border border   rounded-sm`}
          >
            {status.title}
            {status.key > 0 ? "中" : ""}
          </button>
        </Tooltip>
      </div>
      {/* 第二行 */}
      <div className="border-l border-r text-left pl-4 py-2 border-gray-200 flex flex-col  h-48">
        {!eq?.bmIotEquipmentRelationshipList ? (
          <></>
        ) : (
          eq?.bmIotEquipmentRelationshipList
            .filter((re) => {
              if (re.iotIsMainField && re.status) {
                return re;
              }
            })
            .sort((a, b) =>
              parseInt(a.fieldSort) > parseInt(b.fieldSort) ? 1 : -1
            )
            .map((re, idx) => {
              return (
                <div className={` flex flex-row mb-1 mr-3 `} key={idx}>
                  <VLabel>{re.iotFieldDescribe}：</VLabel>{" "}
                  <div className="flex-auto"></div>
                  <Tooltip
                    placement="top"
                    title={re.iotFieldValueTime}
                    mouseEnterDelay={1}
                  >
                    {!fieldValueMap ? (
                      ""
                    ) : (
                      <label
                        className={` text-right  ${classNamez} text-[#297FC8]`}
                      >
                        {typeof re.iotFieldValue === "boolean"
                          ? String(re.iotFieldValue)
                          : re.iotFieldValue}
                      </label>
                    )}
                  </Tooltip>
                </div>
              );
            })
        )}
      </div>

      {/* 第三行 */}
      <div className=" border group flex  items-center  flex-raw h-12 rounded-b  border-gray-200 px-1">
        <div className="  flex flex-row  flex-auto w-12 justify-center  cursor-pointer">
          {status.key === 2 ? (
            <PlayIcon className={`   flex-0 h-5 w-5  mr-1   ${status.text}`} />
          ) : status.key === 1 ? (
            <PauseIcon className={`   flex-0 h-5 w-5  mr-1   ${status.text}`} />
          ) : status.key === 3 ? (
            <StopIcon className={`   flex-0 h-5 w-5  mr-1   ${status.text}`} />
          ) : (
            <BellIcon className={`   flex-0 h-5 w-5  mr-1   ${status.text}`} />
          )}
          <div className="  flex-0 inline-flex items-center  ml-1  text-black justify-center ">
            {status.title}
          </div>
        </div>
        <div className="border-l border-gray-200  h-full flex-0"></div>
        <div
          onClick={alartPop}
          className=" flex  items-center  justify-center  flex-auto w-12 border-gray-200 cursor-pointer"
        >
          {/* {alertcount > 0 ? (
            <span className=" inline-flex rounded-full  text-red-500    items-center  justify-center  ">
              {alertcount}
            </span>
          ) :  */}

          <div className="relative inline-flex">
            {alertcount > 0 ? (
              <BellIconS
                className={`flex-0 h-5 w-5  mr-1 text-red-500  `}
              ></BellIconS>
            ) : (
              <BellIcon className={`flex-0 h-5 w-5  mr-1  `}></BellIcon>
            )}
            {alertcount > 0 ? (
              <span className="text-red-500">{alertcount}</span>
            ) : (
              ``
            )}
          </div>

          <div
            className={`flex-0 inline-flex items-center  ml-1  ${
              alertcount > 0 ? "text-red-500" : "text-black"
            } justify-center`}
          >
            告警
          </div>
        </div>
        <div className="border-l border-gray-200  h-full flex-0"></div>

        <div
          onClick={togglePop}
          className="  flex  flex-row   items-center  justify-center  flex-auto w-12 border-gray-200 cursor-pointer"
        >
          {ViewListIcon && <ViewListIcon className=" flex-0 h-5 w-5  mr-1  " />}
          <div className=" flex-0 inline-flex items-center  ml-1  text-black justify-center ">
            其他
          </div>
        </div>
      </div>
    </div>
  );
}
export default Card;
