import moment from "moment";
import store from "@/store";

// 将现有机房巡检数据转换为SQL数据所需要格式
export function dataToSql(data) {
  let synFlag = 0;
  // 是否有草稿状态的井道
  let hasDraft;
  hasDraft = !(data.originData.reduce((acc,cur) => {
    acc.push(...cur.position)
    return acc
  }, []).every(pos => pos.isSubmit === '' || pos.isSubmit === 1))
  if (data.synchronization === 1) {
    synFlag = 1;
  } else {
    if(hasDraft || !data.signImg) {
      synFlag = 2
    } else {
      synFlag = 0
    }
  }
  const send = {
    inspectionType: data.inspectionType,
    inspectionCode: data.inspectionCode,
    recordName: `${moment().format("yyyyMMDD")}-井道巡检`,
    inspectionTime: moment().valueOf(),
    isException: data.isException, // 是否异常：0 否 1 是 2 巡检中
    userId: store.state.now_user.userId,
    userName: store.state.now_user.user,
    synFlag: synFlag, // 0.未同步，1.已同步，2.编辑
    signImg: data.signImg || "",
    createBy: store.state.now_user.userId,
    createTime: data.id ? data.createTime : `${new Date().getTime()}`,
    updateTime: `${new Date().getTime()}`,
    updateBy: store.state.now_user.userId,
    inspectionData: data.originData,
  };
  console.log("dataToSql", send);
  return send;
}

export function sqlToData(sqlData) {
  try {
    let isSubmit;
    let synchronization;

    if (sqlData.synFlag === 0) {
      isSubmit = 0;
      synchronization = 0;
    } else {
      isSubmit = 1;
      synchronization = sqlData.synFlag;
    }
    const originData = JSON.parse(sqlData.inspectionData || "{}");
    const inspectedItems = originData.reduce((acc,cur) => {
      acc.push(...cur.position)
      return acc
    }, []).filter((item) => (item.status == 1 || item.status == 2) && item.isSubmit !== 0)
    console.log(inspectedItems)

    // 获取已经巡检过的数量
    const inspectionNumber = inspectedItems.length;

    const ret = {
      id: sqlData.id,
      inspectionType: sqlData.inspectionType,
      inspectionCode: sqlData.inspectionCode,
      isException: sqlData.isException,
      signImg: sqlData.signImg,
      createTime: sqlData.createTime,
      isSubmit: isSubmit,
      synchronization: synchronization,
      originData,
      inspectionNumber
    };
    console.log(ret)
  return ret;
  } catch (err) {
    console.log(err)
  }
}
