import { clipboard, ipcRenderer, remote } from "electron";
import { v4 as uuidv4 } from "uuid";
import {
  getWindowHeight,
  searchKeyValues,
  sysFile,
  mergePlugins,
  find,
  downloadZip,
  downloadZipFromGitCode,
  fileLists
} from "../../assets/common/utils";
import systemMethod from "../../assets/common/system";
import fs, { stat } from "fs";
import path from "path";
import { execSync } from "child_process";

const opConfig = remote.getGlobal("opConfig");

const state = {
  selected: null,
  options: [],
  showMain: false,
  current: ["market"],
  searchValue: "",
  devPlugins: mergePlugins(sysFile.getUserPlugins() || []),
  mode: "view",
  showUpdateBadge: false,
  installs: [
    {
      icon: "https://gitcode.net/codechina/operation-work/uploads/48886bea190eb24ef4cf0499e589554c/1_cpongo9_1634797583.gif",
      name: "CSDN",
      showTag: true,
      url: "http://csdn.net",
      tag: "new"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/6e49210c084629259f22609980c48ecf.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "日报",
      url: "https://c.csdn.net/pages/viewpage.action?pageId=79377929",
      showTag: true,
      tag: 7
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/assets/weather/code_100.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "天气",
      showTag: true,
      url: "http://weathernew.pae.baidu.com/weathernew/pc?query=%E5%8C%97%E4%BA%AC%E5%A4%A9%E6%B0%94&srcid=4982&city_name=%E5%8C%97%E4%BA%AC&province_name=%E5%8C%97%E4%BA%AC",
      tag: "26℃"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/cee009549b352def723ba09d6da4b742.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "京东",
      showTag: true,
      url: "http://www.jd.com",
      tag: "99+"
    },
    // {
    //   icon: "https://codechina-uploads.obs.cn-north-4.myhuaweicloud.com/appearance/favicon/1/icon.png?response-content-disposition=inline%3B%20filename%3D%22icon.png%22%3B%20filename%2A%3DUTF-8%27%27icon.png&response-content-type=image%2Fpng&X-Amz-Expires=600&X-Amz-Date=20211215T032431Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=QK3ORGAKW2CFPLGKCDJI%2F20211215%2Fcn-north-4%2Fs3%2Faws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=811e18ba658bc6fbd9a01f926daba12e4c4ce6f92abd9bffc808f953715bc20b",
    //   name: "Gitcode",
    //   showTag: true,
    //   tag: "git",
    // subMenu: [
    //   {
    //     icon: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F19%2F39%2F40570b09774307e.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1638705958&t=2b31b638b2ca256f12794fa7b5e76ef1",
    //     name: "新建项目",
    //     url: "https://gitcode.net/codechina/operation-work/uploads/497f7a5e18fffed48e7059af16ef5d3b/image.png",
    //     type: 1
    //   },
    //   {
    //     icon: "http://img2.baidu.com/it/u=2689189425,1285948593&fm=253&app=138&f=JPEG?w=500&h=500",
    //     url: "https://gitcode.net/codechina/operation-work/uploads/8ad0dcbc201c3e7780395504986c9ad4/image.png",
    //     name: "Issue列表",
    //     type: 2
    //   },
    //   {
    //     icon: "http://img0.baidu.com/it/u=4290061247,3369746211&fm=253&app=138&f=JPEG?w=450&h=450",
    //     name: "新建笔记",
    //     url: "https://gitcode.net/codechina/operation-work/uploads/3d7d50bfbaf7f329f75342650fa2b0f6/image.png",
    //     type: 3
    //   }
    // ]
    // },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/f6ec2e6ee20fe198f81cf620413bc35b.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "携程网",
      url: "https://www.ctrip.com/",
      showTag: true,
      tag: "hot"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/37d396f9975e494b10ac8696d64ebb2a.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "Youtube",
      url: "http://www.youtube.com",
      showTag: true,
      tag: "hot"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/11ad5726053067fa842833ff0529b680.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "Github",
      url: "http://www.github.com",
      showTag: true,
      tag: "git"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/24982e111c555d3a4afc44981627925f.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "知乎",
      url: "https://www.zhihu.com/",
      showTag: true,
      tag: "知乎"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/2fc65bd66987ba1596324d55c01bddd7.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "微信",
      showTag: true,
      url: "https://wx.qq.com/",
      tag: "23"
    },
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/8061c93a71355024e801820969e2ecff.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "百度网盘",
      showTag: true,
      url: "https://pan.baidu.com/",
      tag: "100TB"
    }
  ],
  uninstalls: [
    {
      icon: "https://infinityicon.infinitynewtab.com/user-share-icon/65e5f9e7f4f0023ed9c04dd2af62aa1b.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim",
      name: "翻译",
      showTag: true,
      url: "http://csdn.net",
      tag: "new"
    }
  ],
  searchOptions: [
    {
      key: "csdn",
      name: "CSDN",
      icon: "https://gitcode.net/uploads/-/system/group/avatar/42/0_csdn.png",
      path: "https://so.csdn.net/so/search?q="
    },
    {
      key: "baidu",
      name: "百度",
      icon: "https://img0.baidu.com/it/u=3653818396,394239711&fm=253&fmt=auto&app=120&f=PNG?w=200&h=200",
      path: "https://www.baidu.com/s?&wd="
    },
    {
      key: "git",
      name: "GitCode",
      icon: "https://codechina-uploads.obs.cn-north-4.myhuaweicloud.com/appearance/favicon/1/icon.png?response-content-disposition=inline%3B%20filename%3D%22icon.png%22%3B%20filename%2A%3DUTF-8%27%27icon.png&response-content-type=image%2Fpng&X-Amz-Expires=600&X-Amz-Date=20211215T032431Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=QK3ORGAKW2CFPLGKCDJI%2F20211215%2Fcn-north-4%2Fs3%2Faws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=811e18ba658bc6fbd9a01f926daba12e4c4ce6f92abd9bffc808f953715bc20b",
      path: `file://${__static}/plugins/gitcode/index.html?`
      // path: path.resolve(__dirname, `../../../../static/plugins/gitcode/index.html`)
    },
    {
      key: "demo",
      name: "词典demo",
      icon: "https://codechina.csdn.net/uploads/-/system/project/avatar/39/logo-1-s.png?width=108",
      path: `file://${__static}/plugins/demo/deep.html?`
      // path: path.resolve(__dirname, `../../../../static/plugins/gitcode/index.html`)
    }
  ],
  subPlaceHolder: "",
  userInfo: { ...opConfig.get() }.userInfo,
  webviewPath: "",
  pluginLoading: true,
  pluginInfo: (() => {
    try {
      return window.pluginInfo || {};
    } catch (e) {}
  })()
};

