<template>
  <div class="softwareDetail">
    <!-- <span>{{aa}}</span> -->
    <el-row :gutter="20" :style="{ height: menuHeight + 'px' }" style="overflow: hidden">
      <el-col :span="4" class="modulesTree height100" v-if="!isMode" style="padding-right: 0;">
        <div class="height100">
          <div class="br-2">
            <div class="pt-2 topSoft pointer">
              <el-button type="primary" icon="el-icon-s-home" circle size="mini" @click="switchTab"></el-button>
              <span style='font-size:14px;padding-left:5px;'  @click="switchTab">{{appName}}</span>
              <i @click="createModules" class="el-icon-plus addModule d-none"></i>
            </div>
          </div>
          <el-scrollbar class="br-2" style='height:calc(100% - 40px)' :native="false" ref="homeScroll">
            <el-tree 
            :props="props" 
            lazy :load="loadNode" 
            :expand-on-click-node="false" 
            @node-click="onClickNode"
            class="relative"
            v-loading="loading"
            :element-loading-text="$t('home.loading')"
            element-loading-spinner="el-icon-loading"
            ref="homeTree"
            highlight-current
            @node-expand="nodeExpand"
            @node-collapse="nodeCollapse"
            node-key="id"
            :default-expanded-keys="defaultExpandKey"

            >
              <span class="smallfont custom-tree-node" slot-scope="{ node, data }">
                <span 
                  :title="data.name" 
                  class="textTree" 
                  :style="{width: treeWidth + 'px', fontWeight: treeId == data.id ? 'bolder': 'normal'}">
                  <i :class='getTreeImg(node)' style="color:#409EFF;padding-right:5px;"></i>
                  {{data.name}}
                </span>
                <div>
                  <span @click="addModules(data.id)">
                    <i class="addModule el-icon-plus d-none" style="position:absolute;right:20px;line-height:5px;color:#409EFF;padding-right:8px;"></i>
                  </span>
                  <span @click="delectModules(data.id)">
                    <i class="delModule el-icon-delete d-none" style="position:absolute;right:10px;line-height:5px;color:#409EFF;"></i>
                  </span>
                </div>
              </span>
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="moduleCol">
        <div v-if="!visible">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane :label="$t('tabs.basic_info')" name="basicInfor"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.general_tools')" name="commonTool"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.advanced_tools')" name="advancedTool"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.library')" name="library" v-if="!isMode"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.multilanguage')" name="multiLanguage" v-if="!isMode"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.cb_info')" name="cbInfo" v-if="isMode"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.work_flow')" name="process" v-if="isMode"></el-tab-pane>
          </el-tabs>
        </div>
        <div v-if="visible">
          <el-tabs v-model="active" type="card" @tab-click="handleTabClick">
            <el-tab-pane :label="$t('tabs.basic_info')" name="basicInfor"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.form')" name="form"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.view')" name="view"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.work_flow')" name="process"></el-tab-pane>
            <!-- <el-tab-pane label="交叉报表" name="crossReport"></el-tab-pane> -->
            <el-tab-pane :label="$t('tabs.chart')" name="charts"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.report')" name="report"></el-tab-pane>
            <el-tab-pane :label="$t('tabs.page')" name="page"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="rightSoftHeight">
          <router-view></router-view> 
        </div>
      </el-col>
    </el-row>
    <div>
      <el-dialog :title="$t('module.new_module')" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
        <span>
          <el-form :model="params" ref="params" :rules="rules" label-position="right" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('module.name')" prop="name">
                  <el-input v-model="params.name" :placeholder="$t('placeholder.module_name')" size="small" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('module.superior_module')">
                  <el-select v-model="params.superior" size="small" :placeholder="$t('placeholder.select')">
                    <el-option v-for="item in data" :key="item.id" :label="item.value" :value="item.id"> </el-option>
                  </el-select>
                  <!-- <el-input v-model="params.superior" :placeholder="$t('placeholder.name')" size="small" clearable></el-input> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('module.module_description')">
                  <el-input v-model="params.description" type="textarea" :rows="2" :placeholder="$t('placeholder.description')" size="small" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('module.module_ordernumber')">
                  <el-input-number v-model="params.orderNo" :min="0" :max="10000000" size="small" :precision="0" :step="1"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="handleClose">{{$t('btns.cancel')}}</el-button>
          <el-button type="primary" size="small" @click="handleModules('params')" :loading="btnLoading">{{$t('btns.confirm')}}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getModulesTree, getAllmodules, getModulesBasicInfo, delectModules, getApplications } from "@/service/CommonApi.js";
