import SqlliteDbUtil from "@/utils/sqllitedb";
import table from "./sqllite/table.js";
import { fixNullVal } from "@/utils/common";

// 巡检
export default {
  async selectLastData(data, inspectionType = 1) {
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let rs = await sqllitedb.selectSQL(
        `SELECT *
FROM ${table.inspectionRecordName}
WHERE userId = '${data}' 
  AND createTime >= strftime('%s', 'now') - 7*24*60*60
  AND inspectionType = '${inspectionType}' 
	AND (synFlag = 0 OR synFlag = 1)
ORDER BY createTime DESC
LIMIT 1;`
      );
      return rs;
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
  },
  async selectList() {
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let rs = await sqllitedb.selectSQL(
        `select * from ${table.inspectionRecordName}`
      );
      return rs;
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
  },
  async selectDataForTime(data) {
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let inspectionTimeCondition = "";
      if (
        Array.isArray(data.inspectionTime) &&
        data.inspectionTime.length === 2
      ) {
        const startTime = new Date(data.inspectionTime[0]).getTime();
        const endTime = new Date(
          data.inspectionTime[1] + "T23:59:59"
        ).getTime();
        inspectionTimeCondition = `AND inspectionTime >= '${startTime}' AND inspectionTime <= '${endTime}'`;
      }
      let isAdmin = "";
      if (data.userId) {
        const userResult = await sqllitedb.selectSQL(
          `SELECT isAdmin FROM ${table.userName} WHERE userId = '${data.userId}'`
        );
        isAdmin = userResult?.[0]?.isAdmin || "";
      }
      const userCondition = isAdmin ? "" : `AND userId = '${data.userId}'`;
      let sql = `SELECT id,inspectionType,inspectionCode
				,recordName
				,userName
				,userId
				,inspectionTime
				,isException
				,synFlag
				,dataSource
				,signImg
				,createTime,delFlag,inspectionData
				 FROM ${table.inspectionRecordName} 
			where 1=1
			${data.inspectionType ? `AND inspectionType = '${data.inspectionType}'` : ""}
		    ${data.synFlag ? `AND synFlag = '${data.synFlag}'` : ""}
		    ${data.isException ? `AND isException = '${data.isException}'` : ""}
			${inspectionTimeCondition}
			${userCondition}
			and delFlag = 0
			order by createTime desc`;
      let rs = await sqllitedb.selectSQL(sql);
      console.log("sql", sql);
      return rs;
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
  },
  async info(id) {
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let sql = `select * from ${table.inspectionRecordName} where id = '${id}'`;
      let res = await sqllitedb.selectSQL(sql);
      if (res && res.length > 0) {
        return res[0];
      }
    } catch (e) {
      console.log(e.message);
    } finally {
      // await sqllitedb.closeDB();
    }
  },
  async remove(arr) {
    if (!id) {
      return;
    }
    let sql = `delete from ${table.inspectionRecordName} where id in '${id}'`;
    try {
      let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
      await sqllitedb.executeSQL(sql);
    } catch (e) {
      console.log(e.message);
    } finally {
      // await sqllitedb.closeDB();
    }
  },
  //更新同步
  async updateSyncData(data) {
    let ids = "(" + data.join(",") + ")";
    let sql = `update ${table.inspectionRecordName} set synFlag=1 where id in ${ids}`;
    try {
      let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
      let rs = await sqllitedb.executeReturnDataSQL(sql);
      return rs;
    } catch (e) {
      console.log(e.message);
    } finally {
      // await sqllitedb.closeDB();
    }
  },
  async batchRemove(id) {
    let sql = `update ${table.inspectionRecordName} set delFlag=1 where id = '${id}'`;
	let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let rs = await sqllitedb.executeReturnDataSQL(sql);
      return rs;
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
  },

  async remove(arr) {
    if (!id) {
      return;
    }
    let sql = `delete from ${table.inspectionRecordName} where id = '${id}'`;
    try {
      let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
      await sqllitedb.executeSQL(sql);
    } catch (e) {
      console.log(e.message);
    } finally {
      // await sqllitedb.closeDB();
    }
  },
  async saveBatch(list) {
    if (list.length === 0) {
      return;
    }
    console.log("开始保存用户信息...." + list.length);
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      for (let data of list) {
        let column = "";
        let values = "";
        let idx = 0;
        for (let attr in data) {
          let dataField = table["inspectionRecord"].find((v) => {
            if (v.field === attr) {
              return v;
            }
          });
          if (!dataField) {
            continue;
          }
          column += dataField.field + ",";
          values += "'" + fixNullVal(data[attr]) + "',";
          idx++;
        }

        column = column.endsWith(",")
          ? column.substring(0, column.length - 1)
          : column;
        values = values.endsWith(",")
          ? values.substring(0, values.length - 1)
          : values;

        let sql = `insert into ${table.inspectionRecordName}(${column}) values(${values})`;
        let has = await this.info(data.id);
        if (has && has.id) {
          await this.remove(data.id);
        }
        await sqllitedb.executeSQL(sql);
      }
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
    console.log("导入完成...");
  },
  async save(data) {
    console.log("开始保存巡检记录", data);
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      let sql = `insert into ${table.inspectionRecordName}(
			inspectionType,
			inspectionCode,
			recordName,
			inspectionTime,
			isException,
			userId,
			userName,
			synFlag,
			createBy,
			createTime,
			updateTime,
			signImg,
			inspectionData
		) values(
			'${data.inspectionType}',
			'${data.inspectionCode}',
			'${data.recordName}',
			'${data.inspectionTime}',
			'${data.isException}',
			'${data.userId}',
			'${data.userName}',
			'${data.synFlag}',
			'${data.createBy}',
			'${data.createTime}',
			'${data.updateTime}',
			'${data.signImg}',
			'${JSON.stringify(data.inspectionData)}'
		 );
		 `;
      let result = await sqllitedb.executeReturnDataSQL(sql);
      console.log(result, "有有有有有有");
      return result;
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
    console.log("导入完成...");
  },
  async update(data) {
    console.log("开始更新巡检记录", data);
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      if (!data.id) {
        throw new Error("更新操作需要提供 id");
      }
      let sql = `UPDATE ${table.inspectionRecordName} SET 
            inspectionType = '${data.inspectionType}',
            inspectionCode = '${data.inspectionCode}',
            recordName = '${data.recordName}',
            inspectionTime = '${data.inspectionTime}',
            isException = ${data.isException},
            userId = '${data.userId}',
            userName = '${data.userName}',
            synFlag = ${data.synFlag},
            signImg = '${data.signImg}',
            createBy = '${data.createBy}',
            createTime = '${data.createTime}',
            updateTime = '${data.updateTime}',
            inspectionData = '${JSON.stringify(data.inspectionData)}'
            WHERE id = ${data.id}`;
      await sqllitedb.executeSQL(sql);
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
    console.log("更新完成...");
  },
  async updateSignImg(data) {
    console.log("开始更新巡检签名图片", data);
    let sqllitedb = await SqlliteDbUtil.initSqlliteDB();
    try {
      if (!data.id) {
        throw new Error("更新操作需要提供 id");
      }
      let sql = `UPDATE ${table.inspectionRecordName} SET 
            signImg = '${data.signImg}',
			synFlag = '${data.synFlag}',
			isException = '${data.isException}'
            WHERE id = ${data.id}`;
      await sqllitedb.executeSQL(sql);
    } catch (e) {
      console.log(e.message);
    } finally {
      await sqllitedb.closeDB();
    }
    console.log("更新完成...");
  },
};
