import moment from "moment";
import store from "@/store";
import inspectApi from "@/api/inspect.js";

// 将现有机房巡检数据转换为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 || 2,
		inspectionCode: data.inspectionCode || `JDXJ${moment().format("yyyyMMDDHHmmss")}${Math.floor(Math.random() * 900) + 100}`,
		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 || 2,
			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)
	}
}



export function getHistoryData() {
	return new Promise((resolve, reject) => {
		inspectApi.selectLastData(store.state.now_user.userId, 2).then((history) => {
			if (history && history.length) {
				// 处理历史数据（选项、文案、照片；异常项-不调出文案及照片）
				const data = setHistoryData(history[0]);
				resolve(data);
			} else {
				resolve(null);
			}
		});
	});
}

function setHistoryData(data) {
	const inspectionData = JSON.parse(data.inspectionData || '[]');
	// 如果该机房有异常项，则不调出文案及照片
	inspectionData.forEach(item => {
		item.position.forEach((current) => {
		  if (current.statusLable == '巡检异常') {
				current.statusLable = '草稿'
		    // 内部的异常标识
		    current.details.forEach((detail) => {
		      // 表单项的异常
		      if (detail.inspectionResult == 1) {
		        detail.conclusion = "";
		        detail.photos = [];
		      }
		    });
		  }
		});
	})
	data.inspectionData = JSON.stringify(inspectionData)
	data.signImg = "";
	data.synFlag = 0
	data.inspectionCode = `JDXJ${moment().format("yyyyMMDDHHmmss")}${Math.floor(Math.random() * 900) + 100}`;
	delete data.createTime
	delete data.delFlag;
	delete data.inspectionTime;
	// delete data.synFlag;
	delete data.updateBy;
	delete data.updateTime;
	delete data.userId;
	delete data.userName;
	delete data.recordName;
	return data;
}