<script>
import {
  BASE_PATH,
  SYNCHRONIZE_DATA_PATH,
  SYNCHRONIZE_DATA_PAD,
  checkAndCreateDirectory,
  checkFileExists,
  createFileWithPlusIO,
  readFileContent,
  USER_LiST,
  USER_FILE_NAME,
} from "./utils/systemCofig";
import { Base64 } from "js-base64";
import { differenceBy } from "lodash";

import { readDirectoryData } from "@/utils/IoReadingAndWriting.js";
import initService from "@/api/sqllite/init.js";
export default {
  onLaunch: function () {
    // #ifdef APP-PLUS
    plus.screen.lockOrientation("landscape-primary"); //锁定横屏
    // #endif

    this.init();

    // #ifdef APP-PLUS
    plus.android.requestPermissions(
      ["android.permission.WRITE_EXTERNAL_STORAGE"],
      function (e) {
        if (e.deniedAlways.length > 0) {
          //权限被永久拒绝
          // 弹出提示框解释为何需要读写手机储存权限，引导用户打开设置页面开启
          uni.showModal({
            title: "存储权限",
            content: "您拒绝了存储权限，请去设置-应用开启存储权限。",
            success: function (res) {
              if (res.confirm) {
              } else if (res.cancel) {
              }
            },
          });
        }
        if (e.deniedPresent.length > 0) {
          //权限被临时拒绝
          // 弹出提示框解释为何需要读写手机储存权限，可再次调用plus.android.requestPermissions申请权限
          plus.android.requestPermissions([
            "android.permission.WRITE_EXTERNAL_STORAGE",
          ]);
        }
        if (e.granted.length > 0) {
          //权限被允许
          init();
        }
      },
      function (e) {}
    );
    // #endif
  },
  onShow: function () {
    const now_user = uni.getStorageSync("now_user") || {};
    if (now_user.user) {
      this.$store.commit("SET_USER", now_user);
    }
    // this.init();
  },
  onLoad: function (query) {
    console.log("即将开始初始化app");
  },
  onHide: function () {
    // app关闭时将数据存储到本地缓存
    uni.setStorageSync("now_user", this.$store.state.now_user);
    uni.setStorageSync(
      "last_time",
      this.$store.state.now_user.LastSynchronizationTime
    );

    // 清除store 数据
    this.$store.commit("SET_DARF_DATA", {});
    this.$store.commit("SET_LOG_LIST", []);
    this.$store.commit("SET_ALL_DATA", []);
  },
  onUnload() {},
  methods: {
    /**
     * 第一步: 检查目录是否存在，如果没有就创建
     * 第二步：检查指定文件是否存在，如果存在就读取内容；否则就创建文件，并写入初始化数据
     * 第三步：存储读取到的数据
     */
    async init() {
      initService.init();
	  return
      checkAndCreateDirectory(SYNCHRONIZE_DATA_PAD)
        .then(() => {
          return new Promise((resolve, reject) => {
            // 检查目录下的文件是否存在
            checkFileExists(SYNCHRONIZE_DATA_PAD, USER_FILE_NAME)
              .then((fileEntry) => {
                // 文件存在，
                return readFileContent(fileEntry)
                  .then((res) => {
                    resolve(res);
                  })
                  .catch((error) => {
                    reject(error);
                  });
              })
              .catch((error) => {
                // 文件不存在, 写入文件
                const fileContent = JSON.stringify(
                  Base64.encode(JSON.stringify(USER_LiST))
                );
                createFileWithPlusIO(
                  SYNCHRONIZE_DATA_PAD,
                  USER_FILE_NAME,
                  fileContent
                )
                  .then((res) => {
                    resolve(res);
                  })
                  .catch((error) => {
                    reject(error);
                  });
              });
          })
            .then(async (res) => {
              // 获取文件数据
              let userData = Base64.decode(res);

              const diffUserList = await this.diffUserList(userData);
              if (diffUserList.length) {
                this.updateIpadUsetList([...USER_LiST, ...diffUserList]);

                userData = JSON.stringify([...USER_LiST, ...diffUserList]);
              }

              uni.setStorage({
                key: "user_data",
                data: userData,
                fail: (error) => {
                  console.log("APP.vue 存储数据失败", error);
                },
              });
            })
            .catch((error) => {
              console.log("---", error);
            });
        })
        .catch((error) => {
          console.log("---目录创建失败", error);
        });
    },

    //  比较代码中的用户列表 和 ipad中存储用户的 差异
    async diffUserList(ipadUserList = []) {
      const temp = eval(ipadUserList);
      const diffResult = differenceBy(USER_LiST, temp, "userId");

      return diffResult;
    },

    // 更新 ipad 用户信息
    updateIpadUsetList(tempPersonList) {
      const temp = JSON.stringify(tempPersonList);

      const fileContent = JSON.stringify(Base64.encode(temp));
      createFileWithPlusIO(SYNCHRONIZE_DATA_PAD, USER_FILE_NAME, fileContent);
    },
  },
};
</script>

<style lang="less">
@import "./common/atom.less";
@import "./common/base.less";
@import "./common/global.css";
@import "~@/static/iconFont/iconfont.css";

@font-face {
  font-family: AlibabaPuHuiTi-Medium;
  src: url("~@/static/font/Alibaba-PuHuiTi-Medium.ttf");
}

@font-face {
  font-family: "iconfont";
  /* Project id 4374193 */
  src: url("~@/static/iconFont/iconfont.woff2?t=1725876968366") format("woff2"),
    url("~@/static/iconFont/iconfont.woff?t=1725876968366") format("woff"),
    url("~@/static/iconFont/iconfont.ttf?t=1725876968366") format("truetype");
}

// @font-face {
//   font-family: "iconfont"; /* Project id 4374193 */
//   src: url('iconfont.woff2?t=1725876968365') format('woff2'),
//        url('iconfont.woff?t=1725876968365') format('woff'),
//        url('iconfont.ttf?t=1725876968365') format('truetype');
// }
@font-face {
  font-family: AlibabaPuHuiTi;
  src: url("~@/static/font/Alibaba-PuHuiTi-Regular.ttf");
}

@font-face {
  font-family: YouSheBiaoTiHei;
  src: url("~@/static/font/YouSheBiaoTiHei.ttf");
}

body {
  width: 100vw;
  // height: calc(100vh - 44px);
  height: 100vh;
  background-color: #f3f6fa;

  /* background-color: red; */
}

* {
  box-sizing: border-box;
  font-family: AlibabaPuHuiTi;
  /* font-size: 9.41rpx; */
}

image {
  will-change: transform;
  /* 解决加载时瞬间拉伸问题 */
  width: auto;
  /* 解决加载时瞬间拉伸问题 */
  height: auto;
  /* 解决加载时瞬间拉伸问题 */
  image-rendering: -moz-crisp-edges;
  image-rendering: -o-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -ms-interpolation-mode: nearest-neighbor;
}

.uni-nav-bar-text {
  /* 导航栏文字大小 */
  font-size: 24px !important;
  letter-spacing: 1px;
}

.uni-navbar--shadow {
  box-shadow: none !important;
}

.uni-data-checklist .checklist-group {
  flex-wrap: nowrap !important;
}

/*每个页面公共css */
</style>