const getters = {
  dingApp(state, getters) {
    return [
      ...state.devPlugins.filter(plugin => {
        return plugin.ding === true;
      })
    ];
  }
};

const mutations = {
  changeMode(state, val) {
    state.mode = val;
  },
  changeUpdateBadge(state, val) {
    state.showUpdateBadge = val;
  },
  uninstallApp(state, index) {
    state.installs.splice(index, 1);
  },
  installApp(state, app) {
    state.installs.push(app);
  },
  saveUninstalls(state, val) {
    state.uninstalls.push(val);
  },
  removeUninstalls(state, index) {
    state.uninstalls.splice(index, 1);
  },
  setUserInfo(state, info) {
    state.userInfo = info;
  },
  changeWebviewPath(state, path) {
    state.webviewPath = path;
  },
  commonUpdate(state, payload) {
    Object.keys(payload).forEach(key => {
      state[key] = payload[key];
      if (key === "devPlugins") {
        sysFile.savePlugins(payload[key]);
      }
    });
  },
  setSubPlaceHolder(state, payload) {
    state.subPlaceHolder = payload;
  },
  deleteDevPlugin(state, payload) {
    state.devPlugins = state.devPlugins.filter(
      plugin => plugin.name !== payload.name
    );
    sysFile.savePlugins(state.devPlugins);
  },
  dingProdPlugin(state, { payload, status }) {
    state.devPlugins.forEach(plugin => {
      if (plugin.name === payload.name) {
        plugin.ding = status;
      }
    });
    state.devPlugins = [...state.devPlugins];
    sysFile.savePlugins(state.devPlugins);
  },
  deleteProdPlugin(state, payload) {
    state.devPlugins = state.devPlugins.filter(
      plugin => plugin.id !== payload.id
    );
    sysFile.savePlugins(state.devPlugins);
    // todo 删除 static 目录下的对应插件
  },
  devPluginStatusChange(state, payload) {
    state.devPlugins.forEach(plugin => {
      if (plugin.name === payload.name) {
        plugin.status = !plugin.status;
      }
    });
    state.devPlugins = [...state.devPlugins];
    sysFile.savePlugins(state.devPlugins);
  }
};

