<template>
  <div class="customer-css">
    <!-- 查询区域 - rqrq -->
    <el-form :inline="true" label-position="top" label-width="100px" style="margin-top: 0px;">
      <el-row>
        <el-col :span="24">
          <el-form-item label="单据号:">
            <el-input v-model="searchData.applyNo" style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item label="单据类型:">
            <el-select v-model="searchData.orderType" style="width: 130px" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="产品资料" value="产品资料"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流程状态:">
            <el-select v-model="searchData.status" style="width: 130px" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="运行中" value="RUNNING"></el-option>
              <el-option label="已完成" value="COMPLETED"></el-option>
              <el-option label="已终止" value="TERMINATED"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button class="customer-bun-min" type="primary" @click="getInstanceList">查询</el-button>
            <el-button type="primary" @click="openAddDialog">新增测试</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 上表：流程实例列表 -->
    <div style="font-weight: bold; margin-bottom: 5px;">流程实例列表</div>
    <el-table
      :height="height1"
      :data="instanceList"
      border
      ref="instanceTable"
      highlight-current-row
      @row-click="selectInstance"
      v-loading="instanceLoading"
      style="width: 100%;">
      <el-table-column prop="applyNo" label="单据号" min-width="150" header-align="center" align="center"></el-table-column>
      <el-table-column prop="orderType" label="单据类型" min-width="100" header-align="center" align="center"></el-table-column>
      <el-table-column prop="flowName" label="流程名称" min-width="150" header-align="center" align="left"></el-table-column>
      <el-table-column prop="currentNodeName" label="当前节点" min-width="120" header-align="center" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" min-width="80" header-align="center" align="center">
        <template slot-scope="scope">
          <span :style="{ color: getStatusColor(scope.row.status) }">{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" min-width="150" header-align="center" align="center"></el-table-column>
      <el-table-column prop="applicant" label="申请人" min-width="100" header-align="center" align="center"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <a type="text" v-if="scope.row.status === 'COMPLETED' || scope.row.status === 'TERMINATED'" size="small" @click="handleRestart(scope.row)">重新审批</a>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 5px"
      @size-change="instanceSizeChange"
      @current-change="instancePageChange"
      :current-page="instancePageIndex"
      :page-sizes="[20, 50, 100, 200]"
      :page-size="instancePageSize"
      :total="instanceTotal"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 下表：节点实例列表 -->
    <div style="font-weight: bold; margin: 10px 0 5px 0;">节点审批记录</div>
    <el-table
      :height="height2"
      :data="nodeInstanceList"
      border
      ref="nodeTable"
      highlight-current-row
      v-loading="nodeLoading"
      style="width: 100%;">
      <el-table-column prop="nodeOrder" label="序号" width="60" header-align="center" align="center"></el-table-column>
      <el-table-column prop="nodeName" label="节点名称" min-width="100" header-align="center" align="center"></el-table-column>
      <el-table-column prop="departmentName" label="审批部门" min-width="100" header-align="center" align="center">
        <template slot-scope="scope">{{ scope.row.departmentName || '-' }}</template>
      </el-table-column>
      <el-table-column prop="assigneeName" label="审批人" min-width="80" header-align="center" align="center"></el-table-column>
      <el-table-column prop="attemptNo" label="次数" width="60" header-align="center" align="center"></el-table-column>
      <el-table-column prop="approveType" label="审批类型" min-width="100" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.approveType === 'SINGLE'">单人审批</span>
          <span v-else-if="scope.row.approveType === 'ALL'">会签</span>
          <span v-else-if="scope.row.approveType === 'ANY'">或签</span>
          <span v-else>{{ scope.row.approveType }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="80" header-align="center" align="center">
        <template slot-scope="scope">
          <span :style="{ color: getNodeStatusColor(scope.row.status) }">{{ getNodeStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="comment" label="审批意见" min-width="150" header-align="center" align="left" show-overflow-tooltip></el-table-column>
      <el-table-column prop="completeTime" label="完成时间" min-width="150" header-align="center" align="center">
        <template slot-scope="scope">{{ scope.row.completeTime || '-' }}</template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="openApproveDialog(scope.row)">审批</a>
<!--          <el-button v-if="scope.row.status === 'PENDING'" size="mini" type="text" @click="openApproveDialog(scope.row)">审批</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增测试对话框 - rqrq -->
    <el-dialog
      title="新增审批流程（测试）"
      :visible.sync="addDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      v-drag>
      <el-form :model="addFormData" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-form-item label="工厂编码" prop="site">
          <el-input v-model="addFormData.site" placeholder="请输入工厂编码"></el-input>
        </el-form-item>
        <el-form-item label="单据号" prop="applyNo">
          <el-input v-model="addFormData.applyNo" placeholder="请输入单据号"></el-input>
        </el-form-item>
        <el-form-item label="单据类型" prop="orderType">
          <el-select v-model="addFormData.orderType" style="width: 100%" placeholder="请选择单据类型">
            <el-option label="产品资料" value="产品资料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程编码" prop="flowCode">
          <el-input v-model="addFormData.flowCode" placeholder="请输入流程编码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddForm" :loading="addLoading">{{ addLoading ? '创建中...' : '创建' }}</el-button>
        <el-button @click="addDialogVisible = false" :disabled="addLoading">取消</el-button>
      </span>
    </el-dialog>

    <!-- 审批对话框 - rqrq -->
    <el-dialog
      title="审批"
      :visible.sync="approveDialogVisible"
      width="550px"
      :close-on-click-modal="false"
      v-drag>
      <el-form :model="approveData" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据号">
              <el-input v-model="approveData.applyNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前节点">
              <el-input v-model="approveData.nodeName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批部门">
              <el-input v-model="approveData.departmentName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人">
              <el-input v-model="approveData.assigneeName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审批意见">
          <el-input type="textarea" v-model="approveData.comment" :rows="3" placeholder="请输入审批意见"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 60px;text-align:center">

          <el-button type="success" @click="submitApprove('APPROVED')" :loading="approveLoading">同意</el-button>
        <el-button type="danger" @click="submitApprove('REJECTED')" :loading="approveLoading">驳回</el-button>
        <el-button type="info" @click="openFlowPreview">流程预览</el-button>
        <el-button @click="approveDialogVisible = false" :disabled="approveLoading">取消</el-button>

      </el-footer>
    </el-dialog>

    <!-- 流程预览对话框 - rqrq -->
    <el-dialog
      title="流程预览"
      :visible.sync="previewDialogVisible"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
      v-drag>
      <div style="margin-bottom: 15px;">
        <span style="font-weight: bold;">流程名称：</span>{{ previewData.flowName }}
        <span style="margin-left: 20px; font-weight: bold;">流程编码：</span>{{ previewData.flowCode }}
        <span style="margin-left: 20px; font-weight: bold;">版本：</span>{{ previewData.flowVersion }}
      </div>
      <el-table :data="previewData.nodeList" border style="width: 100%;">
        <el-table-column prop="nodeOrder" label="顺序" width="60" header-align="center" align="center">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="nodeCode" label="节点编码" min-width="100" header-align="center" align="center"></el-table-column>
        <el-table-column prop="nodeName" label="节点名称" min-width="120" header-align="center" align="center"></el-table-column>
        <el-table-column prop="nodeType" label="节点类型" min-width="80" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.nodeType === 'START'" style="color: #67C23A">开始</span>
            <span v-else-if="scope.row.nodeType === 'END'" style="color: #F56C6C">结束</span>
            <span v-else style="color: #409EFF">审批</span>
          </template>
        </el-table-column>
        <el-table-column prop="approveType" label="审批类型" min-width="100" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.approveType === 'SINGLE'">单人审批</span>
            <span v-else-if="scope.row.approveType === 'ALL'">会签</span>
            <span v-else-if="scope.row.approveType === 'ANY'">或签</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="审批部门" min-width="120" header-align="center" align="center">
          <template slot-scope="scope">{{ scope.row.departmentName || '-' }}</template>
        </el-table-column>
        <el-table-column prop="approverNames" label="审批人" min-width="150" header-align="center" align="left">
          <template slot-scope="scope">{{ scope.row.approverNames || '-' }}</template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchInstanceList,
  searchNodeInstanceList,
  createFlowInstance,
  approveNodeInstance,
  getFlowPreview,
  restartFlowInstance
} from '@/api/workFlow/workFlow.js'

export default {
  data() {
    return {
      height1: 200,
      height2: 200,
      // 流程实例
      instanceLoading: false,
      instanceList: [],
      instancePageIndex: 1,
      instancePageSize: 20,
      instanceTotal: 0,
      currentInstance: null,
      searchData: {
        site: this.$store.state.user.site,
        applyNo: '',
        orderType: '',
        status: ''
      },
      // 节点实例
      nodeLoading: false,
      nodeInstanceList: [],
      // 当前登录用户
      currentUser: this.$store.state.user.username,
      // 新增对话框
      addDialogVisible: false,
      addLoading: false,
      addFormData: {
        site: this.$store.state.user.site,
        applyNo: '',
        orderType: '产品资料',
        flowCode: ''
      },
      addFormRules: {
        site: [{ required: true, message: '请输入工厂编码', trigger: 'blur' }],
        applyNo: [{ required: true, message: '请输入单据号', trigger: 'blur' }],
        orderType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
        flowCode: [{ required: true, message: '请输入流程编码', trigger: 'blur' }]
      },
      // 审批对话框
      approveDialogVisible: false,
      approveLoading: false,
      approveData: {
        applyNo: '',
        nodeCode: '',
        nodeName: '',
        departmentName: '',  // 审批部门 - rqrq
        assigneeName: '',
        site: '',
        orderType: '',
        comment: '',
        flowCode: '',
        flowVersion: null
      },
      // 流程预览
      previewDialogVisible: false,
      previewData: {
        flowCode: '',
        flowName: '',
        flowVersion: '',
        nodeList: []
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height1 = (window.innerHeight - 250) / 2
      this.height2 = (window.innerHeight - 250) / 2
    })
    this.getInstanceList()
  },
  methods: {
    // 获取流程实例列表
    getInstanceList() {
      this.instanceLoading = true
      const params = {
        ...this.searchData,
        limit: this.instancePageSize,
        page: this.instancePageIndex
      }
      searchInstanceList(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.instanceList = data.page.list
          this.instanceTotal = data.page.totalCount
        }
        this.instanceLoading = false
      })
    },
    instanceSizeChange(val) {
      this.instancePageSize = val
      this.instancePageIndex = 1
      this.getInstanceList()
    },
    instancePageChange(val) {
      this.instancePageIndex = val
      this.getInstanceList()
    },
    // 选中流程实例
    selectInstance(row) {
      this.currentInstance = row
      this.getNodeInstanceList()
    },
    // 获取节点实例列表
    getNodeInstanceList() {
      if (!this.currentInstance) {
        this.nodeInstanceList = []
        return
      }
      this.nodeLoading = true
      searchNodeInstanceList({
        applyNo: this.currentInstance.applyNo,
        site: this.currentInstance.site,
        orderType: this.currentInstance.orderType
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.nodeInstanceList = data.rows
        }
        this.nodeLoading = false
      })
    },
    // 状态颜色
    getStatusColor(status) {
      switch (status) {
        case 'RUNNING': return '#409EFF'
        case 'COMPLETED': return '#67C23A'
        case 'TERMINATED': return '#F56C6C'
        default: return '#909399'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'RUNNING': return '运行中'
        case 'COMPLETED': return '已完成'
        case 'TERMINATED': return '已终止'
        default: return status
      }
    },
    getNodeStatusColor(status) {
      switch (status) {
        case 'PENDING': return '#E6A23C'
        case 'APPROVED': return '#67C23A'
        case 'REJECTED': return '#F56C6C'
        case 'SKIPPED': return '#909399'
        default: return '#909399'
      }
    },
    getNodeStatusText(status) {
      switch (status) {
        case 'PENDING': return '待审批'
        case 'APPROVED': return '已通过'
        case 'REJECTED': return '已驳回'
        case 'SKIPPED': return '已跳过'
        default: return status
      }
    },
    // 打开新增对话框
    openAddDialog() {
      this.addFormData = {
        site: this.$store.state.user.site,
        applyNo: '',
        orderType: '产品资料',
        flowCode: ''
      }
      this.addDialogVisible = true
    },
    // 提交新增
    submitAddForm() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.addLoading = true
          createFlowInstance(this.addFormData).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message.success('流程实例创建成功')
              this.addDialogVisible = false
              this.getInstanceList()
            } else {
              this.$message.error(data.msg || '创建失败')
            }
          }).finally(() => {
            this.addLoading = false
          })
        }
      })
    },
    // 打开审批对话框
    openApproveDialog(row) {
      this.approveData = {
        applyNo: this.currentInstance.applyNo,
        nodeCode: row.nodeCode,
        nodeName: row.nodeName,
        departmentName: row.departmentName || '',  // 审批部门 - rqrq
        assigneeName: row.assigneeName,
        site: this.currentInstance.site,
        orderType: this.currentInstance.orderType,
        comment: '',
        flowCode: this.currentInstance.flowCode,
        flowVersion: this.currentInstance.flowVersion
      }
      this.approveDialogVisible = true
    },
    // 提交审批
    submitApprove(action) {
      if (action === 'REJECTED' && !this.approveData.comment) {
        this.$message.warning('驳回时必须填写审批意见')
        return
      }
      this.approveLoading = true
      approveNodeInstance({
        applyNo: this.approveData.applyNo,
        nodeCode: this.approveData.nodeCode,
        site: this.approveData.site,
        orderType: this.approveData.orderType,
        action: action,
        comment: this.approveData.comment
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success(action === 'APPROVED' ? '审批通过成功' : '驳回成功')
          this.approveDialogVisible = false
          this.getInstanceList()
          this.getNodeInstanceList()
        } else {
          this.$message.error(data.msg || '操作失败')
        }
      }).finally(() => {
        this.approveLoading = false
      })
    },
    // 流程预览
    openFlowPreview() {
      getFlowPreview({
        flowCode: this.approveData.flowCode,
        flowVersion: this.approveData.flowVersion,
        site: this.approveData.site
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.previewData = data.row
          this.previewDialogVisible = true
        } else {
          this.$message.error(data.msg || '获取流程信息失败')
        }
      })
    },
    // 重新审批 - rqrq
    handleRestart(row) {
      this.$confirm('确定要重新发起审批流程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        restartFlowInstance({
          applyNo: row.applyNo,
          site: row.site,
          orderType: row.orderType
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('重新审批成功')
            this.getInstanceList()
            this.nodeInstanceList = []
            this.currentInstance = null
          } else {
            this.$message.error(data.msg || '操作失败')
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
