<template>
  <div class="apaas-custom-page-todo custom-page">
    <template v-if="!showEngineDetail && !showEngineCheck && !showApprovalProgressDetail && !showReportDetail">
      <div class="page-header">
        <div class="title">
          我的待办
        </div>
        <div class="operation">
          <x-svg-icon
            :name="'refresh-icon'"
            class="pointer"
            style="cursor: pointer;"
            @click.native="handleRefresh()"
          ></x-svg-icon>
        </div>
      </div>

      <div class="page-data-list">
        <x-vxe-table
          ref="vxeTable"
          :border="true"
          :seqWidth="40"
          :colConfigs="tableConfig.colConfigs"
          :tableData="tableData"
          :rowDraggable="tableConfig.rowDraggable"
          :seqType="tableConfig.seqType"
          :pagination="pagination"
          :layout="tableConfig.layout"
          :seqConfig="tableConfig.seqConfig"
          :autoSize="tableConfig.autoSize"
          :pageConfig="tableConfig.pageConfig"
          class="block-table"
          @table-row-click="rowClickEvent"
          @size-change="pageSizeChange"
          @current-page-change="currentChange"
          @select-data-change="selectDataChange"
        >
          <template v-for="(colConfig, index) in tableConfig.colConfigs" v-slot:[colConfig.customSlot]="{ row, rowIndex }">
            <div v-if="colConfig.customSlot === 'options'" :key="'op' + index + '' + rowIndex">
              <a href="javascript:void(0)" class="el-link el-link--primary" @click.stop="handleRowView(row)">查看</a>
            </div>
          </template>

          <template slot="empty">
            <div class="table-empty">
              <x-empty-page></x-empty-page>
            </div>
          </template>
        </x-vxe-table>
      </div>
    </template>

    <!-- 发动机详情组件 -->
    <engine-detail
      v-if="showEngineDetail && !showEngineCheck"
      :model="currentModel"
      :detail="currentEngineDetail"
      :engine-model-i-d="currentEngineModelID"
      :is-dispatch-mode="isDispatchMode"
      :dispatch-type="dispatchType"
      :responsible-person-id="responsiblePersonId"
      :filled-by="filledBy"
      class="engine-detail-wrapper"
      @back="handleBackFromDetail"
    />

    <!-- 发动机审批组件 -->
    <engine-check
      v-if="showEngineCheck"
      :detail="currentEngineDetail"
      :visible="showEngineCheck"
      :engine-type="engineType"
      class="engine-check-wrapper"
      @close="handleBackFromCheck"
    />

    <!-- 模板审核组件 -->
    <approval-progress-detail
      v-if="showApprovalProgressDetail"
      :detail="currentApprovalDetail"
      :visible="showApprovalProgressDetail"
      class="approval-progress-detail-wrapper"
      @refresh="handleBackFromApprovalProgress"
      @close="handleBackFromApprovalProgress"
    />

    <!-- 对标报告审核组件 -->
    <report-detail
      v-if="showReportDetail"
      :detail="currentReportDetail"
      :visible="showReportDetail"
      class="report-detail-wrapper"
      @close="handleBackFromReport"
    />
  </div>
</template>