const actions = {
  showMainUI({ commit, state }, payload) {
    ipcRenderer.send("changeWindowSize-rubick", {
      height: getWindowHeight()
    });
    setTimeout(() => {
      commit("commonUpdate", {
        showMain: true,
        selected: {
          key: "market",
          name: "插件中心"
        }
      });
    }, 50);
  },
  reloadDevPlugin({ commit }, payload) {
    const config = JSON.parse(
      fs.readFileSync(path.join(payload.sourceFile, "../plugin.json"), "utf-8")
    );
    const pluginConfig = {
      ...config,
      sourceFile: path.join(payload.sourceFile, `../${config.main}`)
    };
    const devPlugins = [...state.devPlugins];
    commit("commonUpdate", {
      devPlugins: devPlugins.map(plugin => {
        if (plugin.name === payload.name) {
          return {
            ...plugin,
            ...pluginConfig
          };
        }
        return plugin;
      })
    });
  },
  /**
   * @param {Object} payload payload.filePath为配置文件的绝对路径。payload.value为搜索栏文字值。
   */
  async onSearch({ commit, getters }, payload) {
    if (state.selected && state.selected.key !== "plugin-container") {
      commit("commonUpdate", { searchValue: "" });
      return;
    }
    const value = payload.value;
    // 在插件界面不触发其他功能
    if (
      (state.selected && state.selected.key === "plugin-container") ||
      payload.searchType === "subWindow"
    ) {
      commit("commonUpdate", { searchValue: value });
      return;
    }
    const fileUrl =
      payload.filePath ||
      clipboard.read("public.file-url").replace("file://", "");
    commit("commonUpdate", { searchValue: value });
    // 复制文件
    if (payload.filePath || (fileUrl && value === "plugin.json")) {
      const config = JSON.parse(fs.readFileSync(fileUrl, "utf-8"));

      const pluginConfig = {
        ...config,
        sourceFile: path.join(fileUrl, `../${config.main || "index.html"}`),
        id: uuidv4(),
        type: "dev",
        icon: "image://" + path.join(fileUrl, `../${config.logo}`),
        subType: (() => {
          if (config.subType) return config.subType;
          if (config.main) {
            return "";
          }
          return "template";
        })()
      };
      commit("commonUpdate", {
        selected: {
          key: "plugin",
          name: "plugin.json"
        },
        searchValue: "",
        options: [
          {
            name: "新建rubick开发插件",
            value: "new-plugin",
            icon: "https://static.91jkys.com/activity/img/b37ff555c748489f88f3adac15b76f18.png",
            desc: "新建rubick开发插件",
            click: router => {
              commit("commonUpdate", {
                showMain: true,
                devPlugins: [pluginConfig, ...state.devPlugins],
                selected: {
                  key: "plugin",
                  name: "新建rubick开发插件"
                },
                current: ["dev"]
              });
              ipcRenderer.send("changeWindowSize-rubick", {
                height: getWindowHeight()
              });
              router.push("/home/dev");
            }
          },
          {
            name: "复制路径",
            desc: "复制路径",
            value: "copy-path",
            icon: "https://static.91jkys.com/activity/img/ac0d4df0247345b9a84c8cd7ea3dd696.png",
            click: () => {
              clipboard.writeText(fileUrl);
              commit("commonUpdate", {
                showMain: false,
                selected: null,
                options: []
              });
              ipcRenderer.send("changeWindowSize-rubick", {
                height: getWindowHeight([])
              });
              remote.Notification("Rubick 通知", { body: "复制成功" });
            }
          }
        ]
      });
      // 调整窗口大小
      ipcRenderer.send("changeWindowSize-rubick", {
        height: getWindowHeight(state.options)
      });
      return;
    }

    let options = [];

    // check 是否是插件
    if (value) {
      state.devPlugins.forEach(plugin => {
        // dev 插件未开启
        if (plugin.type === "dev" && !plugin.status) return;
        const feature = plugin.features;
        feature.forEach(fe => {
          const cmds = searchKeyValues(fe.cmds, value);
          options = [
            ...options,
            ...cmds.map(cmd => ({
              name: cmd,
              value: "plugin",
              icon: plugin.sourceFile
                ? "image://" + path.join(plugin.sourceFile, `../${plugin.logo}`)
                : plugin.logo,
              desc: fe.explain,
              type: plugin.type,
              click: router => {
                actions.openPlugin(
                  { commit },
                  { cmd, plugin, feature: fe, router }
                );
              }
            }))
          ];
        });
      });

      let descMap = new Map();
      options = [
        ...options,
        ...fileLists
          .filter(plugin => {
            if (!descMap.get(plugin)) {
              descMap.set(plugin, true);
              let has = false;
              plugin.keyWords.some(keyWord => {
                if (
                  keyWord
                    .toLocaleUpperCase()
                    .indexOf(value.toLocaleUpperCase()) >= 0
                ) {
                  has = keyWord;
                  plugin.name = keyWord;
                  return true;
                }
                return false;
              });
              return has;
            } else {
              return false;
            }
          })
          .map(plugin => {
            plugin.click = () => {
              actions.openPlugin({ commit }, { plugin });
            };
            return plugin;
          })
      ];

      descMap = null;
    }

    commit("commonUpdate", {
      options
    });
    ipcRenderer.send("changeWindowSize-rubick", {
      height: getWindowHeight(state.options, getters.dingApp)
    });
  },
  async downloadPlugin({ commit }, payload) {
    const distUrl = await downloadZipFromGitCode(
      payload.downloadUrl,
      payload.name
    );
    // const distUrl = await downloadZip(payload.downloadUrl, payload.name);
    const fileUrl = find(distUrl);

    // 复制文件
    const config = JSON.parse(
      fs.readFileSync(`${fileUrl}/plugin.json`, "utf-8")
    );
    const pluginConfig = {
      ...config,
      id: uuidv4(),
      sourceFile: `${fileUrl}/${config.main}`,
      type: "prod",
      icon: payload.logo,
      subType: (() => {
        if (config.main) {
          return "";
        }
        return "template";
      })()
    };
    commit("commonUpdate", {
      devPlugins: [pluginConfig, ...state.devPlugins]
    });
  },
  async updatePlugin({ commit }, payload) {
    const distUrl = await downloadZipFromGitCode(
      payload.downloadUrl,
      payload.name
    );
    // const distUrl = await downloadZip(payload.downloadUrl, payload.name);
    const fileUrl = find(distUrl);

    // 复制文件
    const config = JSON.parse(
      fs.readFileSync(`${fileUrl}/plugin.json`, "utf-8")
    );
    const pluginConfig = {
      ...config,
      id: uuidv4(),
      sourceFile: `${fileUrl}/${config.main}`,
      type: "prod",
      icon: payload.logo,
      subType: (() => {
        if (config.main) {
          return "";
        }
        return "template";
      })()
    };
    const devPlugins = state.devPlugins;

    const index = devPlugins.findIndex(plugin => {
      return plugin.name === pluginConfig.name;
    });

    console.log(index, devPlugins, pluginConfig);

    if (index !== -1) {
      devPlugins[index] = pluginConfig;
    }
    commit("commonUpdate", {
      devPlugins: devPlugins
    });
  },
  openPlugin({ commit }, { cmd, plugin, feature, router, payload }) {
    if (plugin.type === "app") {
      execSync(plugin.action);
      commit("commonUpdate", {
        selected: null,
        showMain: false,
        options: [],
        searchValue: ""
      });
      ipcRenderer.send("changeWindowSize-rubick", {
        height: getWindowHeight([])
      });
      return;
    }
    commit("commonUpdate", {
      selected: {
        key: "plugin-container",
        name: cmd.label ? cmd.label : cmd,
        icon: "image://" + path.join(plugin.sourceFile, `../${plugin.logo}`)
      },
      searchValue: "",
      showMain: true
    });
    ipcRenderer.send("changeWindowSize-rubick", {
      height: getWindowHeight()
    });
    if (plugin.type === "system") {
      systemMethod[plugin.tag][feature.code]();
      commit("commonUpdate", {
        selected: null,
        showMain: false,
        options: []
      });
      ipcRenderer.send("changeWindowSize-rubick", {
        height: getWindowHeight([])
      });
      router.push({
        path: "/home"
      });
      return;
    }
    commit("commonUpdate", {
      pluginInfo: {
        cmd,
        ...plugin,
        detail: feature,
        payload
      }
    });

    router.push({
      path: "/plugin",
      query: {
        ...plugin,
        _modify: Date.now(),
        detail: JSON.stringify(feature)
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
