<script setup>
import { ref,reactive,nextTick } from 'vue'
import { getMyTaskPage,addMyTask,updateMyTask,deleteMyTask,getMyTaskDetail,claim,unclaim,complete,setComment } from './api'
import { getProcessXml, getInstanceTaskList } from '@/api/workflow'
import { baseModelOptions,baseFilterOptions } from './options'
import useUserStore from '@/store/modules/user'
import { ElMessageBox,ElMessage,ClickOutside as vClickOutside } from 'element-plus'
import convert from 'xml-js';
import ProcessView from '@/components-zbry/Bpmn/ProcessView.vue'

const user = useUserStore()
const { proxy } = getCurrentInstance();

const state = reactive({
  baseModelOptions: baseModelOptions(),
  baseFilterOptions: baseFilterOptions(),
  title: "MyTask管理",
  baseModelName: 'MyTask信息',
  addBtnName: '添加MyTask',
  editBtnName: '',
  delBtnName: '',
  primaryKey: 'id',
  getTableFn: getMyTaskPage,
  addFn: addMyTask,
  editFn: updateMyTask,
  deleteFn: deleteMyTask,
  detailFn: getMyTaskDetail,
  showEditBtn: false,
  showDeleteBtn: false,
  handleAdd: () => {
    proxy.$router.push({ path: '/workflow/modeler' });
  },
  handleEdit: (index,row) => {
    proxy.$router.push({ 
      path: '/workflow/modeler',
      query: {
        id: row.id
      }
    });
  },
  rowControl: {
    showEditBtn: false,
    showDelBtn: false
  },
  permission: {//菜单管理中添加权限
    add: 'system:user:list',
    edit: 'system:user:list',
    delete: 'system:user:list',
    detail: 'system:user:list',
  },
  pageInfo: { total: 0, base:{limit: 8,current: 1} },
  pageKeys: {
    limit: 'maxResults',
    start: 'firstResult'
  },
  formOptions: [],
  auditFormOptions: [
    {
        tag: 'BaseSelect',
        label: '审批意见:',
        key: 'comment',
        value: '',
        default: '',
        attribute: {//配置项内容
            placeholder: '请选择审批意见',
            options: [
                { label: '通过', value: 'approved' },
                { label: '拒绝', value: 'rejected' },
            ]
        },
        rules: [
            { required: true, message: '请选择审批意见', trigger: 'change' }
        ]
    },
    {
        tag: 'el-input',
        label: '审批参数:',
        key: 'params',
        value: '',
        default: '',
        attribute: {//配置项内容
            placeholder: '请输入审批意见等其他自定义参数',
        }
    }
  ],
  viewForm: false,
  flowData: [],
  showProcess: false,
  activeName: 'all',
  baseQuery: {

  },
  audit: false,
  rowData: null,
})

const viewForm = (row) => {
  state.formOptions = row.form;
  //nextTick
  if (row.form_values) {
    try {
      const formValues = JSON.parse(row.form_values);
      state.formOptions.forEach(item => {
        if (formValues[item.key]) {
          item.default = formValues[item.key];
          item.value = formValues[item.key];
        }
      });
    } catch (e) {
      console.error('Failed to parse form values:', e);
    }
  }
  console.log('state.formOptions :>> ', state.formOptions);
  state.viewForm = true
}
const table = ref();
const doClaim = (row) => {
  claim({taskId: row.id,userId: user.userId}).then(res => {
    const {getTableData} = table.value;
    getTableData();
  })
}
const doUnclaim = (row) => {
  unclaim({taskId: row.id}).then(res => {
    const {getTableData} = table.value;
    getTableData();
  })
}
const doComplete = (row) => {
  state.audit = true;
  state.rowData = row;
  return;
  ElMessageBox.confirm('是否执行任务,参数写带代码里了', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    setComment({
      taskId: row.id,
      "message": JSON.stringify({message: '执行成功',id: '其他的测试信息',user: '张三',userId: user.userId})
    }).then(res => {
      complete({ 
        taskId: row.id,
        data: {
          "variables": {
            "approvalResult": {
              // "value": "rejected",  // 或者 "rejected"
              "value": "approved",  // 或者 "rejected"
              "type": "String"
            }
          }
        }
      }).then(res => {
        table.value.getTableData();
      })
    })
    
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消执行'
    });
  });
}
const doAudit = () => {
  //获取审批意见
  const comment = state.auditFormOptions[0].value;
  if(!comment){
    proxy.$message.error('请选择审批意见')
    return
  }
  const params = state.auditFormOptions[1].value;
  setComment({
    taskId: state.rowData.id,
    "message": JSON.stringify({message: `执行成功: ${params}`,userId: user.userId})
  }).then(res => {
    complete({ 
      taskId: state.rowData.id,
      data: {
        "variables": {
          "approvalResult": {
            "value": comment,  // approved 或者 "rejected"
            "type": "String"
          }
        }
      }
    }).then(res => {
      state.audit = false;
      table.value.getTableData();
    })
  })
}

