<template>
  <div class="app-container">
    <div class="tab-header webtop">
      <div style="text-align: right">
<!--        <router-link tag='a' :to="'/home'">《&nbsp;返回首页</router-link>-->
        <a href="javascript:window.opener=null;window.open('','_self');window.close();" class="text-center">关闭</a>
      </div>
    </div>
    <div class="searchcon">
      <div class="search">
        <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="100px" class="tab-header">
          <el-form-item label="流程名称">
            <el-input v-model="listQuery.params.proDefName" placeholder="流程名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="申请日期">
            <el-date-picker v-model="listQuery.params.startDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
            <label>至</label>
            <el-date-picker v-model="listQuery.params.endDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
        </el-form>
      </div>
    </div>
    <div class="listtop">
      <div class="tit">已办任务列表</div>
      <pageye v-show="total > 0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
    </div>
    <div class="listcon">
      <el-table :key="tableKey" v-loading="listLoading" :data="list" border style="width:100%" @selection-change="handleSelectionChange">
        <el-table-column width="60px" label="序号" type="index" :index="tableKey+1" align="center"/>
        <el-table-column width="180px" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleCheck(scope.row)">详情</el-button>
            <el-button type="danger" v-show="scope.row.endTime === null && scope.row.startUserSid === listQuery.params.userSid" size="small" @click="handleTerminate(scope.row)">终止</el-button>
          </template>
        </el-table-column>
        <!--        <el-table-column label="流程类别" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span class="bluezi">{{scope.row.category}}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="工作名称" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.procDefName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起人" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.startUserName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起日期" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.createTime|formatTimer}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起部门" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.startDeptName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="当前处理人" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.endTime!=null"></span>
            <span v-else>{{scope.row.assigneeName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="当前环节" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.endTime!=null" class="bluezi" @click="handleFlowRecord(scope.row)">已办结</span>
            <span v-else class="bluezi" @click="handleFlowRecord(scope.row)">{{scope.row.taskName}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column width="80px" label="审批记录" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button type="primary" size="small" @click="handleFlowRecord(scope.row)">查看</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </div>
    <div class="pages">
      <div class="tit"/>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
    </div>
    <!-- Start查看页面 -->
    <el-dialog
      title=""
      :visible.sync="centerDialogVisible"
      width="78%"
      height="1%"
      :before-close="closeIt"
      center>
      <iframe frameborder="0" id="iframe_done"
              style="width:100%;"
              :src="this.centerDialogVisible === true ? url :''"
      ></iframe>
    </el-dialog>
    <!-- End查看页面-->

    <!-- 编辑信息 -->
    <el-dialog title="审批记录" :visible.sync="editDialog" width="80%" style="overflow: hidden">
      <!--流程流转记录-->
      <flow-records :xmlData="xmlData" :taskData="taskList" :flowRecordList="flowRecordList"></flow-records>
    </el-dialog>

    <!-- 发起人终止申请，填写终止原因 -->
    <el-dialog center :visible.sync="breakProcessVisible" width="50%">
      <el-form :model="dialogList" class="formadd">
        <el-row style="border-top: 1px solid #E0E3EB">
          <el-col :span="4" class="tleftb">
            <span>终止原因</span>
          </el-col>
          <el-col :span="20">
            <el-form-item>
              <el-input v-model="dialogList.comment" clearable placeholder="" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" resize="none"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleConfirm">确定</el-button>
        <el-button size="small" @click="breakProcessVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import flowRecords from '@/components/flow/flowRecord'
  import Pagination from '@/components/pagination'
  import pageye from '@/components/pagination/pageye'
  import { getStorage } from '@/utils/auth'
  import { revokeTask, getList, selectUrl, readXml, getFlowViewer, breakProcess } from '@/api/flow/todo'
  import { flowRecord, revokeProcess } from "@/api/workflow/finished"
  import { loginDetails } from '@/api/user'
 // import flow from "@/views/flow/flow";

  export default {
    name: "",
    components: {
      pageye, Pagination, flowRecords
    },
    data() {
      return {
        taskList: [],
        xmlData: '',
        dialogHeight: '80%',
        isDialogVisible: false, // 撤回弹窗
        centerDialogVisible: false, // 弹框
        editDialog: false,
        flowRecordList: [],
        listLoading: false,
        total: 0,
        list: [],
        tableKey: 0,
        taskName_now: '',
        url: '',
        loginInfo: {
          userSid: ''
        },
        // 撤回
        revokeList: {
          businessSid: '',
          instanceId: '',
          taskId: '',
          userSid: ''
        },
        breakProcessVisible: false,
        dialogList: {
          businessSid: '',
          comment: '',
          instanceId: '',
          taskId: '',
          orgSidPath: '',
          taskDefKey: '',
          userSid: ''
        },
        selectUrl_list: {
          proc_def_id: '', // 流程定义id
          taskDefKey: '', // 节点id
          type: '' // 类型
        },
        listQuery: {
          current: 1,
          size: 10,
          params: {
            proDefName: '',
            startDate: '',
            endDate: '',
            userSid: ''
          }
        }
      }
    },
    mounted() {
      // 在外部vue的window上添加postMessage的监听，而且绑定处理函数handleMessage
      window.addEventListener('message', this.handleMessage)
    },
    created() {
      // 加载列表
      // this.getList()
      this.init()
    },
    filters: {
      formatTimer: function(value) {
        let date = new Date(value)
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate()
        d = d < 10 ? '0' + d : d
        let h = date.getHours()
        h = h < 10 ? '0' + h : h
        let m = date.getMinutes()
        m = m < 10 ? '0' + m : m
        let s = date.getSeconds()
        s = s < 10 ? '0' + s : s
        return y + '-' + MM + '-' + d // + " " + h + ":" + m;
      }
    },
    methods: {
      /** xml 文件 */
      getModelDetail(deployId) {
        var token = getStorage()
        // 发送请求，获取xml
        readXml(deployId, token).then(res => {
          this.xmlData = res.data
        })
      },
      //已办环节的节点
      getFlowViewer(procInsId) {
        var token = getStorage()
        getFlowViewer(procInsId, token).then(res => {
          this.taskList = res.data
        })
      },
      setIframeHeight(iframe) {
        iframe.height = this.dialogHeight // iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
      },
      async handleMessage(event) {
        var code = event.data.params.code
        if (code == 1) {
          this.init()
          this.centerDialogVisible = false
        } else if (code == 2) {
          this.dialogHeight = event.data.params.data
          this.setIframeHeight(document.getElementById('iframe_done'))
        }
      },
      init() {
        var token = getStorage();
        loginDetails(token).then((response) => {
          if (response.code === '200') {
            this.loginInfo = response.data;
            this.revokeList.userSid = this.loginInfo.sid
            this.listQuery.params.userSid = this.loginInfo.sid
            this.getList()
          }
        });
      },
      /** 打开详情 */
      handleCheck(row) {
        this.selectUrl_list.proc_def_id = row.procDefId
        this.selectUrl_list.taskDefKey = row.taskDefKey
        this.selectUrl_list.type = 2 // 详情
        const parameter_list = {
          businessSid: row.processVariables.businessSid,
          instanceId: row.procInsId,
          taskId: row.taskId,
          taskDefKey: row.taskDefKey,
          taskName: row.taskName,
          deployId: row.deployId
        }
        selectUrl(this.selectUrl_list).then((response) => {
          if (response.success && response.data.url !== '') {
            // this.url = 'http://127.0.0.1:9531' + '/production/#/paichanguanli/haveDone' + '?token=' + getStorage() + '&data=' + encodeURI((JSON.stringify(parameter_list)))
             this.url = 'http://jg.yyundong.com/' + response.data.url + '?token=' + getStorage() + '&data=' + encodeURI((JSON.stringify(parameter_list)))
            // this.url = 'http://120.46.172.184' + response.data.url + '?token=' + getStorage() + '&data=' + encodeURI((JSON.stringify(parameter_list)))
            console.log(this.url)
          } else if (response.success && response.data.url === '') {
            this.$notify({
              title: '提示',
              message: '请在手机端进行审核',
              type: 'error',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '提示',
              message: '执行失败',
              type: 'error',
              duration: 2000
            })
          }
        })
        // 撤回
        this.taskName_now = row.taskName
        this.revokeList.businessSid = row.processVariables.businessSid
        this.revokeList.instanceId = row.procInsId
        this.revokeList.taskId = row.taskId
        this.getFlowRecordList(row.procInsId, row.deployId)
        this.centerDialogVisible = true
        // this.$router.push({path: '/todo' + '?token=' + getStorage()})
      },
      closeIt() {
        this.url = ''
        this.centerDialogVisible = false
      },
      handleTerminate(row) {
        this.breakProcessVisible = true
        this.dialogList.comment = ''
        this.dialogList.businessSid = row.processVariables.businessSid
        this.dialogList.instanceId = row.procInsId
        this.dialogList.taskId = row.taskId
        this.dialogList.taskDefKey = row.taskDefKey
        this.dialogList.userSid = window.sessionStorage.getItem('userSid')
      },
      handleConfirm() {
        if (this.dialogList.comment === '') {
          this.$message({ showClose: true, type: 'error', message: '请填写终止原因' })
          return
        }
        const tip = '请确认是否终止该申请'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          breakProcess(this.dialogList).then((resp) => {
            if (resp.success) {
              this.breakProcessVisible = false
              this.$message({ showClose: true, type: 'success', message: '操作成功' })
              this.getList()
            }
          })
        })
      },
      /** 流程流转记录 */
      handleFlowRecord(row) {
        this.getModelDetail(row.deployId)
        this.getFlowViewer(row.procInsId)
        this.getFlowRecordList(row.procInsId, row.deployId)
        this.editDialog = true
      },
      /** 流程流转记录 */
      getFlowRecordList(procInsId, deployId) {
        var token = getStorage()
        const params = { procInsId: procInsId, deployId: deployId, token: token }
        flowRecord(params).then(res => {
          this.flowRecordList = res.data.flowList
          // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
          if (res.data.formData) {
            this.formConf = res.data.formData
            this.formConfOpen = true
          }
        }).catch(res => {
          this.getList()
        })
      },
      getList() {
        this.listLoading = true
        getList({
          current: this.listQuery.current,
          size: this.listQuery.size,
          params: {
            proDefName: this.listQuery.params.proDefName,
            startDate: this.listQuery.params.startDate,
            endDate: this.listQuery.params.endDate,
            userSid: this.listQuery.params.userSid
          }
        }).then((rep) => {
          this.listLoading = false
          this.list = rep.data.records
          this.total = rep.data.total
        })
      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },
      handleSelectionChange() {

      },

      indexMethod() {
        return 0;
      },
      setIcon(val) {
        if (val) {
          return "el-icon-check";
        } else {
          return "el-icon-time";
        }

      },
      setColor(val) {
        if (val) {
          return "#2bc418";
        } else {
          return "#b3bdbb";
        }

      }
    }
  }
</script>

<style>
  .scroll_div {
    height: 500px;
    overflow-y: scroll;
  }

  .diaTitle {
    padding: 30px 0 15px 0;
    font-size: 20px;
    font-weight: 500;
  }

  .el-icon-document, .el-icon-chat-line-square, .el-icon-notebook-2 {
    margin-right: 5px;
  }

  .listtop {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0px 0px 10px 15px;
    margin: 0;
  }

  .listtop .tit {
    font-weight: bold;
  }

  .listtop .pagination {
    margin: 0;
    padding: 0;
  }

  .pages {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: flex-end;
    padding: 0px 0px 15px 15px;
  }

  .pages .tit {
    font-weight: bold;
  }

  .pages .pagination {
    margin: 0;
  }
</style>
