<template>
  <div class="abnormal-control-panel">
    <div class="workflow-container">
      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-card class="stats-card" @click.native="switchTab('pending')">
            <div class="stats-number">{{ stats.pending }}</div>
            <div class="stats-label">待处理任务</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stats-card" @click.native="switchTab('initiated')">
            <div class="stats-number">{{ stats.initiated }}</div>
            <div class="stats-label">我发起的</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stats-card" @click.native="switchTab('processed')">
            <div class="stats-number">{{ stats.completed }}</div>
            <div class="stats-label">已完成</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 选项卡切换 -->
      <el-tabs v-model="activeTab" type="border-card" class="workflow-tabs" @tab-click="handleTabClick">
        <!-- 待我处理 -->
        <el-tab-pane label="待我处理" name="pending">
          <div class="filter-bar">
            <el-input placeholder="搜索流程名称" v-model="filters.pending.keyword" class="filter-item" style="width: 200px;" clearable>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-select v-model="filters.pending.priority" placeholder="优先级" class="filter-item" clearable>
              <el-option label="紧急" value="urgent"></el-option>
              <el-option label="高" value="high"></el-option>
              <el-option label="普通" value="normal"></el-option>
            </el-select>
          </div>

          <div v-if="filteredPendingTasks.length > 0">
            <el-card v-for="task in filteredPendingTasks" :key="task.节点ID" class="process-card">
              <div slot="header" class="clearfix">
                <el-tag :type="getPriorityType(task.优先级)" class="priority-tag">
                  {{ getPriorityText(task.优先级) }}
                </el-tag>
                <span v-if="task.是否转办" class="node-status status-transferred">转办</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="handleTask(task)">处理</el-button>
                <el-button size="mini" icon="el-icon-s-fold" @click="showTransferDialog(task)">转办</el-button>
              </div>
              <div>
                <p><strong>流程名称:</strong> {{ task.流程标题 }}</p>
                <p><strong>申请人:</strong> {{ task.申请人 }}</p>
                <p><strong>申请时间:</strong> {{ task.申请时间 }}</p>
                <p><strong>当前节点:</strong> {{ task.当前节点 }}</p>
                <p><strong>描述:</strong> {{ task.流程描述 }}</p>
                <p><strong>已关联生产订单:</strong> {{ task.已关联计划号 }}</p>
                <p><strong>物料名称:</strong> {{ task.零件名称 }}</p>
                <p><strong>物料编号:</strong> {{ task.零件编号 }}</p>
                <p><strong>工序名称:</strong> {{ task.工序名称 }}</p>
              </div>
            </el-card>
          </div>
          <div v-else class="empty-state">
            <el-empty description="暂无待处理任务"></el-empty>
          </div>
        </el-tab-pane>

        <!-- 我发起的 -->
        <el-tab-pane label="我发起的" name="initiated">
          <div class="filter-bar">
            <el-input placeholder="搜索流程名称" v-model="filters.initiated.keyword" class="filter-item" style="width: 200px;" clearable>
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-select v-model="filters.initiated.status" placeholder="状态" class="filter-item" clearable>
              <el-option label="审批中" value="processing"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已拒绝" value="rejected"></el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog" style="width: auto;">发起新流程</el-button>
          </div>

          <el-table :data="filteredInitiatedProcesses" style="width: 100%">
            <el-table-column prop="流程标题" label="流程名称" width="150"></el-table-column>
            <el-table-column prop="发起时间" label="发起时间" width="200"></el-table-column>
            <el-table-column prop="当前节点" label="当前节点" width="120"></el-table-column>
            <el-table-column prop="状态" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.状态)">
                  {{ getStatusText(scope.row.状态) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="viewProcessDetail(scope.row)">查看进度</el-button>
                <el-button v-if="scope.row.状态 === 'processing'" type="text" @click="showCompleteDialog(scope.row)">完结</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 我已处理 -->
        <el-tab-pane label="我已处理" name="processed">
          <el-table :data="processedTasks" style="width: 100%">
            <el-table-column prop="流程名称" label="流程名称" width="150"></el-table-column>
            <el-table-column prop="申请人" label="申请人" width="100"></el-table-column>
            <el-table-column prop="处理时间" label="处理时间" width="200"></el-table-column>
            <el-table-column prop="处理结果" label="处理结果" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.处理结果 === 'transferred'">
                  转办
                </el-tag>
                <el-tag v-else :type="scope.row.处理结果 === 'approved' ? 'success' : 'danger'">
                  {{ scope.row.处理结果 === 'approved' ? '同意' : '拒绝' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="审批意见" label="审批意见"></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="viewProcessDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 发起流程对话框 -->
      <el-dialog title="发起新流程" :visible.sync="createDialogVisible" width="1000px" :close-on-click-modal="false" :append-to-body="true">
        <el-form :model="newProcessForm" label-width="120px" :rules="formRules" ref="processForm">
          <!-- 基础信息 -->
          <div class="form-section">
            <div class="form-section-title">
              <i class="el-icon-info"></i>基础信息
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="优先级" prop="priority">
                  <el-select v-model="newProcessForm.priority" placeholder="请选择优先级" style="width: 100%">
                    <el-option label="普通" value="normal"></el-option>
                    <el-option label="高" value="high"></el-option>
                    <el-option label="紧急" value="urgent"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="流程标题" prop="title">
              <el-input v-model="newProcessForm.title" placeholder="请输入流程标题"></el-input>
            </el-form-item>
            
            <el-form-item label="流程描述" prop="description">
              <el-input type="textarea" v-model="newProcessForm.description" :rows="3" 
                    placeholder="请输入流程详细描述"></el-input>
            </el-form-item>
            <!-- 审批流程设置 -->
            <div class="form-section" v-if="newProcessForm.type">
              <div class="form-section-title">
                <i class="el-icon-s-check"></i>审批流程设置
              </div>
              
              <el-form-item label="审批人" prop="approverIds">
                <el-select
                  v-model="newProcessForm.approverIds"
                  multiple
                  filterable
                  clearable
                  collapse-tags
                  placeholder="请选择审批人"
                  style="width: 100%;">
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          
          <div class="form-section">
            <div class="form-section-title">
              <i class="el-icon-info"></i>绑定任务信息
            </div>
            <el-form-item v-if="selectedRow" label="已关联生产订单">
              <el-input v-model="tableOrderNum" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow" label="物料名称">
              <el-input v-model="tableProductName" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow" label="物料编号">
              <el-input v-model="tableProductCode" placeholder="" readonly></el-input>
            </el-form-item>
            <el-form-item v-if="selectedRow" label="工序名称">
              <el-input v-model="tableProcessName" placeholder="" readonly></el-input>
            </el-form-item>
            <div class="search-container">
              <span class="show-text">生产订单:</span>
              <el-input v-model="orderNo" placeholder="请输入生产订单" clearable style="width: 150px;margin-right: 10px" />
              <span class="show-text">产品编码:</span>
              <el-input v-model="productCode" placeholder="请输入产品编码" clearable style="width: 150px;margin-right: 10px" />
              <span class="show-text">产品名称:</span>
              <el-input v-model="productName" placeholder="请输入产品名称" clearable style="width: 150px;margin-right: 10px" />
              <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable3()">查询</el-button>
            </div>
            <div class="custom-tabs">
              <el-table v-loading="loading" :data="tableData5" :height="'40vh'" border
                element-loading-background="rgba(0, 0, 0, 0.2)" element-loading-spinner="el-icon-loading"
                highlight-current-row size="mini" style="width: 100%;" tooltip-effect="dark"
                @row-click="handleRowClick">
                <el-table-column align="center" label="序号" type="index" width="50" fixed />
                <el-table-column align="center" prop="合同号" label="销售订单" width="120" fixed />
                <el-table-column align="center" prop="订单号" label="生产订单" width="100" fixed />
                <el-table-column align="center" prop="产品编码" label="零件编码" width="220" />
                <el-table-column align="center" prop="产品名称" label="产品名称" width="190" />
                <el-table-column align="center" prop="计划数量" label="计划数" width="80" />
                <el-table-column align="center" prop="工序名称" label="工序名称" width="120" />
                <el-table-column align="center" prop="指派对象编号" label="指派对象编号" width="120" />
                <el-table-column align="center" prop="指派对象" label="指派对象" width="120" />
                <el-table-column align="center" prop="指派数量" label="指派数量" width="120" />
                <el-table-column align="center" prop="计划开始时间" label="计划开始时间" width="120" />
                <el-table-column align="center" prop="计划完成时间" label="计划完成时间" width="120" />
                <el-table-column align="center" prop="最晚开始时间" label="最晚开始时间" width="120" />
                <el-table-column align="center" label="要求完工日期" width="120">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.要求完工日期) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="createDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitNewProcess">提 交</el-button>
        </span>
      </el-dialog>

      <!-- 处理任务对话框 -->
      <el-dialog title="处理任务" :visible.sync="handleDialogVisible" width="700px" :append-to-body="true">
        <div v-if="currentTask">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请人">{{ currentTask.申请人 }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ currentTask.申请时间 }}</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(currentTask.优先级)">
                {{ getPriorityText(currentTask.优先级) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ currentTask.流程描述 }}</el-descriptions-item>
            <el-descriptions-item label="已关联生产订单">{{ currentTask.已关联计划号 }}</el-descriptions-item>
            <el-descriptions-item label="物料名称">{{ currentTask.零件名称 }}</el-descriptions-item>
            <el-descriptions-item label="物料编号">{{ currentTask.零件编号 }}</el-descriptions-item>
            <el-descriptions-item label="工序名称">{{ currentTask.工序名称 }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider></el-divider>

          <el-form :model="handleForm" label-width="100px" ref="approvalForm">
            <el-form-item label="处理意见" required>
              <el-radio-group v-model="handleForm.result">
                <el-radio label="approved">同意</el-radio>
                <el-radio label="rejected">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见">
              <el-input type="textarea" v-model="handleForm.comment" :rows="3" placeholder="请输入审批意见"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitHandle(currentTask)">提 交</el-button>
        </span>
      </el-dialog>

      <!-- 查看流程进度对话框 -->
      <el-dialog title="流程进度详情" :visible.sync="detailDialogVisible" width="800px" :append-to-body="true">
        <div v-if="currentProcess">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="流程名称">{{ currentProcess.processInfo.流程标题 }}</el-descriptions-item>
            <el-descriptions-item label="发起人">{{ currentProcess.processInfo.发起人姓名 }}</el-descriptions-item>
            <el-descriptions-item label="发起时间">{{ currentProcess.processInfo.创建时间 }}</el-descriptions-item>
            <el-descriptions-item label="当前状态">
              <el-tag :type="getStatusType(currentProcess.processInfo.状态)">
                {{ getStatusText(currentProcess.processInfo.状态) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="已关联生产订单">{{ currentProcess.processInfo.已关联计划号 }}</el-descriptions-item>
            <el-descriptions-item label="物料名称">{{ currentProcess.processInfo.零件名称 }}</el-descriptions-item>
            <el-descriptions-item label="物料编号">{{ currentProcess.processInfo.零件编号 }}</el-descriptions-item>
            <el-descriptions-item label="工序名称">{{ currentProcess.processInfo.工序名称 }}</el-descriptions-item>
          </el-descriptions>

          <el-divider></el-divider>

          <h4>审批流程</h4>
          <el-steps :active="currentProcess.processInfo.当前步骤" align-center style="margin: 20px 0;">
            <el-step v-for="(step, index) in currentProcess.steps" :key="index" 
                 :title="step.标题" :description="step.描述"></el-step>
          </el-steps>

          <el-divider></el-divider>

          <h4>审批记录</h4>
          <el-timeline style="margin-top: 20px;">
            <el-timeline-item v-if="record.处理结果 != 'transferred'" v-for="(record, index) in currentProcess.approvalRecords" 
                     :key="index" :timestamp="record.时间" :type="record.处理结果 === 'approved' ? 'success' : 'danger'"
                     :icon="record.处理结果 === 'approved' ? 'el-icon-check' : 'el-icon-close'">
              <el-card>
                <h4>{{ record.审批人姓名 }} - {{ record.处理结果 === 'approved' ? '同意' : '拒绝' }}</h4>
                <p>{{ record.审批意见 || '无备注' }}</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item v-if="record.处理结果 == 'transferred'" v-for="(record, index) in currentProcess.approvalRecords" 
                     :key="index" :timestamp="record.时间" :type="'success'"
                     :icon="'el-icon-check'">
              <el-card>
                <h4>{{ record.审批人姓名 }}-转办</h4>
                <p>{{ record.审批意见 || '无备注' }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>

      <!-- 转办对话框 -->
      <el-dialog title="转办流程" :visible.sync="transferDialogVisible" width="700px" :append-to-body="true">
        <el-form :model="transferForm" label-width="100px">
          <el-form-item label="目标人员" required>
            <el-select v-model="transferForm.newApproverId" placeholder="请选择人员" style="width: 100%">
              <el-option v-for="user in users" :key="user.id" 
                      :label="user.name" :value="user.id">
                <span>{{ user.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="转办原因" required>
            <el-input type="textarea" v-model="transferForm.reason" :rows="3" placeholder="请输入转办原因"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmTransfer" :loading="transferLoading">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 完结对话框 -->
      <el-dialog title="完结流程" :visible.sync="completeDialogVisible" width="700px" class="complete-dialog" :append-to-body="true">
        <el-form :model="completeForm" label-width="120px">
          <el-form-item label="流程名称">
            <div>{{ selectProcess ? selectProcess.流程标题 : '' }}</div>
          </el-form-item>
          <el-form-item label="完结原因" required>
            <el-input type="textarea" v-model="completeForm.reason" :rows="3" 
                      placeholder="请输入完结原因"></el-input>
          </el-form-item>
          <el-form-item label="完结结果" required>
            <el-radio-group v-model="completeForm.result">
              <el-radio label="completed">完成</el-radio>
              <el-radio label="cancelled">取消</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmComplete" :loading="completeLoading" style="width: auto;">确 认 完 结</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WorkflowManagement',
  props: {
    initialSelectedRow: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 搜索条件
      orderNo: '',
      contractNo: '',
      productCode: '',
      productName: '',
      processName: '',
      nature: '',
      completionTime: [],
      productionStatus: '',
      
      tableData5: [],
      activeTab: 'pending',
      tableOrderNum: '',
      tableProductCode: '',
      tableProductName: '',
      tableProcessName: '',
      selectedRow: '',
      loading: false,
      
      // 转办相关数据
      transferDialogVisible: false,
      transferLoading: false,
      
      // 完结相关数据
      completeDialogVisible: false,
      completeLoading: false,
      
      currentTask: null,
      currentProcess: null,
      selectProcess: null,
      
      transferForm: {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      },
      
      completeForm: {
        reason: '',
        result: 'completed'
      },
      
      createDialogVisible: false,
      handleDialogVisible: false,
      detailDialogVisible: false,
      submitting: false,
      
      filters: {
        pending: { keyword: '', priority: '', type: '' },
        initiated: { keyword: '', status: '' }
      },
      
      newProcessForm: {
        type: '',
        priority: 'normal',
        title: '',
        description: '',
        approverIds: []
      },
      
      formRules: {
        title: [{ required: true, message: '请输入流程标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入流程描述', trigger: 'blur' }],
        approverIds: [{ type: 'array', required: true, message: '请选择审批人', trigger: 'change' }]
      },
      
      handleForm: {
        result: 'approved',
        comment: ''
      },
      
      userList: [],
      
      stats: {
        pending: 0,
        initiated: 0,
        completed: 0,
      },
      
      // 数据
      pendingTasks: [],
      initiatedProcesses: [],
      processedTasks: [],
      users: [],
    };
  },
  
  computed: {
    filteredPendingTasks() {
      let tasks = this.pendingTasks;
      if (this.filters.pending.keyword) {
        tasks = tasks.filter(task => 
          task.流程标题.includes(this.filters.pending.keyword)
        );
      }
      if (this.filters.pending.priority) {
        tasks = tasks.filter(task => task.优先级 == this.filters.pending.priority);
      }
      return tasks;
    },
    
    filteredInitiatedProcesses() {
      let processes = this.initiatedProcesses;
      if (this.filters.initiated.keyword) {
        processes = processes.filter(process => 
          process.流程标题.includes(this.filters.initiated.keyword)
        );
      }
      if (this.filters.initiated.status) {
        processes = processes.filter(process => process.状态 === this.filters.initiated.status);
      }
      return processes;
    }
  },
  
  created() {
    this.applyInitialSelectedRow();
    this.searchTable();
    this.searchTable1();
    this.getUserList();
    this.getProcessedTasks();
    this.searchTable3();
  },
  watch: {
    initialSelectedRow: {
      handler() {
        this.applyInitialSelectedRow();
      },
      deep: true
    }
  },
  
  methods: {
    // 数据查询方法
    switchTab(tabName) {
      this.activeTab = tabName
      this.refreshActiveTab(tabName)
    },
    handleTabClick(tab) {
      this.refreshActiveTab(tab.name)
    },
    refreshActiveTab(tabName = this.activeTab) {
      if (tabName === 'pending') {
        this.searchTable1()
      } else if (tabName === 'initiated') {
        this.searchTable()
      } else if (tabName === 'processed') {
        this.getProcessedTasks()
      }
    },
    getProcessedTasks() {
      var params = []
      params.push(['审批人ID', this.$store.state.user.id])
      const data = this.CreateData('11', 'sp_获取最近处理任务', params)
      this.ExecDatabase(data).then((response) => {
        this.processedTasks = response.data || []
        this.stats.completed = this.processedTasks.length
      })
    },
    
    getUserList() {
      const data = this.CreateData('11', '人员管理_人员信息查询')
      this.ExecDatabase(data).then((response) => {
        response.data.forEach(item => {
          this.users.push({ id: item.Personnel_Number, name: item.Personnel_Name })
          this.userList.push({ id: item.Personnel_Number, name: item.Personnel_Name })
        });
        console.log( this.userList)
      }).catch(() => {
        this.$message.error('处理失败')
      }) 
    },
    
    searchTable() {
      var params = []
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['状态', null])
      var data = this.CreateData('11', 'sp_获取我的流程', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        this.initiatedProcesses = response.data || [];
        this.stats.initiated = this.initiatedProcesses.length
      }).catch(() => {
        this.loading = false
      })
    },
    
    searchTable1() {
      var params = []
      params.push(['审批人ID', this.$store.state.user.id])
      var data = this.CreateData('11', 'sp_获取待处理任务', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        this.pendingTasks = response.data || [];
        this.stats.pending = this.pendingTasks.length
      }).catch(() => {
        this.loading = false
      })
    },
    
    searchTable3() {
      this.loading = true
      var params = []
      params.push(['订单号', this.orderNo || 0])
      params.push(['物料类型', '自制件'])
      params.push(['合同号', this.contractNo])
      params.push(['产品编码', this.productCode])
      params.push(['产品名称', this.productName])
      params.push(['工序名称', this.processName])
      params.push(['性质', this.nature])
      params.push(['要求完工日期1', this.completionTime ? this.completionTime[0] : ''])
      params.push(['要求完工日期2', this.completionTime ? this.completionTime[1] : ''])
      params.push(['排产状态', this.productionStatus])
      params.push(['工位',''])
      var data = this.CreateData('11', 'MES_ProductAdmin_Query', params)
      this.ExecDatabase(data).then(response => {
        this.loading = false
        this.tableData5 = response.data || []
      }).catch(() => {
        this.loading = false
      })
    },

    // 对话框控制方法
    showCreateDialog() {
      this.createDialogVisible = true;
      this.resetNewProcessForm();
      this.applyInitialSelectedRow();
    },
    
    showTransferDialog(task) {
      this.currentTask = task;
      this.transferForm = {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      };
      this.transferDialogVisible = true;
    },
    
    showCompleteDialog(process) {
      this.selectProcess = process;
      this.completeForm = {
        reason: '',
        result: 'completed'
      };
      this.completeDialogVisible = true;
    },
    
    handleTask(task) {
      this.currentTask = task;
      this.handleForm = {
        result: 'approved',
        comment: ''
      };
      this.handleDialogVisible = true;
    },

    // 表单操作方法
    resetNewProcessForm() {
      this.newProcessForm = {
        type: true,
        priority: 'normal',
        title: '',
        description: '',
        approverIds: []
      };
    },
    
    getSelectedApprovers() {
      const selectedIds = this.newProcessForm.approverIds || [];
      const approvers = selectedIds.map(id => {
        return this.userList.find(user => String(user.id) === String(id));
      }).filter(Boolean);
      return approvers.filter((user, index, arr) => {
        return arr.findIndex(item => String(item.id) === String(user.id)) === index;
      });
    },
    
    // 数据处理方法
    applyInitialSelectedRow() {
      if (!this.initialSelectedRow || Object.keys(this.initialSelectedRow).length === 0) return
      this.handleRowClick(this.initialSelectedRow)
      this.orderNo = this.tableOrderNum
      this.productCode = this.tableProductCode
      this.productName = this.tableProductName
      this.processName = this.tableProcessName
    },
    handleRowClick(row) {
      this.selectedRow = row
      this.tableOrderNum = row.订单号 || row.计划号 || row.生产订单 || ''
      this.tableProductCode = row.产品编码 || row.零件编码 || row.物料编码 || ''
      this.tableProductName = row.产品名称 || row.零件名称 || row.物料名称 || ''
      this.tableProcessName = row.工序名称 || ''
    },
    
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },

    // 提交处理方法
    // 调用简化版存储过程的方法
submitNewProcess() {
  if(!this.selectedRow){
    return this.$message.warning('请选择绑定信息');
  }

  this.$refs.processForm.validate((valid) => {
    if (valid) {
      this.submitting = true;
      
      const approvers = this.getSelectedApprovers();
      if (approvers.length === 0) {
        this.submitting = false;
        return this.$message.warning('请选择审批人');
      }
      const approverId = approvers.map(user => user.id).join(',');
      const approverName = approvers.map(user => user.name).join(',');
      
      const params = []
      params.push(['流程标题', this.newProcessForm.title])
      params.push(['流程描述', this.newProcessForm.description])
      params.push(['优先级', this.newProcessForm.priority || 'normal'])
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['发起人姓名', this.$store.state.user.name])
      params.push(['审批人ID', approverId])
      params.push(['审批人姓名', approverName])
      params.push(['新流程ID', '0'])
      params.push(['已关联计划号', this.tableOrderNum || ''])
      params.push(['零件名称', this.tableProductName || ''])
      params.push(['零件编号', this.tableProductCode || ''])
      params.push(['工序名称', this.tableProcessName || ''])
      
      console.log('简化版参数:', params);

      // 调用简化版存储过程
      const data = this.CreateData('11', 'sp_创建流程_简化版', params)
      
      this.ExecDatabase(data).then((response) => {
        console.log('简化版返回:', response);
        if(response.data && response.data.length > 0){
          const result = response.data[0];
          if(result.结果 == 1){
            this.$message.success('流程创建成功！流程ID: ' + result.新流程ID);
            this.createDialogVisible = false;
            this.resetNewProcessForm();
            this.searchTable();
            this.searchTable1();
          } else {
            this.$message.error('创建失败: ' + (result.消息 || '未知错误'));
          }
        }
        this.submitting = false;
      }).catch((error) => {
        console.error('API调用错误:', error);
        this.$message.error('保存失败');
        this.submitting = false;
      }) 
    }
  });
},
    submitHandle(task) {
      const params = []
      params.push(['流程ID', task.流程ID])
      params.push(['节点ID', task.节点ID])
      params.push(['审批人ID', this.$store.state.user.id])
      params.push(['审批人姓名', this.$store.state.user.name])
      params.push(['处理结果', this.$refs.approvalForm.model.result])
      params.push(['审批意见', this.$refs.approvalForm.model.comment])
      params.push(['成功',''])
      
      const data = this.CreateData('12', 'sp_处理审批', params)
      this.ExecDatabase(data).then((response) => {
       
          this.$message.success('处理完成');
          this.handleDialogVisible = false;
          this.searchTable1();
          this.getProcessedTasks();
        
      }).catch(() => {
        this.$message.error('处理失败')
      }) 
    },
    
    confirmTransfer() {
      if (!this.transferForm.newApproverId) {
        this.$message.warning('请选择目标人员');
        return;
      }
      
      this.users.forEach(user => {
        if(user.id == this.transferForm.newApproverId){
          this.transferForm.newApproverName = user.name
        }
      });
      
      if (!this.transferForm.reason) {
        this.$message.warning('请输入转办原因');
        return;
      }
      
      this.transferLoading = true;
      const params = []
      params.push(['流程ID', this.currentTask.流程ID])
      params.push(['节点ID', this.currentTask.节点ID])
      params.push(['原审批人ID', this.$store.state.user.id])
      params.push(['原审批人姓名', this.$store.state.user.name])
      params.push(['新审批人ID', this.transferForm.newApproverId])
      params.push(['新审批人姓名', this.transferForm.newApproverName])
      params.push(['转办原因', this.transferForm.reason])
      params.push(['成功', ''])
      
      const data = this.CreateData('12', 'sp_转办流程', params)
      this.ExecDatabase(data).then((response) => {
        
          this.$message.success('转办成功！');
          this.transferDialogVisible = false;
          this.searchTable1();
        
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.transferLoading = false;
      })
    },
    
    confirmComplete() {
      if (!this.completeForm.reason) {
        this.$message.warning('请输入完结原因');
        return;
      }
      
      const params = []
      params.push(['流程ID', this.selectProcess.流程ID])
      params.push(['发起人ID', this.$store.state.user.id])
      params.push(['发起人姓名', this.$store.state.user.name])
      params.push(['完成类型', this.completeForm.result])
      params.push(['完成原因', this.completeForm.reason])
      params.push(['成功', ''])
      
      const data = this.CreateData('11', 'sp_完成流程', params)
      this.ExecDatabase(data).then((response) => {
       
          this.$message.success('操作成功！');
          this.completeDialogVisible = false;
          this.searchTable();
        
      }).catch(() => {
        this.$message.error('保存失败')
      }).finally(() => {
        this.completeLoading = false;
      })
    },
    // 查看详情方法
    viewProcessDetail(process) {
      var params = []
      params.push(['流程ID', process.流程ID])
      var data = this.CreateData('11', 'sp_获取流程详情', params)
      this.ExecDatabase(data).then(response => {
        this.加载中 = false
        const result = JSON.parse(response.data[0]["JSON_F52E2B61-18A1-11d1-B105-00805F49916B"])
        const processInfo = JSON.parse(result.流程信息);
        const steps = JSON.parse(result.步骤信息);
        var  approvalRecords = ''
        if(result.审批记录){
          approvalRecords = JSON.parse(result.审批记录);
        }
        this.currentProcess = {
          'processInfo': processInfo,
          'steps': steps,
          'approvalRecords': approvalRecords,
        }
        console.log(this.currentProcess)
        
        this.detailDialogVisible = true;
      }).catch(() => {
        this.加载中 = false
      })
    },

    // 工具方法
    getPriorityType(priority) {
      const map = { urgent: 'danger', high: 'warning', normal: 'success' };
      return map[priority] || 'info';
    },
    
    getPriorityText(priority) {
      const map = { urgent: '紧急', high: '高', normal: '普通' };
      return map[priority] || '普通';
    },
    
    getStatusType(status) {
      const map = { processing: 'warning', completed: 'success', rejected: 'danger', cancelled: 'info' };
      return map[status] || 'info';
    },
    
    getStatusText(status) {
      const map = { processing: '审批中', completed: '已完成', rejected: '已拒绝', cancelled: '已取消' };
      return map[status] || status;
    },
    
    isUrgent(deadline) {
      return new Date(deadline) - new Date() < 24 * 60 * 60 * 1000;
    },
    
    
  }
};
</script>

<style>
	.workflow-container {
			padding: 20px;
			min-height: 100%;
	}
	.page-header {
			background: #fff;
			padding: 20px;
			margin-bottom: 20px;
			border-radius: 4px;
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			display: flex;
			justify-content: space-between;
			align-items: center;
	}
	.workflow-tabs {
			background: #fff;
			border-radius: 4px;
			overflow: hidden;
	}
	.filter-bar {
			padding: 15px;
			background: #fff;
			margin-bottom: 15px;
			border-radius: 4px;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
	}
	.filter-item {
			margin-right: 15px;
			margin-bottom: 10px;
	}
	.process-card {
			margin-bottom: 15px;
			cursor: pointer;
			transition: all 0.3s;
	}
	.process-card:hover {
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}
	.priority-tag {
			margin-left: 10px;
	}
	.footer-buttons {
			margin-top: 20px;
			text-align: right;
	}
	.empty-state {
			text-align: center;
			padding: 40px 0;
			color: #909399;
	}
	.stats-card {
			text-align: center;
			padding: 20px;
			cursor: pointer;
			transition: all 0.3s;
	}
	.stats-card:hover {
			transform: translateY(-5px);
			box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
	}
	.stats-number {
			font-size: 24px;
			font-weight: bold;
			color: #409EFF;
			margin: 10px 0;
	}
	.stats-label {
			color: #909399;
	}
	.transfer-actions {
			margin: 10px 0;
			padding: 10px;
			background: #f5f7fa;
			border-radius: 4px;
	}
	.complete-dialog .el-dialog__body {
			max-height: 60vh;
			overflow-y: auto;
	}
	.node-status {
			display: inline-block;
			padding: 2px 8px;
			border-radius: 4px;
			font-size: 12px;
			margin-left: 10px;
	}
	.status-transferred {
			background: #fdf6ec;
			color: #e6a23c;
	}
</style>