const tasksStatus = {};
const taskComment = {};
const drawProcess = (row) => {
  Promise.all([
    getProcessXml(row.processDefinitionId),
      getInstanceTaskList({
          firstResult: 0,
          maxResults: 888,
          processInstanceId: row.processInstanceId,
      })
  ]).then(([processXmlRes, instanceTaskListRes]) => {
      instanceTaskListRes.data.list.map(item => {
          tasksStatus[item.taskDefinitionKey] = item;
          taskComment[item.taskDefinitionKey] = item.comment;
      });
      row.showProcess = true;
      parseBpmnXml(processXmlRes.data.bpmn20Xml);
  });
}
const closeProcess = (row) => {
  row.showProcess = false;
}
const parseBpmnXml = (xml) => {
  const result = convert.xml2js(xml, { compact: true });
  const process = result['bpmn:definitions']['bpmn:process'];
  const tasks = process['bpmn:userTask'];
  const flows = process['bpmn:sequenceFlow'];
  let gateways = process['bpmn:exclusiveGateway'];
  const startEvent = process['bpmn:startEvent'];

  console.log('process :>> ', process);
  // 确保 gateways 是一个数组
  if (gateways && !Array.isArray(gateways)) {
    gateways = [gateways];
  }

  const taskMap = {};
  tasks.forEach(task => {
    taskMap[task._attributes.id] = {
      id: task._attributes.id,
      name: task._attributes.name,
      type: 'task',
      assignee: task._attributes['camunda:assignee'],
      candidateUsers: task._attributes['camunda:candidateUsers'],
      formKey: task._attributes['camunda:formKey'],
      next: []
    };
  });

  const gatewayMap = {};
  if (gateways) {
    gateways.forEach(gateway => {
      gatewayMap[gateway._attributes.id] = {
        id: gateway._attributes.id,
        name: gateway._attributes.name,
        type: 'gateway',
        next: []
      };
    });
  }

  const startEventMap = {};
  if (startEvent) {
    startEventMap[startEvent._attributes.id] = {
      id: startEvent._attributes.id,
      name: startEvent._attributes.name,
      type: 'startEvent',
      next: []
    };
  }
  let firstTaskId = '';
  flows.forEach(flow => {
    const source = flow._attributes.sourceRef;
    const target = flow._attributes.targetRef;
    const condition = flow['bpmn:conditionExpression'];
    const nextNode = { target, condition };

    if (taskMap[source]) {
      taskMap[source].next.push(nextNode);
    } else if (gatewayMap[source]) {
      gatewayMap[source].next.push(nextNode);
    } else if (startEventMap[source]) {
      firstTaskId = target;
    }
  });

  // console.log('Tasks:', taskMap);
  // console.log('Gateways:', gatewayMap);
  // console.log('Start Events:', startEventMap)

  const buildProcessFlow = (taskId, taskMap, gatewayMap, processFlow,condition=null) => {
    if (taskMap[taskId]) {
      const task = taskMap[taskId];
      task.status = tasksStatus[taskId];
      task.comment = taskComment[taskId];
      if(condition) task.condition = condition;
      processFlow.push(task);
      task.next = task.next.map(nextNode => buildProcessFlow(nextNode.target, taskMap, gatewayMap, [],nextNode.condition));
    } else if (gatewayMap[taskId]) {
      const gateway = gatewayMap[taskId];
      
      processFlow.push(gateway);
      gateway.next = gateway.next.map(nextNode => buildProcessFlow(nextNode.target, taskMap, gatewayMap, [],nextNode.condition));
    }
    return processFlow.length === 1 ? processFlow[0] : processFlow;
  };


  // 生成完整的流程数据
  const processFlow = [];
  if (firstTaskId) {
    buildProcessFlow(firstTaskId, taskMap, gatewayMap, processFlow);
  }
  
  nextTick(() => {
    state.flowData = processFlow;
  });
};

