<template>
  <div class="hello">
    <div class="box">
      <el-container>
        <el-aside width="180px"  >
          <div class="title">流程分类</div>
          <div class="left">
            <ul>
              <li style="cursor:pointer"   @click="changeCategroy(item.id)" v-for="item in processList"><i class="el-icon-s-order"></i>{{item.categoryName}}</li>
            </ul>
          </div>
        </el-aside>
        <el-main class="right">
          <div class="bgfff">
            <el-form :model="queryParams" ref="queryForm" :inline="true">
              <el-form-item label="流程名称:" prop="activitiName">
                <el-input
                  v-model="queryParams.activitiName"
                  placeholder="请输入要查询的关键字"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus"  @click="handleAdd()">新建流程</el-button>
                <el-button type="primary" icon="el-icon-plus"  @click="handleUpload()">导入模型</el-button>
              </el-form-item>
            </el-form>
          <!--  <el-row class="der">
              <el-button @click="handleQuery()">刷新</el-button>
              <el-button type="primary" @click="handleAdd()">添加模型</el-button>
              <el-button type="primary" @click="handleUpload()">导入模型（BPMN）</el-button>
              &lt;!&ndash;              <el-button>查看流程图</el-button>&ndash;&gt;
              &lt;!&ndash;              <el-button>查看流程(XML)</el-button>&ndash;&gt;
              &lt;!&ndash;              <el-button>查看流程(JSON)</el-button>&ndash;&gt;
              &lt;!&ndash;              <el-button>导出流程(BPMN)</el-button>&ndash;&gt;
              &lt;!&ndash;              <el-button>导入流程(BPMN)</el-button>&ndash;&gt;
            </el-row>-->
            <el-table
              border
              v-loading="loading"
              :data="modelerList"
              style="width: 100%;"
            >
              <el-table-column label="序号" type="index" align="center">
                <template slot-scope="scope">
                  <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="流程名称" align="center" prop="activitiName"/>
              <el-table-column label="流程分类" align="center" prop="activitiDeployId"/>
            <!--  <el-table-column label="流程定义" align="center" prop="resourceName" width="180">
                <template slot-scope="scope">
                  <el-link target="_blank" type="success" @click="viewFlowXML(scope.row)">
                    查看流程(XML)
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column label="流程图" align="center" prop="diagramResourceName" width="180">
                <template slot-scope="scope">
                  <el-link target="_blank" type="primary" @click="viewFlowChat(scope.row)">
                    查看流程图
                  </el-link>
                </template>
              </el-table-column>-->
              <el-table-column label="部署状态" align="center" prop="activitiDeployStatus" width="180">
                <template slot-scope="scope">
                  <el-tag
                    :type="formatStatus(scope.row.activitiDeployStatus)"
                    effect="dark">
                    {{ scope.row.activitiDeployStatus==='0'?'未部署':'已部署' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="运行状态" align="center" prop="activitiDeployStatus" width="180">
                <template slot-scope="scope" v-if="scope.row.processDefinition!=null">
                  <el-tag
                    :type="scope.row.processDefinition.suspendState ==='2'?'warning':''"
                    effect="dark">
                    {{scope.row.processDefinition.suspendStateName}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="activitiCreateTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTimeT(scope.row.activitiCreateTime) }}</span>
                </template>
              </el-table-column>
            <!--  <el-table-column label="最后更新时间" align="center" prop="activitiUpdateTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTimeT(scope.row.activitiUpdateTime) }}</span>
                </template>
              </el-table-column>-->

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:menu:edit']"
                  >修改
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-upload"
                    @click="handleDeploy(scope.row)"
                    v-hasPermi="['system:menu:add']"
                  >{{scope.row.activitiDeployStatus==='0'?'部署':'重新部署'}}
                  </el-button>
                  <el-button
                    v-if="scope.row.processDefinition!=null"
                    size="mini"
                    type="text"
                    icon="el-icon-switch-button"
                    @click="handleSuspendOrActiveApply(scope.row)"
                    v-hasPermi="['system:menu:add']"
                  >{{scope.row.processDefinition.suspendState === '2' ? '激活' : '挂起'}}
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row,scope.$index)"
                    v-hasPermi="['system:menu:remove']"
                  >删除
                  </el-button>

                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="data_association(scope.row.activitiKey)"
                  >业务关联
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getList"/>
          </div>
        </el-main>
      </el-container>
    </div>
    <el-dialog id="editModeler" title="修改流程" :visible.sync="editOpen" width="90%" top="10"
               @close="handleEditModelerDialogClose" fullscreen>
      <iframe :src="src" id="activiti_main" frameborder="no" :style="'width: 100%;height:'+ iframe.height"
              scrolling="auto"/>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".bpmn"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“*.bpmn”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 第一个业务关联 -->
    <el-dialog title="业务关联" :visible.sync="dialogVisible" width="1200px">
      <el-tabs :tab-position="tabPosition" style="min-height: 300px;">
        <el-tab-pane>
          <span slot="label"><i class="el-icon-date"></i> 业务关联</span>
          <el-button type="primary" icon="el-icon-plus" @click="addDatAassociation">新增</el-button>
        <br/>
          <el-table border :data="DataAssociation" >
            <el-table-column label="序号" type="index" width="130" align="center">

            </el-table-column>
            <el-table-column label="表名/自定义表单编号" width="180" align="center" prop="tablename"/>
            <el-table-column label="业务标题表达式" align="center" prop="titleexp"/>
            <el-table-column label="操作" width="180" align="center" >
              <template slot-scope="scope">
           <!--   <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="data_association(scope.row.activitiKey)"
              >编辑
              </el-button>-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteAss(scope.row.id)"
                v-hasPermi="['system:menu:remove']"
              >删除
              </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
           <el-button @click="cancel">关 闭</el-button>

      </span>
    </el-dialog>

    <!-- 第二个增加业务关联 -->
    <el-dialog title="新增" :visible.sync="dialogaddVisible" width="800px" height="500px">

      <el-form ref="formadd" :model="formadd" :rules="rules" label-width="120px">
        <el-form-item label="流程key:" prop="actkey" read>
          <el-input v-model="formadd.actkey" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="表名:" prop="tablename">
          <el-input v-model="formadd.tablename"></el-input>
        </el-form-item>
        <el-form-item label="标题表达式:" prop="titleexp">
          <el-input v-model="formadd.titleexp"></el-input>

        </el-form-item>
        <el-form-item  >
          <p style="color: red;">参考：XXXX【${busname}】-XXXX【${name}】；其中${}表达式取流程变量的值</p>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="SubmitAcc('formadd')">确 定</el-button>
          <el-button @click="closeAddform" >关 闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listModeler,
    deployModeler,
    suspendOrActiveApply,
    delModeler,
    getActCategroy,
    addDataAssociation,
    getListDataAssociation,
    removeDataAssociation
  } from '@/api/activiti/modeler/activiti_list'
  import { getToken } from '@/utils/auth'

  export default {
    created() {
      getActCategroy().then(response => {
        this.processList = response.rows
      })
      this.getList()
    },
    data() {
      return {
        formadd: {
          actkey:'',
          tablename:'',
          titleexp:''
        },
        rules: {
          tablename: [
            { required: true, message: '请输入表名', trigger: 'blur' }
          ],
          titleexp: [
            { required: true, message: '请输入标题表达式', trigger: 'blur' }
          ],
        },
        baseUrl: process.env.VUE_APP_BASE_API,
        processList: [],
        dialogVisible: false,
        dialogaddVisible:false,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 表格数据
        modelerList: [],
        // 查询参数
        queryParams: {
          activitiName: undefined,
          activitiCategory: 0,
          pageNum: 1,
          pageSize: 10
        },
        // 是否显示弹出层
        editOpen: false,
        iframe: {
          height: document.documentElement.clientHeight - 126.5 + 'px;'
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: undefined,
          actkey:'',
          //业务关联数据
          DataAssociation:[]
        }
      }
    },
    methods: {
      changeCategroy(item) {
        this.queryParams.activitiCategory = item
        this.handleQuery()
      },
      /** 查询列表 */
      getList() {
        this.loading = true
        listModeler(this.queryParams).then(response => {
          this.modelerList = response.rows
          //console.log(response.rows)
          this.total = response.total
          this.loading = false
        })
      },

      formatStatus(status) {
        return status === '0' ? 'danger' : 'success'
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.src = process.env.VUE_APP_BASE_API + '/modeler/create?f=' + this.queryParams.activitiCategory + '&r=' + Math.random()
        this.editOpen = true
      },
      /** 编辑按钮操作 */
      handleUpdate(row) {
        this.src = process.env.VUE_APP_BASE_API + '/modeler/activiti/index?modelId=' + row.activitiId
        this.editOpen = true
      },
      /** 部署按钮操作 */
      handleDeploy(row) {
        const name = row.activitiName
        this.$confirm('是否确认部署名称为"' + name + '"的流程模型?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return deployModeler(row.id)
        }).then(() => {
          this.getList()
          this.msgSuccess('部署成功')
        }).catch(function() {
        })
      },
      handleSuspendOrActiveApply(row) {
        let suspendOrActive = row.processDefinition.suspendState === '2' ? '激活' : '挂起'
        this.$confirm('是否挂起"' + suspendOrActive + '"流程定义?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return suspendOrActiveApply(row.processDefinition.id, row.processDefinition.suspendState)
        }).then(() => {
          this.getList()
          this.msgSuccess(suspendOrActive + '成功')
        }).catch(function() {
        })
      },
      /** 删除按钮操作 */
      handleDelete(row, index) {
        const name = row.activitiName
        this.$confirm('是否确认删除名称为"' + name + '"的流程模型?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delModeler(row.id)
        }).then(() => {
          if (this.modelerList.length - 1 === 0) {
            this.queryParams.pageNum = this.queryParams.pageNum - 1 === 0 ? 1 : this.queryParams.pageNum - 1
          }
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /**
       * 查看流程图
       * 2020年7月24日09:06:14
       * 吕瑞涵
       */
      viewFlowChat(row) {
        if (row.activitiDeployStatus === '1') {
          window.open(this.baseUrl + '/activiti/definition/readResource?id=' + row.id + '&type=png')
        } else {
          this.msgError('暂未部署，无法查看')
        }
      },
      /**
       * 查看流程XML
       * 2020年7月24日09:06:59
       * 吕瑞涵
       */
      viewFlowXML(row) {
        if (row.activitiDeployStatus === '1') {
          window.open(this.baseUrl + '/activiti/definition/readResource?id=' + row.id + '&type=xml')
        } else {
          this.msgError('暂未部署，无法查看')
        }
      },
      handleUpload() {
        this.upload.title = '部署自定义流程'
        this.upload.open = true
        this.upload.url = process.env.VUE_APP_BASE_API + '/activiti/definition/upload/' + this.queryParams.activitiCategory
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
        this.getList()
      },
      //监听修改流程对话框的关闭事件
      handleEditModelerDialogClose() {
        this.getList()
      },
      //单击业务关联
      data_association(actkeyvalue){
        this.dialogVisible = false;
        getListDataAssociation(actkeyvalue).then(response => {
        this.DataAssociation=response.rows;
          this.dialogVisible = true;
        });
        this.actkey=actkeyvalue;
      },
      // 取消按钮
      cancel() {
        this.dialogVisible = false
      },
      //弹出新增关联按钮
      addDatAassociation(){
        this.formadd.actkey=this.actkey;
        this.dialogaddVisible=true;
      },
      //提交数据
      SubmitAcc(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            addDataAssociation(this.formadd).then(response => {
              this.msgSuccess('新增成功')
              this.dialogaddVisible=false;
              this.data_association(this.actkey);
            });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      handleDeleteAss(id){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return  removeDataAssociation(id);
        }).then(() => {
          this.data_association(this.actkey)
          this.msgSuccess('删除成功')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
       /* removeDataAssociation(id).then(response => {
          this.msgSuccess('删除成功');
        })*/
      },
      closeAddform(){
      this.dialogaddVisible=false;
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .el-aside{background: #fff;}
  h3 {
    margin: 40px 0 0;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: inherit;
    text-decoration: none;
  }

  body {
    background: #ffffff;
    padding: 10px;
  }

  .box {
    margin: 10px;
  }

  .el-aside {
    /*background-color: #D3DCE6;*/
    color: #333;
    border: 1px solid #e9e9e9;
    border-radius: 10px;
  }

  .title {
    line-height: 40px;
    border-bottom: 2px solid #e9e9e9;
    text-align: left;
    padding-left: 30px;
  }

  .left {
    width: 100%;
    /*height: 100%;*/
  }

  .left ul {
    min-height: 800px;
    height: 100%;
  }

  .left ul li {
    width: 80%;
    height: 50px;
    line-height: 50px;
    color: #2f4050;
    text-align: left;
    padding-left: 30px;
  }

  .left ul li:hover {
    color: #02a7f0;
  }

  .right {
    border: 1px solid #e9e9e9;
    margin-left: 20px;
    padding-top: 0;
    padding-left: 0;
    border-radius: 10px;
    padding-right: 0;
  }

  .dad {
    height: 75px;
    border-top: 1px solid #e9e9e9;
    border-bottom: 1px solid #e9e9e9;
    border-top: none;
  }
.bgfff{background:#fff;padding:10px;}
  .dead {
    width: 100%;
    height: 500px;
    margin-top: 20px;
    border-top: 1px solid #e9e9e9;
    border-bottom: 1px solid #e9e9e9;
  }
  .left ul li[data-v-74afc76c]{
    padding-left: 20px;
  }
  .der {
    float: left;
    margin-bottom: 10px;
  }

  .der .el-button {
    margin-bottom: 10px;
  }
  .right{margin-left:10px;}
  .ddt {
    margin: 0 20px;
  }
  .el-icon-s-order{
    color:#bbbbbb;
    font-size: 22px;
    line-height: 1.2;
  }
</style>