<script>
import EngineDetail from './engineDetail.vue'
import EngineCheck from './engineCheck.vue'
import ApprovalProgressDetail from './approvalProgressDetail.vue'
import ReportDetail from './reportDetail.vue'
import { getUserId } from '@/utils'
import api from '@/api/demo'
export default {
  name: 'TodoPage',
  components: {
    EngineDetail,
    EngineCheck,
    ApprovalProgressDetail,
    ReportDetail
  },
  data: function() {
    return {
      tableData: [],
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      showEngineDetail: false,
      showEngineCheck: false,
      currentModel: '',
      currentEngineModelID: '',
      currentEngineDetail: null,
      isDispatchMode: false,
      dispatchType: 'todo', // 默认为分发责任人
      responsiblePersonId: '', // 管理员分发责任人时传递的 responsiblePersonId
      filledBy: '', // 填写发动机参数值时传递的 filledBy
      engineType: '玉柴', // 发动机类型，默认为玉柴
      showApprovalProgressDetail: false, // 是否显示模板审核详情
      currentApprovalDetail: null, // 当前模板审核详情
      showReportDetail: false, // 是否显示对标报告详情
      currentReportDetail: null // 当前对标报告详情
    }
  },
  computed: {
    tableConfig() {
      return {
        rowDraggable: false,
        colConfigs: [
          // { prop: 'documentNo', label: '单据编号', showOverflowTooltip: true, minWidth: '140' },
          { prop: 'processTitle', label: '流程主题', showOverflowTooltip: true, minWidth: '160' },
          { prop: 'currentNode', label: '当前环节', showOverflowTooltip: true, minWidth: '140' },
          // { prop: 'statusCode', label: '状态代号', showOverflowTooltip: true, minWidth: '120' },
          // { prop: 'modelName', label: '产品型号', showOverflowTooltip: true, minWidth: '120' },
          { prop: 'currentProcessor', label: '当前处理人', showOverflowTooltip: true, minWidth: '120' },
          { prop: 'createdBy', label: '创建人', showOverflowTooltip: true, minWidth: '120' },
          { prop: 'creationDate', label: '创建时间', showOverflowTooltip: true, minWidth: '160', align: 'center', formatter: this.formatDateTime },
          { prop: 'options', label: '操作', customSlot: 'options', align: 'center', width: '100', fixed: 'right' }
        ],
        seqType: '',
        seqConfig: {},
        layout: 'total, prev, pager, next, jumper, sizes'
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    pageSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      this.loadData()
    },
    rowClickEvent(row) {
      console.warn(row)
    },
    handleRowView(row) {
      // 根据流程主题判断打开哪种页面
      const dataType = row.dataType || ''
      const isFillParameterMode = dataType === '数据维护'
      const isResponsibleDispatchMode = dataType === '任务分解'
      const isInApprovalMode = dataType === '数据审批'
      const isModelCheck = dataType === '模板审核'
      const isReportCheck = dataType === '对标报告审核'

      // 设置引擎型号信息
      this.currentModel = row.modelName || row.productFullName || ''
      // engineModelID 可能来自不同的字段，需要根据实际情况调整
      this.currentEngineModelID = row.modelId

      // 如果是"数据审批"，打开审批页面
      if (isInApprovalMode) {
        this.currentEngineDetail = { ...row, id: row.documentNo }
        this.showEngineCheck = true
        this.showEngineDetail = false
        this.showApprovalProgressDetail = false
        this.showReportDetail = false
        // 根据数据类型判断发动机类型（可能需要根据实际字段调整）
        // 这里假设有 dataType 字段，或者可以根据其他字段判断
        this.engineType = row.dataType === '竞品' ? '竞品' : '玉柴'
        return
      }

      // 如果是"模板审核"，打开模板审核详情页面
      if (isModelCheck) {
        this.showApprovalProgressDetail = true
        this.showEngineDetail = false
        this.showEngineCheck = false
        this.showReportDetail = false
        // documentNo 对应 flowId，modelId 对应 templateId
        this.currentApprovalDetail = {
          flowId: row.documentNo || '',
          templateId: row.modelId || '',
          ...row
        }
        return
      }

      // 如果是"对标报告审核"，打开对标报告详情页面
      if (isReportCheck) {
        this.showReportDetail = true
        this.showEngineDetail = false
        this.showEngineCheck = false
        this.showApprovalProgressDetail = false
        // documentNo 对应 flowId，modelId 对应 reportId
        this.currentReportDetail = {
          flowId: row.documentNo || '',
          reportId: row.modelId || '',
          ...row
        }
        return
      }

      // 如果是"填写发动机参数值"，打开非分发模式（查看模式）
      // 如果是"管理员分发责任人"，打开分发模式且是分发填写人（显示填写人列，调用UPDATE_PARAM接口）
      // 其他情况打开分发模式且是分发责任人
      if (isFillParameterMode) {
        this.currentEngineDetail = { ...row, id: row.modelId }
        // 填写发动机参数值：非分发模式（只读），传递 filledBy
        this.isDispatchMode = false
        this.dispatchType = 'todo'
        this.filledBy = row.ownerId || ''
        this.responsiblePersonId = ''
      } else if (isResponsibleDispatchMode) {
        this.currentEngineDetail = { ...row, id: row.modelId }
        // 管理员分发责任人：分发填写人模式（显示填写人列，可编辑），传递 responsiblePersonId
        this.isDispatchMode = true
        this.dispatchType = 'update_param'
        this.responsiblePersonId = row.ownerId || ''
        this.filledBy = ''
      } else {
        // 其他分发模式：分发责任人模式（显示责任人列）
        this.isDispatchMode = true
        this.dispatchType = 'todo'
        this.responsiblePersonId = ''
        this.filledBy = ''
      }
      this.showEngineDetail = true
      this.showEngineCheck = false
      this.showApprovalProgressDetail = false
      this.showReportDetail = false
    },
    handleBackFromDetail() {
      this.showEngineDetail = false
      this.currentModel = ''
      this.currentEngineModelID = ''
      this.currentEngineDetail = null
      this.isDispatchMode = false
      this.dispatchType = 'todo'
      this.responsiblePersonId = ''
      this.filledBy = ''
      this.engineType = '玉柴'
    },
    handleBackFromCheck() {
      this.showEngineCheck = false
      this.currentEngineDetail = null
      this.engineType = '玉柴'
      this.loadData() // 刷新待办列表
    },
    handleBackFromApprovalProgress() {
      this.showApprovalProgressDetail = false
      this.currentApprovalDetail = null
      this.loadData() // 刷新待办列表
    },
    handleBackFromReport() {
      this.showReportDetail = false
      this.currentReportDetail = null
      this.loadData() // 刷新待办列表
    },
    currentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.loadData()
    },
    selectDataChange(data) {
      this.$emit('select-data-change', data)
    },
    handleRefresh() {
      this.pagination.currentPage = 1
      this.loadData()
    },
    loadData() {
      const request = {
        ...api.GET_TODO_LIST,
        params: {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          isFinished: 0,
          personId: getUserId()
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.tableData = resp.data.list
          this.pagination.total = resp.data.totalCount
        })
        .asyncErrorCatch((err) => {
          console.error('获取待办列表失败:', err)
          this.$message.error('获取待办列表失败')
        })
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    formatDateTime({ cellValue }) {
      if (!cellValue) return ''
      // 处理 ISO 8601 格式: 2025-12-02T06:36:21.000+0000
      try {
        const date = new Date(cellValue)
        if (isNaN(date.getTime())) return cellValue // 如果无法解析，返回原值

        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        console.error('日期格式化错误:', error)
        return cellValue
      }
    }
  }
}
</script>

<style lang="scss">
.custom-page {
    width: 100%;
    height: 100%;
    overflow-y: auto !important;
    display: flex;
    flex-direction: column;

    .page-header {
      display: flex;
      align-items: center;
      height: 56px;
      position: relative;
      width: 100%;
      min-height: 56px;
      background: #fff;
      border-bottom: 1px solid #ebeef5;
      flex-shrink: 0;

      .title {
        color: #303133;
        font-weight: 700;
        margin-left: 20px;
        flex: 1;
        font-size: 12px;
      }

      .operation {
        display: flex;
        min-width: 330px;
        justify-content: flex-end !important;
        margin-right: 20px;
      }
    }

    .page-data-list {
      display: flex;
      flex: 1;
      min-height: 0;
      padding: 20px;

      .x-empty-page {
        top: 0;
      }
    }

    .engine-detail-wrapper {
      width: 100%;
      height: 100%;
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .engine-check-wrapper {
      width: 100%;
      height: 100%;
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .approval-progress-detail-wrapper {
      width: 100%;
      height: 100%;
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;
    }

    .report-detail-wrapper {
      width: 100%;
      height: 100%;
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;
    }
  }
</style>