const handleClick = () => {
  if(state.activeName == 'all') {
    state.baseQuery = {}
    table.value.getTableData();
  } else {
    state.baseQuery = {
      assignee: user.userId,
      candidateUser: user.userId,
      candidateGroup: user.roles.join(',')
    }
    table.value.getTableData();
  }
}
</script>

<template>
  <div>
    <div style="margin: 10px 0 0 0;">
      <el-tag size="large" @click="state.activeName='all',handleClick()" :type="state.activeName == 'all'?'primary':'info'">全部审批</el-tag>
      <el-tag el-tag size="large" @click="state.activeName='mine',handleClick()" :type="state.activeName == 'mine'?'primary':'info'">我的审批</el-tag>
    </div>
    <!-- <el-tabs v-model="state.activeName" @tab-click="handleClick">
      <el-tab-pane label="全部审批" name="all"></el-tab-pane>
      <el-tab-pane label="我的审批" name="mine"></el-tab-pane>
    </el-tabs> -->
    <BaseTablePage 
      :tableOptions="state" 
      ref="table"
    >
      <template v-slot:column>
        <el-table-column align="center" prop="id" label="任务ID" />
        <el-table-column align="center" prop="name" label="当前任务名称" />
        <el-table-column align="center" prop="processName" label="流程名称" />
        <el-table-column align="center" prop="form_name" label="表单名称" />
        <el-table-column align="center" prop="assignee" label="当前任务执行人Id">
          <template #default="{ row }">
            <span v-if="row.assignee">{{ row.assignee }}</span>
            <span v-else style="color:red">未被领取</span>
          </template>

        </el-table-column>
        <el-table-column align="center" prop="created" label="创建时间">
          <template #default="{ row }">
            <span>{{ $util.dateFormatter.formate(row.created, "yyyy-mm-dd hh:mm") }}</span>
          </template>

        </el-table-column>
        
        
      </template>
      <template #before="scope">
        <el-popover
          trigger="click"
          width="auto"
          @show="drawProcess(scope.row)"
          @hide="closeProcess(scope.row)"
          popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
        >
          <template #reference>
            <el-button type="warning">查看执行情况</el-button>
          </template>
          <template #default>
            <div v-if="scope.row.showProcess">
              <ProcessView :processFlow="state.flowData"></ProcessView>
            </div>
          </template>
        </el-popover>
        <el-button type="primary" @click="viewForm(scope.row)">查看表单</el-button>
        <el-button type="primary" v-if="!scope.row.assignee" @click="doClaim(scope.row)">领取任务</el-button>
        <el-button type="primary" v-if="scope.row.assignee" @click="doUnclaim(scope.row)">取消执行人</el-button>
        <el-button type="primary" v-if="scope.row.assignee" @click="doComplete(scope.row)">执行任务</el-button>
      </template>
    </BaseTablePage>
    <BaseModel
      ref="bm"
      v-if="state.viewForm"
      :title="'表单预览'"
      :modelType="'edit'"
      :columnCount="1"
      :showModel="state.viewForm"
      :width="'35%'"
      :modelOptions="state.formOptions"
      @dialogClose="state.viewForm=false"
      @dialogSubmit="state.viewForm=false"
    >
    </BaseModel>
    <BaseModel
      ref="bm"
      v-if="state.audit"
      :title="'执行审批'"
      :modelType="'edit'"
      :columnCount="1"
      :showModel="state.audit"
      :width="'35%'"
      :modelOptions="state.auditFormOptions"
      @dialogClose="state.audit=false"
      @dialogSubmit="doAudit"
    >
    </BaseModel>
  </div>
</template>

<style scoped>
</style>
