<template>
  <div v-loading="loading">
    <div class="obpm-title"  v-if="type == 'list'">
      <div class="d-inline-block">
        <i class="el-icon-folder title-icon"></i>
        <div class="title-name d-inline-block ml-2">{{$t('flow.title')}}</div>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" plain size="small" @click="copyProcess"
          >{{$t("btns.copy")}}</el-button
        >
        <el-button type="primary" size="small" @click="newProcess"
          >{{$t("btns.new")}}</el-button
        >
        <el-button type="danger" plain size="small" @click="showDeleteConfirm"
          >{{$t("btns.delete")}}</el-button
        >
      </div>
    </div>
    <div class="obpm-content mt-2 " v-if="type == 'list'">
      <div class="search">
        <el-form
          ref="form"
          :inline="true"
          :model="searchParams"
          class="demo-form-inline"
          size="mini" @submit.native.prevent
        >
          <el-form-item>
            <el-input
              v-model="searchParams.name"
              :placeholder="$t('placeholder.name')"
              @keyup.enter.native="getProcessList"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getProcessList" type="primary" plain>{{$t("btns.query")}}</el-button>
            <el-button @click="resetName">{{$t("btns.reset")}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="obpm-content-table">
        <template>
          <el-table
            ref="tableList"
            :data="data.data"
            @selection-change="handleSelectionChange"
            @cell-click='onRowClick'
            :height="tableHeight"
            style="width: 100%"
            size='small'
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="name" :label="$t('flow.name')"> </el-table-column>
            <el-table-column prop="id" :label="$t('flow.id')"></el-table-column>
          </el-table>
        </template>
        <el-pagination
          class="text-right pt-1"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNo"
          :page-sizes="[10, 25, 50, 100]"
          :page-size="10"
          background
          layout="total, prev, pager, next, sizes"
          :total="data.rowCount"
        >
        </el-pagination>
      </div>
    </div>
    <div v-else>
      <iframe
        ref="flowDetail"
        :src="src"
        width="100%"
        :height="iframeHeight"
        frameborder="0"
        :style="iframeStyle"
      ></iframe>
    </div>
  </div>
</template>
<script>
import {
  getModuleProcessList,
  deleteWorkflows,
  copyProcess,
  getContextPath,
  getStaticPath
} from "@/service/ModulesApi.js";
import {delMsg} from '@/utils/elementui'
export default {
  name: "processlist",
  data() {
    return {
      loading: false,
      vueId:'processList',
      searchParams: {
        appId: "",
        moduleId: "",
        name: "",
        pageNo: 1,
        linesPerPage: 10,
      },
      params: {
        id: "",
        name: "",
        authorname: "",
        lastmodify: "",
        subject: "",
        flow: ""
      },
      data: {},
      multipleSelectionId: [],
      multipleSelectionArray: [],
      tableHeight: 100,
      iframeHeight: 100,
      type: "list",
      contextPath:getContextPath(),
      staticPath: getStaticPath(),
      src:'./processHtml/processHtmlTem.html',
      spanClick: 'handleSpanClick',
      iframeStyle:'',//iframe全屏样式
      iframeHeightBefore:100,
    };
  },
  created(){
    window[this.vueId]=(result)=>{
      if(result &&result!='exit'){
        let re=JSON.parse(result);
        if(re.errcode==0){
          this.$message({
            message: this.$t('msg.ss'),
            type: "success"
          });
        }else{
          this.$message({
            message: re.errmsg,
            type: "error"
          });
        }
      }else if(result=='exit'){
        this.src='./processHtml/processHtmlTem.html';
        this.type='list';
        this.$store.commit("changeprocessDetailVisible", false);

        this.getProcessList();
      }else{
        this.$message({
          message: this.$t('msg.sf'),
          type: "error"
        });
        // this.src='./processHtml/processHtmlTem.html';
        // this.type='list';
        // this.getProcessList();
      }
      
    },
    //操作iframe的全屏事件
    window[this.spanClick]=(isScresn)=>{
      this.allScrean(isScresn);
    }
  },
  mounted() {
    this.getScollerHeight();
    let appId = sessionStorage.getItem("appId");
    console.log("flowList",appId)
    let moduleId = JSON.parse(sessionStorage.getItem('software')).type != 1 ? this.$route.query.moduleId : sessionStorage.getItem('appId');
    let searchParams = {
      ...this.searchParams,
      appId: appId,
      moduleId: moduleId
    };

    this.searchParams = searchParams;
    this.getProcessList();
    let flowDetail = this.$refs["flowDetail"];
    if (flowDetail) {
      if (flowDetail.attachEvent) {
        //兼容浏览器判断
        flowDetail.attachEvent("onload", function() {
          let iframeWin = flowDetail.contentWindow;
          iframeWin.postMessage(data, "*");
          //data传递的参数   *写成子页面的域名或者是ip
        });
      } else {
        flowDetail.onload = function() {
          let iframeWin = flowDetail.contentWindow;
          iframeWin.postMessage(data, "*");
        };
      }
    }
  },

  methods: {
    //iframe全屏事件
    allScrean(isScresn){
      if(isScresn){
        this.iframeStyle='position:absolute;top:0;left:0;right:0;bottom:0;z-index:10';
        this.iframeHeight='100%';
        let timer = setTimeout(()=>{
          this.$refs["flowDetail"].contentWindow.caclcuHeight();
          clearTimeout(timer)
        },100)
      }else{
        this.iframeStyle='';
        this.iframeHeight=this.iframeHeightBefore;
        let timer = setTimeout(()=>{
          // this.$refs["flowDetail"].contentWindow.caclcuHeight();
          clearTimeout(timer)
        },100)
      }
    },
    newProcess() {
      // 清空原有的流程id
      window.parent["processList"]("exit")
      this.type = "new";
      this.$store.commit("changeprocessDetailVisible", true);

      this.src=this.src+'?contextPath='+this.contextPath+"&staticPath="+this.staticPath+"&moduleId="+this.searchParams.moduleId+"&applicationId="+sessionStorage.getItem("appId");

    },
    iframeExit(){
      this.type='list';
      this.$store.commit("changeprocessDetailVisible", false);

    },
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 50 列表标题， 71 查询， 20 父组件外边距, 40分页
        this.tableHeight =
          clientHeight - 60 - 32 - 41 - 50 - 71 - 20 - 40 + "px";
        this.iframeHeight = clientHeight - 60 - 32 - 41  + "px";
        this.iframeHeightBefore = clientHeight - 60 - 32 - 41  + "px";

      }, 100);
    },

    /**
     * 获取表单列表
     */
    getProcessList() {
      getModuleProcessList(this.searchParams, {
        onSucess: response => {
          if (response.data.errcode == 0) {
            this.data = response.data.data;
          }
        }
      });
    },

    /**
     * 重置查询名称值
     */
    resetName() {
      let searchParams = {
        ...this.searchParams,
        name: ""
      };
      this.searchParams = searchParams;
      this.getProcessList();
    },

    /**
     * 勾选行时响应
     */
    handleSelectionChange(val) {
      let multipleSelectionId = [];
      if (val.length) {
        val.map(e => {
          multipleSelectionId.push(e.id);
        });
      }
      this.multipleSelectionArray = val;
      this.multipleSelectionId = multipleSelectionId;
    },

    /**
     * 删除角色
     */
    async showDeleteConfirm() {
      let multipleSelectionId = this.multipleSelectionId;
      if(multipleSelectionId.length > 0){
        try{
          await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
          this.loading = true;
          const response = await deleteWorkflows(multipleSelectionId);
          this.loading = false;
          if (response.data.errcode == 0) {
            this.getProcessList();
            this.$message.success(this.$t('msg.del_ss'));
          }
        }catch(e){
          console.log(e)
        }
      }else{
        this.$message.error(this.$t('msg.check_data'))
      }
    },

    /**
     * 当前页
     */
    handleCurrentChange(val) {
      let searchParams = {
        ...this.searchParams,
        pageNo: val
      };
      this.searchParams = searchParams;
      this.getProcessList();
    },

    /**
     * 切换分页，每页显示多少条
     */
    handleSizeChange(val) {
      let searchParams = {
        ...this.searchParams,
        linesPerPage: val
      };
      this.searchParams = searchParams;
      this.getProcessList();
    },

    /**
     * 选中数据源回显
     */
    onRowClick(row, column, cell){
      this.allScrean(false);
      if(cell.cellIndex == 2) 
        return false
      this.type='new';
      this.$store.commit("changeprocessDetailVisible", true);

      this.src=this.src+'?contextPath='+this.contextPath+"&staticPath="+this.staticPath+"&flowId="+row.id+"&moduleId="+this.searchParams.moduleId+"&applicationId="+sessionStorage.getItem("appId");
      
      // this.flowId=row.id;
      // let params = {
      //   ...this.params,
      //   id: row.id,               //角色id
      //   name: row.name,             //角色名称
      //   roleNo: row.roleNo,           //编号
      //   status: row.status,           //激活状态
      //   defaultRole: row.defaultRole,       //系统默认角色
      // }
      // this.$router.push({path: '/home/softwaresdetails/commontool/roles', query:{edit: true, params: params}});
    },

    /**
     * 复制流程
     */
    copyProcess() {
      let multipleSelectionId = this.multipleSelectionId;
      if (multipleSelectionId.length > 0) {
        this.loading = true
        copyProcess(multipleSelectionId, {
          onSucess: response => {
            this.loading = false
            if (response.data.errcode == 0) {
              this.getProcessList();
              this.$message({
                message: this.$t('msg.copy_ss'),
                type: "success"
              });
            }
          }
        });
      } else {
        this.$message({
          message: this.$t('msg.select_more')
        });
      }
    }
  },

  watch:{
    "$store.state.processDetailVisible"(){
      if(this.$store.state.processDetailVisible){
        this.type='new';
      }else{
        this.type='list';
      }
      this.getProcessList();

    }
  },

};
</script>
