<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程名称" prop="name">
        <el-input
          v-model="queryParams.flowName"
          placeholder="请输入流程名称"
          maxlength="20"
          show-word-limit
          clearable v-no-whitespace
          style="width: 240px;"
          @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 icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAuditAdd"
        >新增页面
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="list" @selection-change="handleSelectionChange"
              :default-sort="defaultSort" @sort-change="handleSortChange"
    >
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="流程编号" align="center" prop="deploymentId" :show-overflow-tooltip="true" />
      <el-table-column label="流程标识" align="center" prop="flowKey" :show-overflow-tooltip="true" />
      <el-table-column label="流程名称" align="center" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleReadImage(scope.row.deploymentId)">
            <span>{{ scope.row.name }}</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程类型" align="center" prop="flowType" :show-overflow-tooltip="true" />
      <el-table-column label="审核流类型" align="center" prop="flowBusinessType" :show-overflow-tooltip="true" />
      <el-table-column label="流程说明" align="center" prop="instructions" :show-overflow-tooltip="true" />
      <el-table-column label="流程版本" align="center">
        <template slot-scope="scope">
          <el-tag size="medium">v{{ scope.row.version }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.suspensionState === 1">激活</el-tag>
          <el-tag type="warning" v-if="scope.row.suspensionState === 2">挂起</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180" />
      <el-table-column label="操作" width="250" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button @click="handleLoadXml(scope.row)" icon="el-icon-edit-outline" type="text" size="small">设计
          </el-button>
          <el-button @click="handleUpdateSuspensionState(scope.row)" icon="el-icon-video-pause" type="text" size="small"
                     v-if="scope.row.suspensionState === 1"
          >挂起
          </el-button>
          <el-button @click="handleUpdateSuspensionState(scope.row)" icon="el-icon-video-play" type="text" size="small"
                     v-if="scope.row.suspensionState === 2"
          >激活
          </el-button>
          <el-button @click="handleDelete(scope.row)" icon="el-icon-delete" type="text" size="small">删除
          </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"
    />

    <!-- 流程图 -->
    <el-dialog :title="readImage.title" :visible.sync="readImage.open" width="70%" append-to-body>
      <!-- <el-image :src="readImage.src"></el-image> -->
      <flow :flowData="flowData" />
    </el-dialog>

    <!-- 审批流配置 -->
    <el-dialog title="审批流配置" :visible.sync="flowOpen" width="35%" append-to-body :close-on-click-modal="false">
      <!-- <el-image :src="readImage.src"></el-image> -->
      <div class="container">
        <el-form ref="formData" :model="formData" size="small" :rules="rules" label-width="68px">
          <el-form-item label="流程名称" prop="flowName" label-width="130px">
            <el-input v-model="formData.flowName" @blur="checkIsExistFlowName" placeholder="请输入流程名称" clearable
                      style="width: 100%;" v-no-whitespace
            />
          </el-form-item>
          <el-form-item label="审核流类型" prop="flowType" label-width="130px">
            <el-select v-model="formData.flowType" placeholder="请选择审核流类型" clearable style="width: 100%;"
                       @change="change"
            >
              <el-option label="专用审批流" value="1" />
              <el-option label="通用审批流" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="工程名称" prop="proId" label-width="130px"
                        v-if="formData.flowType == 1 || formData.flowType == '专用审批流'"
          >
            <el-select v-model="formData.proId" placeholder="请选择工程" clearable style="width: 100%;"
                       @change="changeType"
            >
              <el-option
                v-for="item in proOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审批业务类型" prop="flowBusinessType" label-width="130px"
                        v-if="((formData.flowType == 1 || formData.flowType == '专用审批流') && (formData.proId != '' && formData.proId != undefined)) || (formData.flowType == 2 || formData.flowType == '通用审批流')"
          >
            <el-select v-model="formData.flowBusinessType" placeholder="请选择审批业务类型" clearable
                       style="width: 100%;"
            >
              <el-option
                v-for="item in flowOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审批流说明" prop="" label-width="130px">
            <el-input v-model="formData.instructions" placeholder="请输入审批流说明" clearable style="width: 100%;"  v-no-whitespace/>
          </el-form-item>
        </el-form>
        <div class="footer" style="display: flex;flex-direction: row">
          <el-button type="primary" @click="handleSave" style="margin-left: 73%;">下一步</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delFlow, readXml, listFlow, updateState, checkIsExistFlowName } from '@/api/flow/definition'
import flow from '@/views/flow/definition/detail/flow'
import { getProName, queryTheApprovalServiceType } from '@/api/tool/select'

