import {
  analysisResultList,
  getAutoPatrolByRouteId,
  getPatrolDumuList,
  getPatrolRecordMandateInfo,
  getRecentAutoPatrolByRouteId,
  getRouteList,
  patrolRelationList,
  queryAnalysisDict,
  queryPatrolRecord,
  queryUserList,
} from '@/services/eqSelfInspection';

export default {
  namespace: 'eqSelfInspection',
  state: {
    autoReport: {
      warningTotalNum: 0,
    },
    patrolList: [],
    mandateInfo: [],
  },
  effects: {
    *getAutoPatrol({ payload, callback }, { call, put }) {
      const response = yield call(getRecentAutoPatrolByRouteId, payload);
      if (response) {
        // 查询数据报表详情
        yield put({
          type: 'getPatrolDataById',
          payload: { routeId: response.data[0].Id },
          callback: callback,
        });
      }
    },
    *fetchUserList({ payload }, { call, put }) {
      const response = yield call(queryUserList, payload);
      if (response) {
        yield put({
          type: 'userListHandler',
          payload: response.data,
        });
      }
    },
    *getPatrolDataById({ payload, callback }, { call, put, select }) {
      const { data } = yield call(queryPatrolRecord, {
        recordId: payload.routeId,
      });
      if (data) {
        const cacheData = yield select(
          (state) => state.eqSelfInspection.autoReport,
        );
        if (cacheData.Id === data.Id) {
          callback?.(cacheData);
          return;
        }
        const creatorName = data.CreatorUser && data.CreatorUser.CName;
        var status = {};
        let Items = [],
          sensor = [];
        const getItems = (item, patrolType) => {
          let key;
          if (patrolType == 1) {
            key = item.PatrolName;
          } else {
            key = item.DeviceCode + '-' + item.DeviceName;
          }
          item.TemplateItem = item.TemplateItem || {};
          item.patrolType = patrolType;
          item.ThresholdEnum = item.TemplateItem.ThresholdEnum;
          item.Type = item.TemplateItem.Type;
          if (!status[key]) status[key] = { normal: 0, error: 0 };
          if (item.Status == 1) {
            status[key].error++;
          } else {
            status[key].normal++;
          }
          return item;
        };
        let patrolCard = {};
        let arr = [];
        (data.ItemsExtend || []).forEach((item) => {
          console.log(Items);
          if (item.PatrolCardRecordItemAssocThreshold) {
            var arr = item.PatrolCardRecordItemAssocThreshold.map((i) =>
              getItems(i, 1),
            );
            Items = Items.concat(arr);

            patrolCard[item.DeviceCode] =
              item.PatrolCardRecordItemAssocThreshold;
          } else {
            Items.push(getItems(item, 0));

            if (!patrolCard[item.DeviceCode]) patrolCard[item.DeviceCode] = [];
            patrolCard[item.DeviceCode].push(item);
          }
        });
        (data.ItemsSensor || []).forEach((item) => {
          if (item.PatrolCardRecordItemAssocThreshold) {
            var arr = item.PatrolCardRecordItemAssocThreshold.map((i) =>
              getItems(i, 1),
            );
            sensor = sensor.concat(arr);
          } else {
            sensor.push(getItems(item, 0));
          }
        });

        data.Items = Items;
        data.sensor = sensor;

        (data.Points || []).forEach((item) => {
          let key;
          if (item.PatrolType == 1) {
            key = item.DeviceName;
          } else {
            key = item.DeviceCode + '-' + item.DeviceName;
          }
          item.creatorName = creatorName;
          item.level = `${item.ExceptionLevel || '-'}/${
            item.DeviceLevel || '-'
          }`;
          item.status = status[key] || { normal: 0, error: 0 };

          if (patrolCard[item.DeviceCode] instanceof Array) {
            arr = [...arr, ...patrolCard[item.DeviceCode]];
          }
        });
        var ruleList = [46, 65, 92, 94];
        if (ruleList.indexOf(data.ProjectId) != -1) {
          const analysisDict = yield call(queryAnalysisDict, {
            pageSize: 9999,
          });
          const analysisResult = yield call(analysisResultList, {
            project_id: data.ProjectId,
            id: data.Id,
          });
          const patrolRelation = yield call(patrolRelationList, {
            ids: analysisResult?.data,
            project_id: data.ProjectId,
            page: 1,
            page_size: 9999,
          });
          if (patrolRelation) {
            let FaultAnalysis = [];
            patrolRelation?.data?.list?.map((item) => {
              var reason = analysisDict?.data.find(
                (reason) => reason.id == item.Reason,
              );
              if (reason) {
                item.Reason = reason.content;
              }
              var FixPlanArr = item.FixPlan.split(',');
              if (FixPlanArr.length > 0) {
                var FixPlan = [];
                FixPlanArr.map((fixItem) => {
                  var fixPlan = analysisDict?.data.find(
                    (reason) => reason.id == fixItem,
                  );
                  if (fixPlan) FixPlan.push(fixPlan);
                });
                console.log(FixPlan);
              }
              FaultAnalysis.push({
                device_name: item.DeviceName,
                device_code: item.DeviceCode,
                reason: item.Reason,
                fix_plan: FixPlan,
                c_time: item.CTime,
              });
            });
            data.FaultAnalysis = FaultAnalysis;
            console.log(data.FaultAnalysis);
          }
        }

        const dumuList = yield call(getPatrolDumuList, {
          record_id: payload.routeId,
          project_id: data.ProjectId,
        });
        if (dumuList) {
          data.dumuList = dumuList.data || [];
        }
        console.log(data);

        data.sensorWaringData =
          data.sensor?.filter(
            (item) => item.Status === 2 || item.Status === 1,
          ) || [];
        data.sensorWaringNum = data.sensorWaringData.filter(
          (item) => item.Status === 1,
        ).length;

        data.extendWarningAllData = arr;
        data.extendWarningData =
          arr?.filter((item) => item.Status === 2 || item.Status === 1) || [];
        data.extendWarningNum =
          arr?.filter((item) => item.Status === 1)?.length || 0;

        //获取液位检测异常数量
        // const errorNum = data.FluidLevelList?.filter(
        //   (item) => item.status == 1,
        // );
        let num = 0;
        if (data?.extendWarningData?.length > 0) num += 1;
        if (data?.sensorWaringNum > 0) num += 1;
        if (data?.dumuList?.length > 0) num += 1;
        if (data?.FaultAnalysis?.length > 0) num += 1;
        // if (errorNum?.length > 0) num += errorNum;
        data.warningTotalNum = num;

        if (data.extendWarningNum > 0) {
          // 判断是否有异常
          data.patrolStatus = 1;
        } else if (data.extendWarningData.length - data.extendWarningNum > 0) {
          // extendWarningData包含警告和异常
          // 判断是否有警告
          data.patrolStatus = 2;
        } else {
          data.patrolStatus = 0;
        }
        data.faultAnalysisStatus = data?.FaultAnalysis?.length > 0 ? 1 : 0;
        // data.secureStatus =
        //   data?.dumuList?.length > 0 || data?.sensorWaringNum > 0 ? 1 : 0;
        data.secureStatus = data?.dumuList?.length > 0 ? 1 : 0;
        let secureChild = [];
        let dumuStatus = 0;
        if (data?.dumuList?.length > 0) {
          dumuStatus = 1;
        }
        secureChild.push({ label: '安防检测', status: dumuStatus });

        let sensorStatus = 0;
        if (data?.sensorWaringNum > 0) {
          sensorStatus = 1;
        }
        secureChild.push({ label: '环境检测', status: sensorStatus });
        secureChild.push({ label: '电气检测', status: 0 });
        secureChild.push({ label: '密闭空间检测', status: 0 });

        data.secureChild = secureChild;

        callback?.(data);
        yield put({
          type: 'save',
          payload: { autoReport: data },
        });
      }
    },

    *getList({ payload }, { call, put }) {
      const response = yield call(getRouteList, payload);
      if (response) {
        yield put({
          type: 'save',
          payload: {
            patrolList: response.data?.filter((item) => item.IsAuto === 1),
          },
        });
      }
    },
    *getPatrolRecordMandateInfo({ payload }, { call, put }) {
      const response = yield call(getPatrolRecordMandateInfo, payload);
      if (response) {
        yield put({
          type: 'save',
          payload: {
            mandateInfo: response?.data,
          },
        });
      }
    },
    *inspectionRoute({ payload, callback }, { call, put, select }) {
      //先通过巡检路线的Id申请接口，拿到最新的巡检记录Id，去查询
      const response = yield call(getAutoPatrolByRouteId, payload);
      if (response) {
        yield put({
          type: 'getAutoPatrol',
          payload: { projectId: payload.projectId, route_id: payload.routeId },
          callback: callback,
        });
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