import { mapState } from 'vuex';
import { nameCheck } from "@/utils/utils.js";
import {delMsg} from '@/utils/elementui'
export default {
  name: "softwsaredetails",
  data() {
    return {
      loading: true,
      num:1,
      activeName: "basicInfor",
      active: "basicInfor",
      props: {
        label: "name",
        children: "zones",
        isLeaf: "hasChild",
      },
      node: [],
      resolve: function() {},
      visible: false,
      dialogVisible: false,
      params: {
        appId: "",
        id: "",
        name: "",
        description: "",
        superior: "",
        superiorName: "",
        orderNo: 0,
        type:0,
      },
      rules: {
        name: [
          { required: true, message: '请输入模块名称', trigger: "blur" },
          { validator: nameCheck, trigger: "blur" },
        ],
      },
      data: [],
      menuHeight: 0,
      test:10,
      isFirst:true,//标识是否第一次create
      appName:sessionStorage.getItem("appName"),
      moduleCol:20,//用来标识右边的选项卡页签的占比，平台模式是24
      isMode:false,//标识是否是平台模式
      datasourceId: "", // 用于判断当前有没有数据源
      btnLoading: false, // 是否显示可用
      treeWidth: 120, // 动态加载树的宽度
      treeId: '', // 左侧树节点id

      defaultExpandKey: [], // 默认展开的树节点
      barScrollTop: 0, // 重新加载后滚动条的高度
    };
  },
  created() {
    let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    //60 头部， 32 面包屑， 20 父组件外边距
    // this.menuHeight = clientHeight - 60 - 32 - 36 - 20;
    this.menuHeight = clientHeight - 60 - 32;

    let appId = sessionStorage.getItem("appId");
    if (appId == "") {
      appId = sessionStorage.getItem("appId");
      let appName = sessionStorage.getItem("appName");
      this.$emit("breadcrumbName", appName);
      let params = {
        appId: appId,
        appName: appName,
      };
      this.$store.dispatch("landingUser", { params });
    }
    if(JSON.parse(sessionStorage.getItem('software')).type == 1){
      this.moduleCol=24;
      this.isMode=true;
      this.$forceUpdate();
    }
    this.initRouter();


    this.getApplication()
  },
  computed:mapState({
    isReloadTree(state){
      return state.isReloadTree;
    }
  }),
  mounted() {
    this.getAllmodules();
      this.$nextTick(() => {
          if(JSON.parse(sessionStorage.getItem('software')).type != 1){
              this.treeWidth = this.$refs.homeTree.$el.offsetWidth - 80
          }
       })
  },
  methods: {
    getTreeImg(node){
      let className="";
      if(node.isLeaf){
        className='el-icon-document'
      }else if(!node.expanded){
        className='el-icon-folder';
      }else{
        className='el-icon-folder-opened'
      }
      return className;
    },
    //重新加载左边模块树
    reloadTree(){
      this.node.childNodes = [];
      this.loadNode(this.node,this.resolve);
      this.$store.commit('changeIsReloadTree',false);

      setTimeout(() => {
        this.$refs.homeScroll.$el.children[0].scrollTo({
          top: this.barScrollTop,
          left: 0,
          behavior: 'smooth' // 定义缓动动画
        })
      }, 1000)
    },
    /**
     * 初始化打开该模块的基本信息
     */
    initRouter() {
      this.$router.replace({ path: "/home/softwaresdetails/baseicinfor", query: { edit: true} });
    },

    /**
     * 主页-切换页签
     */
    switchTab() {
      this.visible = false;
      this.activeName = 'basicInfor'
      this.initRouter();
    },

    /**
     * **获取树形结构所有模块列表**
     */
    async getAllmodules() {
      let appId = sessionStorage.getItem('appId');
      let currentModuleId = ""
      this.loading = true
      let response = await getAllmodules(appId, currentModuleId);
      if (response.data.errcode == 0) {
        this.loading = false
        this.data = response.data.data;
      }
    },

    /**
     * 当前选中的页签
     */
    handleClick(tab) {
      if (tab.name == "advancedTool") {
        this.$store.dispatch("rightHelpPageParams", { title: "开发者列表", url: "application/application_info_advancedTools_developer_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/advancedTool/developer", query: { edit: true} });
        this.$store.commit('changeIsClickPrimaryTab','developer' + new Date().getTime());
      } else if (tab.name == "commonTool") {
        this.$store.dispatch("rightHelpPageParams", { title: "角色列表", url: "application/application_info_generalTools_role_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/commontool/roleslist", query: { edit: true} });
        this.$store.commit('changeIsClickPrimaryTab','roleslist' + new Date().getTime());
      } else if (tab.name == "library") {
        this.$store.dispatch("rightHelpPageParams", { title: "函数库列表", url: "application/application_info_libraries_macroLibs_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/library/macroLibsList", query: { edit: true} });
        this.$store.commit('changeIsClickPrimaryTab','macroLibs' + new Date().getTime());
      } else if (tab.name == "multiLanguage") {
        this.$store.dispatch("rightHelpPageParams", { title: "多语言列表", url: "domain/domain_multiLanguages_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/multiLanguageList", query: { edit: true} });
      }else if (tab.name == "cbInfo") {
        //平台模式的回调信息没有帮助页面
        this.$store.dispatch("rightHelpPageParams", { title: "流程列表", url: "application/application_module_workflows_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/cbInfo", query: { edit: true} });
      }else if (tab.name == "process") {
        this.$store.dispatch("rightHelpPageParams", { title: "流程列表", url: "application/application_module_workflows_list_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/processlist", query: { edit: true} });
      } else {
        this.$store.dispatch("rightHelpPageParams", { title: "软件信息", url: "application/application_info_help.html" });
        this.$router.replace({ path: "/home/softwaresdetails/baseicinfor", query: { edit: true} });
        
      }
    },
    //右边树的加号新建模块
    addModules(id){
      /**
       * 刷新丢失appId
       */
      if(!this.params.appId){
        this.params.appId = sessionStorage.getItem('appId')
      }
      this.params.superior=id;
      this.createModules();
    },

    /**
     * 新建模块
     */
    createModules() {
     // this.getAllmodules();
      // 需要判断有没有配置数据源，没有配置数据源不能报错
      this.getApplication()
      this.dialogVisible = true;
    },

    getApplication(){
      getApplications({id: sessionStorage.getItem("appId")}, {
        onSucess: response => {
          if (response.data.errcode == 0) {
            let data = response.data.data;
            this.datasourceId = data.datasourceId
          }
        }
      });
    },

    /**
     * 确定新建模块
     */
    handleModules(params) {
      /**
       * 刷新丢失appId
       */
      if(!this.params.appId){
        this.params.appId = sessionStorage.getItem('appId')
      }
      // 判断有没有数据源
      if(!this.datasourceId){
        this.$message.error(this.$t('msg.set_datasource'))
        return false
      }
      this.$refs[params].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const response = await getModulesBasicInfo(this.params);
          if (response.data.errcode == 0) {
            //把存起来的node的子节点清空，不然会界面会出现重复树！
            this.node.childNodes = [];
            let node = this.node;
            let resolve = this.resolve;
            this.loadNode(node, resolve);
            this.handleClose();
            this.getAllmodules();
            this.$message.success(this.$t('msg.created_ss'));
            this.btnLoading = false;
          }
        } else {
          return false;
        }
      });
    },

    /**
     * 取消新建模块
     */
    handleClose() {
      let params = {
        ...this.params,
        id: "",
        name: "",
        description: "",
        superior: "",
        superiorName: "",
        orderNo: 0,
      };
      this.params = params;
      this.dialogVisible = false;
      // this.$refs['params'].resetFields()
    },

    /**
     * 删除节点
     */
    async delectModules(data) {
      try{
        await delMsg(this.$t('msg.del_module'), this.$t('msg.tip'))
        const response = await delectModules([data])
        if (response.data.errcode == 0) {
          this.node.childNodes = [];
          let node = this.node;
          let resolve = this.resolve;
          this.loadNode(node, resolve);
          this.visible = false;
          this.initRouter();
          this.$message({
            message: this.$t('msg.del_ss'),
            type: "success",
          });
        }
      }catch(e){
        console.log(e)
      }
    },

    /**
     * 加载树下级
     */
    async loadNode(node, resolve) {
      let appId = sessionStorage.getItem("appId");
      let parentId = node.data != undefined ? node.data.id : "";
      let data = [];
      if (node.level === 0) {
        this.node = node;
        this.resolve = resolve;
        const response = await getModulesTree(appId, parentId);
        if (response.data.errcode == 0) {
          data = response.data.data ? response.data.data : [];
          if (node.data != undefined) {
            return resolve([{ name: node.data.name }]);
          }
          return resolve(data);
        }
      }
      if (node.level >= 1) {
        const response = await getModulesTree(appId, parentId);
        if (response.data.errcode == 0) {
          data = response.data.data ? response.data.data : [];
          if (node.data != undefined) {
            return resolve(data);
          }
        }
      }
    },

    /**
     * 点击模块树节点
     * 传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身
     */
    onClickNode(data) {
      this.$store.dispatch("rightHelpPageParams", { title: '模块信息', url: "application/application_module_form_list_help.html" });
      this.visible = true;
      this.active = "basicInfor";
      // 存储用于当前的id有其他样式
      this.treeId = data.id
      this.$router.push({ path: "/home/softwaresdetails/basicinfor", query: { edit: true, moduleId: data.id} });
    },

    /**
     * 模块树节点展开时触发的事件
     */
    nodeExpand(data){
      this.defaultExpandKey.push(data.id)
    },

    /**
     * 模块树节点关闭是触发的事件
     */
    nodeCollapse(data){
      for(let i = 0; i < this.defaultExpandKey.length; i++){
        if(this.defaultExpandKey[i] == data.id){
          this.defaultExpandKey = [...this.defaultExpandKey.slice(0, i), ...this.defaultExpandKey.slice(i + 1)]
          break;
        }
      }
    },

    /**
     * 模块节点下的页签切换
     */
    handleTabClick(tab) {
      let moduleId = this.$route.query.moduleId;
      if (tab.name == "form") {
        this.$store.dispatch("rightHelpPageParams", { title: "表单列表", url: "application/application_module_form_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/formlist", query: { edit: true, moduleId: moduleId} });
        this.$store.commit("changeformDetailVisible", false);
      } else if (tab.name == "view") {
        this.$store.dispatch("rightHelpPageParams", { title: "视图列表", url: "application/application_module_view_list_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/viewlist", query: { edit: true, moduleId: moduleId} });
        this.$store.commit("changeviewDetailVisible", false);
      } else if (tab.name == "process") {
        this.$store.dispatch("rightHelpPageParams", { title: "流程列表", url: "application/application_module_workflows_list_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/processlist", query: { edit: true, moduleId: moduleId} });
        this.$store.commit("changeprocessDetailVisible", false);

      } else if (tab.name == "charts") {
        this.$store.dispatch("rightHelpPageParams", { title: "当前页Not帮助", url: "application/application_module_info_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/chartslist", query: { edit: true, moduleId: moduleId} });
      } else if (tab.name == "report") {
        this.$store.dispatch("rightHelpPageParams", { title: "打印列表", url: "application/application_module_print_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/reportslist", query: { edit: true, moduleId: moduleId} });
      } else if(tab.name == 'page'){
        this.$store.dispatch("rightHelpPageParams", { title: "当前页Not帮助", url: "application/application_module_info_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/pagelist", query: { edit: true, moduleId: moduleId} });
      } else {
        this.$store.dispatch("rightHelpPageParams", { title: "模块信息", url: "application/application_module_form_list_help.html" });
        this.$router.push({ path: "/home/softwaresdetails/basicinfor", query: { edit: true, moduleId: moduleId} });
      }
    },
  },
  watch: {
    isReloadTree(){
      if(this.$store.state.isReloadTree){
        this.reloadTree();
        console.log(this.$refs.homeScroll.$el.children[0].scrollTop, 'scrollTop')
        // 记住原来展开的节点id，重新加载后也展开当前的树节点
        this.barScrollTop = this.$refs.homeScroll.$el.children[0].scrollTop
      }
    },
    "$store.state.rightHelpPageParams": {
      handler() {
        if (this.$store.state.rightHelpFrame) {
          this.$store.state.rightHelpFrame.contentWindow.showHelpContentHtml(this.$store.state.rightHelpPageParams.title, this.$store.state.rightHelpPageParams.url);
        }
      },
      deep: true,
    },
    /**
     * 检测浏览器回测时使用(一般的跳转也会执行该方法)
     */
    "$route"(to, from){
      switch(to.name){
        case "baseicinfor":
          this.activeName = "basicInfor";
          this.visible = false;
          break;
        case "roleslist":
          this.activeName = "commonTool";
          break;
        case "pcMenu":
          this.activeName = "commonTool";
          break;
        case "mobileMenu":
          this.activeName = "commonTool";
          break;
        case "tasklist":
          this.activeName = "commonTool";
          break;
        case "widgetlist":
          this.activeName = "commonTool";
          break;
        case "developer":
          this.activeName = "advancedTool";
          break;
        case "excelConf":
          this.activeName = "advancedTool";
          break;
        case "eip":
          this.activeName = "advancedTool";
          break;
        case "dataSourceList":
          this.activeName = "advancedTool";
          break;
        case "metadataMgr":
          this.activeName = "advancedTool";
          break;
        case "macroLibsList":
          this.activeName = "library";
          break;
        case "styleLibsList":
          this.activeName = "library";
          break;
        case "validateLibsList":
          this.activeName = "library";
          break;
        case "multiLanguageList":
          this.activeName = "multiLanguage";
          break;
        case "basicinfor":
          this.active = "basicInfor";
          break;
        case "formlist":
          this.active = "form";
          break;
        case "viewlist":
          this.active = "view";
          break;
        case "processlist":
          this.active = "process";
          break;
        case "chartslist":
          this.active = "charts";
          break;
        case "reportslist":
          this.active = "report";
          break;
        case "pagelist":
          this.active = "page";
          break;
        default: 
          break;
      }
    }
  },
};
</script>