import {
  queryArea,
  queryConfig,
  querySpace,
  updateSpace,
  createSpace,
  queryDataConfig,
  queryData,
  queryPlcData,
  createOperation,
  updateOperation,
  deleteOperation,
  queryOperation,
  queryOperationDetail,
  querySpaceDetail,
  queryDownloadOperation,
  queryRescue,
  queryRescueDetail,
  createRescue,
  deleteRescue,
  queryDownloadRescue,
  queryDownloadCard,
} from '@/services/limitedSpace';
import { getRealtimeData } from '@/services/DeviceInfo';
import { message } from 'antd';
import res from '@/pages/SysAdmin/AuthorityAdmin/models/res';

export default {
  namespace: 'limitedSpace',
  state: {
    areaList: [],
    space: { list: [], pagination: {}, statistics: {} },
    config: [],
    dataConfig: [],
    spaceData: { list: [], pagination: {} },
    operation: { list: [], pagination: {} },
    opDetail: { op: {}, space: {} },
    spaceDetail: {},
    rescue: { list: [], pagination: {} },
    rescueDetail: {},
  },

  effects: {
    *queryArea({ payload, callback }, { call, put }) {
      const res = yield call(queryArea, payload);
      if (!res) return;
      yield put({ type: 'save', payload: { areaList: res.data } });
    },

    *queryConfig({ payload, callback }, { call, put }) {
      const res = yield call(queryConfig, payload);
      if (!res) return;
      yield put({
        type: 'save',
        payload: { config: res.data },
      });
    },

    *querySpace({ payload, callback }, { call, put }) {
      const res = yield call(querySpace, payload);
      if (!res) return;
      let spaceList = res.data.list;
      const { current, pageSize } = res.data.pagination;
      for (let i = 0; i < spaceList.length; ++i) {
        // spaceList[i] = { ...spaceList[i], spaceId: i * res.data.pagination.current + 1 };
        spaceList[i] = { ...spaceList[i], spaceId: i + 1 + (current - 1) * pageSize };
      }
      callback && callback(spaceList);
      yield put({
        type: 'save',
        payload: { space: { ...res.data, list: spaceList } },
      });
    },

    *createSpace({ payload, callback }, { call, put }) {
      const { id } = yield call(createSpace, payload);
      if (!id) return;
      callback && callback();
      message.success('添加成功');
      const { project_id } = payload;
      yield put({
        type: 'queryList',
        payload: { project_id: project_id },
      });
    },

    *updateSpace({ payload, callback }, { call, put }) {
      const { id } = yield call(updateSpace, payload);
      if (!id) return;
      callback && callback();
      message.success('编辑成功');
      const { project_id } = payload;
      yield put({
        type: 'queryList',
        payload: { project_id: project_id },
      });
    },

    *queryDataConfig({ payload, callback }, { call, put }) {
      const res = yield call(queryDataConfig, payload);
      if (!res) return;
      yield put({
        type: 'save',
        payload: { dataConfig: res.data },
      });
    },

    *queryData({ payload, callback }, { call, put }) {
      let res = yield call(queryDataConfig, payload);
      if (!res) return;
      let configList = res.data; //判断条件
      yield put({
        type: 'save',
        payload: { dataConfig: configList },
      });

      res = yield call(queryData, payload);
      if (!res) return;
      let dataList = res.data.list; //plc数据

      let realDataParams = [];
      let dataKeys = configList.map(item => item.item_name);
      dataList.forEach(item => {
        dataKeys.forEach(key => {
          if (item[key] && item[key] != '-') {
            let [deviceId, deviceItems] = item[key].split(',');
            item[key] = {
              deviceId,
              deviceItems,
              project_id: Number(payload.project_id),
            };
            realDataParams.push(item[key]);
          } else {
            // 没有数据的置为空
            item[key] = '';
          }
        });
      });
      const { data: realData } = yield call(getRealtimeData, realDataParams);
      dataList.forEach(item => {
        item.statusObj = {}; // 状态对象 {data1: 3, data2: 3, data3: 2, data4: 1}
        dataKeys.forEach(keys => {
          if (item[keys]) {
            let config = configList.find(t => t.item_name == keys);
            let { deviceId, deviceItems } = item[keys];
            let realValue = realData.find(
              item => item.devid == deviceId && item.itemname == deviceItems
            );
            let singleStatus = 0;
            let x = realValue.val;
            if (config.threshold && eval(config.threshold)) singleStatus = 1; //安全
            if (config.notice_threshold && eval(config.notice_threshold)) singleStatus = 2; //预警
            if (config.warning_threshold && eval(config.warning_threshold)) singleStatus = 3; //报警
            item.statusObj[keys] = singleStatus;
            item[keys] = realValue.val;
            // item[keys] = `${realValue.val},${status}`;
          } else {
            item[keys] = 0;
            //无数据
            item.statusObj[keys] = 0;
          }
        });
      });

      const { current, pageSize } = res.data.pagination;
      for (let i = 0; i < dataList.length; ++i) {
        dataList[i] = { ...dataList[i], spaceId: i + 1 + (current - 1) * pageSize };
      }
      yield put({
        type: 'save',
        payload: { spaceData: { list: dataList, pagination: res.data.pagination } },
      });
    },

    *createOperation({ payload, callback }, { call, put }) {
      const res = yield call(createOperation, payload);
      if (!res) return;
      callback && callback();
      message.success('提交成功');
      const project_id = payload.project_id;
      yield put({
        type: 'queryOperation',
        payload: { project_id: project_id },
      });
    },

    *updateOperation({ payload, callback }, { call, put }) {
      const res = yield call(updateOperation, payload);
      if (!res) return;
      callback && callback();
      message.success('提交成功');
      const project_id = payload.project_id;
      yield put({
        type: 'queryOperation',
        payload: { project_id: project_id },
      });
    },

    *deleteOperation({ payload, callback }, { call, put }) {
      const { id, project_id } = payload;
      const res = yield call(deleteOperation, { id: id });
      if (!res) return;
      callback && callback();
      message.success('删除成功');
      yield put({
        type: 'queryOperation',
        payload: { project_id: project_id },
      });
    },

    *queryOperation({ payload, callback }, { call, put }) {
      const res = yield call(queryOperation, payload);
      if (!res) return;
      let opList = res.data.list;
      const { current, pageSize } = res.data.pagination;
      for (let i = 0; i < opList.length; ++i) {
        opList[i] = { ...opList[i], opId: i + 1 + (current - 1) * pageSize };
      }
      callback?.(opList);
      yield put({
        type: 'save',
        payload: { operation: res.data },
      });
    },

    *queryOpDetail({ payload, callback }, { call, put }) {
      const res = yield call(queryOperationDetail, payload);
      if (!res) return;
      let data = res.data;
      let space = data.space;
      Object.keys(space).forEach(key => {
        if (key.includes('_pic')) {
          try {
            space[key] = JSON.parse(space[key] || '[]');
          } catch (error) {
            space[key] = [];
            console.error(error);
          }
        }
      });
      callback && callback(data);
      yield put({
        type: 'save',
        payload: { opDetail: data },
      });
    },

    *querySpaceDetail({ payload, callback }, { call, put }) {
      const res = yield call(querySpaceDetail, payload);
      if (!res) return;
      // let data = res.data;
      // let space = data.space;
      let space = res.data;
      Object.keys(space).forEach(key => {
        if (key.includes('_pic')) {
          try {
            space[key] = JSON.parse(space[key] || '[]');
          } catch (error) {
            space[key] = [];
            console.error(error);
          }
        }
      });
      // callback && callback(data);
      callback && callback(space);
      yield put({
        type: 'save',
        payload: { spaceDetail: space },
      });
    },

    *querySpacesDetail({ payload, callback }, { call, put }) {
      let res,
        list = [];
      for (let i = 0; i < payload.selectedSpace.length; i++) {
        res = yield call(querySpaceDetail, { id: payload.selectedSpace[i] });
        if (!res) return;
        let space = res.data;
        Object.keys(space).forEach(key => {
          if (key.includes('_pic')) {
            try {
              space[key] = JSON.parse(space[key] || '[]');
            } catch (error) {
              space[key] = [];
              console.error(error);
            }
          }
        });
        list.push(space);
      }
      callback && callback(list);
    },

    *queryDownloadOperation({ payload, callback }, { call, put }) {
      const res = yield call(queryDownloadOperation, payload);
      if (!res) return;
      callback && callback(res.data);
    },

    *queryRescue({ payload, callback }, { call, put }) {
      const res = yield call(queryRescue, payload);
      if (!res) return;
      let saveList = res.data.list;
      const { current, pageSize } = res.data.pagination;
      for (let i = 0; i < saveList.length; ++i) {
        saveList[i] = { ...saveList[i], saveId: i + 1 + (current - 1) * pageSize };
      }
      callback?.(saveList);
      yield put({
        type: 'save',
        payload: { rescue: res.data },
      });
    },

    *queryRescueDetail({ payload, callback }, { call, put }) {
      const res = yield call(queryRescueDetail, payload);
      if (!res) return;
      let space = res.data;
      Object.keys(space).forEach(key => {
        if (key.includes('_pic')) {
          try {
            space[key] = JSON.parse(space[key] || '[]');
          } catch (error) {
            space[key] = [];
            console.error(error);
          }
        }
      });
      callback && callback(res.data);
      yield put({
        type: 'save',
        payload: { rescueDetail: res.data },
      });
    },

    *createRescue({ payload, callback }, { call, put }) {
      const res = yield call(createRescue, payload);
      if (!res) return;
      callback && callback();
      message.success('提交成功');
      const project_id = payload.project_id;
      yield put({
        type: 'queryRescue',
        payload: { project_id: project_id },
      });
    },

    *deleteRescue({ payload, callback }, { call, put }) {
      const { id, project_id } = payload;
      const res = yield call(deleteRescue, { id: id });
      if (!res) return;
      callback && callback();
      message.success('删除成功');
      yield put({
        type: 'queryRescue',
        payload: { project_id: project_id },
      });
    },

    *queryDownloadRescue({ payload, callback }, { call, put }) {
      const res = yield call(queryDownloadRescue, payload);
      if (!res) return;
      callback && callback(res.data);
    },

    *queryDownloadCard({ payload, callback }, { call, put }) {
      const res = yield call(queryDownloadCard, payload);
      if (!res) return;
      callback && callback(res.data);
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