export default {
  name: 'Definition',
  components: {
    flow
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      flowOpen: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选择用户名
      selectName: '',
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      proOptions: [],
      flowOptions: [],
      // 日期范围
      dateRange: [],
      // xml
      flowData: '',
      formData: {
        name: '',
        flowType: '',
        proId: '',
        flowBusinessType: '',
        instructions: ''
      },
      rules: {
        flowName: [
          { required: true, message: '流程名称不能为空', trigger: 'blur' }
        ],
        flowType: [
          { required: true, message: '审核流类型不能为空', trigger: 'blur' }
        ],
        proId: [
          { required: true, message: '工程名称不能为空', trigger: 'blur' }
        ],
        flowBusinessType: [
          { required: true, message: '审批业务类型不能为空', trigger: 'blur' }
        ]
      },
      // 默认排序
      defaultSort: { prop: 'loginTime', order: 'descending' },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      readImage: {
        open: false,
        src: ''
      }
    }
  },
  created() {
    this.getList()
    this.getPro()
    this.getType()
  },
  methods: {
    //检查单位名称是否存在
    async checkIsExistFlowName() {
      const params = {
        flowName: this.formData.flowName
      }
      try {
        const response = await checkIsExistFlowName(params)
        if (response.code === 500) {
          this.$message({
            message: response.msg,
            type: 'error'
          });
          // 返回 false 或者其他值，表示单位名称已存在
          return false;
        } else {
          // 返回 true 或者其他值，表示单位名称不存在重复
          return true;
        }
      } catch (error) {
        return false;
      }
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true
      listFlow(this.queryParams).then(response => {
          console.log(response)
          this.list = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    getPro() {
      const params = {}
      getProName(params).then(response => {
        this.proOptions = response.data
      })
    },
    getType() {
      let params = {}
      queryTheApprovalServiceType(params).then(response => {
        this.flowOptions = response.data
      })
    },
    change(e) {
      if (e === 2 || e === '2') {
        // 通用审批流
        const params = {
          type: 2
        }
        queryTheApprovalServiceType(params).then(response => {
          this.flowOptions = response.data
        })
      }
    },
    changeType(e) {
      console.log("proId:"+e)
      const params = {
        proId: e,
        type: 1
      }
      queryTheApprovalServiceType(params).then(response => {
        this.flowOptions = response.data
      })
    },
    /** 跳转到流程设计页面 */
    handleLoadXml(row) {
      console.log(row)
      this.formData = {
        flowName: row.name,
        flowType: row.flowType,
        proId: row.proName,
        proName: row.proId,
        flowBusinessType: row.flowBusinessType,
        instructions: row.instructions,
        deployId: row.deploymentId,
        flowKey: row.flowKey,
        type: 'edit'
      }
      let params;
      if (row.flowType === 1 || row.flowType === '专用审批流') {
        params={
          type: 1
        }
      } else {
        params={
          type: 1,
          proId: row.proId
        }
      }
      queryTheApprovalServiceType(params).then(response => {
        this.flowOptions = response.data
      })
      this.flowOpen = true
      console.log(this.formData)
      // this.$router.push('/system/flowable/add-flowable-auth/addFlowable/' + JSON.stringify(this.formData))
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.flowName = ''
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deploymentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop
      this.queryParams.isAsc = column.order
      this.getList()
    },
    handleAdd() {
      this.formData = {}
      this.formData.deployId = 0
      this.formData.type = 'add'
      this.flowOpen = true
    },
    handleAuditAdd() {
      this.$router.push({
        path: '/basics/disposition/auditProcess',
        query: {
          id: '0',
        }
      })
    },
    handleSave() {
      this.$refs['formData'].validate(async valid => {
        if (valid) {
          // 前端验证通过，再进行唯一性检查
          const isExist = await this.checkIsExistFlowName();
          if (isExist === false) {
            // 如果单位名称已存在，可以做出相应的提示或处理
            return;
          }
          //判断this.formData.proId是否变化  对proId,proName重新赋值
          if (this.formData.flowType == 1 || this.formData.flowType == '1 '|| this.formData.flowType == '专用审批流') {
            this.formData.flowType = 1
            for (const item in this.proOptions) {
              if (this.proOptions[item].value == this.formData.proId || this.proOptions[item].label == this.formData.proId) {
                this.formData.proName = this.proOptions[item].label
                this.formData.proId = this.proOptions[item].value
              }
            }
          } else {
            this.formData.flowType = 2
          }
          for (const item in this.flowOptions) {
            if (this.flowOptions[item].value == this.formData.flowBusinessType || this.flowOptions[item].label == this.formData.flowBusinessType) {
              this.formData.flowBusinessType = this.flowOptions[item].value
            }
          }
          this.flowOpen = false
          await this.$router.push('/system/flowable/add-flowable-auth/addFlowable/' + JSON.stringify(this.formData))
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.formData = {}
      this.flowOpen = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deploymentIds = row.deploymentId || this.ids
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delFlow(deploymentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      })
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row) {
      let state = 1
      if (row.suspensionState === 1) {
        state = 2
      }
      const params = {
        deployId: row.deploymentId,
        state: state
      }
      updateState(params).then(res => {
        this.$modal.msgSuccess(res.msg)
        this.getList()
      })
    },
    /** 流程图查看 */
    handleReadImage(deployId) {
      this.readImage.title = '流程图'
      this.readImage.open = true
      readXml(deployId).then(res => {
        this.flowData = res.data
      })
    }

  }
}
</script>

