<template>
  <div class="apaas-custom-page-mydemo custom-page">
    <template v-if="!showEngineCheck">
      <div class="page-header">
        <div class="title">
          竞品发动机审核
        </div>
      </div>

      <div class="page-search-panel">
        <div class="search-fields">
          <div class="search-field">
            <span class="field-label">流程主题</span>
            <el-input v-model="searchPanelValue.processTopic" placeholder="请输入" />
          </div>
          <div class="search-field">
            <span class="field-label">产品型号</span>
            <el-input v-model="searchPanelValue.modelName" placeholder="请输入" />
          </div>

          <div class="search-field">
            <span class="field-label">子系统</span>
            <el-input v-model="searchPanelValue.subsystemName" placeholder="请输入" />
          </div>
          <div class="search-field">
            <span class="field-label">申请人</span>
            <el-select
              v-model="searchPanelValue.applicant"
              filterable
              remote
              reserve-keyword
              placeholder="请输入申请人姓名搜索"
              :remote-method="handleApplicantSearch"
              :loading="applicantLoading"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="person in applicantOptions"
                :key="person.userId"
                :value="person.userId"
                :label="person.username"
              >
                <span class="username-text">{{ person.username }}</span>
                <span class="user-id-text">{{ person.userNumber }}</span>
              </el-option>
            </el-select>
          </div>
          <div class="search-field">
            <span class="field-label">当前状态</span>
            <el-select v-model="searchPanelValue.statusDescription" placeholder="请选择" clearable>
              <el-option label="审批中" value="审批中" />
              <el-option label="已通过" value="已通过" />
              <el-option label="已撤回" value="已撤回" />
            </el-select>
          </div>
          <div class="search-actions">
            <el-button type="primary" @click="handleSearch">
              查询
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </div>
        </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"
        >
          <template
            v-for="(colConfig, index) in tableConfig.colConfigs"
            v-slot:[colConfig.customSlot]="{ row, rowIndex }"
          >
            <div v-if="colConfig.customSlot === 'options'" :key="index + '' + rowIndex">
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleViewProgress(row)"
              >
                查看进度
              </a>
            </div>
            <div v-if="colConfig.customSlot === 'statusDescription'" :key="index + '' + rowIndex">
              <span v-if="row[colConfig.prop] === '审核中'" class="status-tag status-approving"
                >审核中</span
              >
              <span v-else-if="row[colConfig.prop] === '已通过'" class="status-tag status-approved"
                >已通过</span
              >
              <span v-else-if="row[colConfig.prop] === '已拒绝'" class="status-tag status-withdrawn"
                >已拒绝</span
              >
              <span v-else class="status-tag status-default">{{ row[colConfig.prop] }}</span>
            </div>
          </template>

          <template slot="empty">
            <div class="table-empty">
              <x-empty-page></x-empty-page>
            </div>
          </template>
        </x-vxe-table>
      </div>
    </template>
    <engine-check
      v-else
      :detail="currentCheckDetail"
      :engine-type="'竞品'"
      @close="closeEngineCheck"
    />

    <!-- 审批弹窗 -->
    <el-dialog
      title="审批"
      :visible.sync="approvalDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
      @close="handleApprovalDialogClose"
    >
      <el-form
        ref="approvalForm"
        :model="approvalFormData"
        :rules="approvalFormRules"
        label-width="80px"
      >
        <el-form-item label="审批结果" prop="operator">
          <el-radio-group v-model="approvalFormData.operator">
            <el-radio label="PASS">
              同意
            </el-radio>
            <el-radio label="REJECT">
              拒绝
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明" prop="comment">
          <el-input
            v-model="approvalFormData.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批说明"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleApprovalDialogClose">
          取消
        </el-button>
        <el-button type="primary" :loading="approvalSubmitting" @click="handleApprovalSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { getUserId } from '@/utils'
import EngineCheck from './engineCheck.vue'

const createDefaultSearch = () => ({
  loginUserId: getUserId(),
  processTopic: '', // 流程主题
  modelName: '', // 产品型号
  subsystemName: '', // 子系统
  applicant: '', // 申请人
  statusDescription: '', // 当前状态
  ycOrOth: '竞品'
})

export default {
  name: 'SelfEngineCheck',
  components: {
    EngineCheck
  },
  data: function() {
    return {
      searchPanelValue: createDefaultSearch(),
      tableData: [],
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      showEngineCheck: false,
      currentCheckDetail: null,
      approvalDialogVisible: false,
      currentApprovalRow: null,
      approvalFormData: {
        operator: 'PASS',
        comment: ''
      },
      approvalSubmitting: false,
      // 申请人搜索相关
      applicantOptions: [],
      applicantLoading: false,
      applicantSearchTimer: null // 防抖定时器
    }
  },
  computed: {
    tableConfig() {
      return {
        rowDraggable: false,
        colConfigs: [
          {
            prop: 'processTopic',
            label: '流程主题',
            showOverflowTooltip: true,
            minWidth: '120'
          },
          {
            prop: 'modelName',
            label: '产品型号',
            showOverflowTooltip: true,
            minWidth: '120'
          },
         
          {
            prop: 'applicant',
            label: '申请人',
            showOverflowTooltip: true,
            minWidth: '100'
          },
          {
            prop: 'creationDate',
            label: '申请时间',
            showOverflowTooltip: true,
            minWidth: '160'
          },
          {
            prop: 'statusDescription',
            label: '当前状态',
            customSlot: 'statusDescription',
            showOverflowTooltip: true,
            minWidth: '100',
            align: 'center'
          },
          {
            prop: 'approverPersons',
            label: '当前审批人',
            showOverflowTooltip: true,
            minWidth: '100'
          },
          {
            prop: 'options',
            label: '操作',
            customSlot: 'options',
            align: 'center',
            width: '180',
            fixed: 'right'
          }
        ],
        seqType: 'seq',
        layout: 'total, prev, pager, next, sizes'
      }
    },
    approvalFormRules() {
      return {
        result: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        opinion: [{ required: true, message: '请输入审批说明', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadUserSelfRole()
    this.loadData()
  },
  beforeDestroy() {
    // 清理定时器
    if (this.applicantSearchTimer) {
      clearTimeout(this.applicantSearchTimer)
      this.applicantSearchTimer = null
    }
  },
  methods: {
    // 判断当前用户是否是申请人
    isApplicant(row) {
      if (!row) return false
      const currentUserId = getUserId()
      // 检查 createdBy 字段，可能是 userId 或 userNumber
      return (
        row.createdBy === currentUserId ||
        row.createdById === currentUserId ||
        row.createBy === currentUserId ||
        row.createById === currentUserId
      )
    },
    // 判断当前用户是否是审批人
    isApprover(row) {
      if (!row) return false
      const currentUserId = getUserId()

      // 检查 currentApprovers 数组（如果有）
      if (row.currentApprovers && Array.isArray(row.currentApprovers)) {
        return row.currentApprovers.some(
          (approver) =>
            approver.userId === currentUserId ||
            approver.userNumber === currentUserId ||
            approver.id === currentUserId
        )
      }

      // 检查 approverPersons（可能是字符串或对象数组）
      if (row.approverPersons) {
        if (Array.isArray(row.approverPersons)) {
          return row.approverPersons.some((approver) => {
            const approverId = approver.userId || approver.userNumber || approver.id || approver
            return approverId === currentUserId
          })
        }
      }

      // 检查 approverPersonIds（如果有这个字段）
      if (row.approverPersonIds && Array.isArray(row.approverPersonIds)) {
        return row.approverPersonIds.includes(currentUserId)
      }

      return false
    },
    // 判断是否显示审批按钮
    // 审批按钮：只有审批人可以看见，提交人不能看见（除非既是审批人又是提交人，此时可以看见）
    canShowApproveButton(row) {
      if (!row || row.statusDescription !== '审核中') {
        return false
      }
      // 如果是审批人，就可以显示审批按钮
      return this.isApprover(row)
    },
    // 判断是否显示撤回按钮
    // 撤回按钮：只有提交人可以看见，审批人不能看见（除非既是审批人又是提交人，此时可以看见）
    canShowWithdrawButton(row) {
      if (!row || row.statusDescription !== '审核中') {
        return false
      }
      // 如果是提交人，就可以显示撤回按钮
      return this.isApplicant(row)
    },
    // 加载用户自身角色权限
    loadUserSelfRole() {
      const request = {
        ...api.GET_USER_SELF_ROLE,
        params: {
          userOrDepID: getUserId()
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            // 将权限数据存储到 localStorage
            try {
              localStorage.setItem('user_self_role', JSON.stringify(resp.data))
            } catch (err) {
              console.error('存储权限数据到 localStorage 失败:', err)
            }
          }
        })
        .asyncErrorCatch((err) => {
          console.error('获取用户自身角色失败:', err)
        })
    },
    pageSizeChange(size) {
      this.pagination.pageSize = size
      this.loadData()
    },
    rowClickEvent(row) {
      console.warn(row)
    },
    currentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.loadData()
    },
    selectDataChange(data) {
      this.$emit('select-data-change', data)
    },
    resetSearch() {
      // 重置所有搜索项
      const defaultValues = createDefaultSearch()
      Object.keys(defaultValues).forEach((key) => {
        this.$set(this.searchPanelValue, key, defaultValues[key])
      })
      // 清空申请人选项
      this.applicantOptions = []
      // 触发查询
      this.handleSearch()
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadData()
    },
    // 申请人远程搜索
    handleApplicantSearch(query) {
      if (!query || query.trim() === '') {
        // 空查询时，只保留已选择的人员在选项中
        if (this.searchPanelValue.applicant) {
          const selectedOption = this.applicantOptions.find(
            (opt) => opt.userId === this.searchPanelValue.applicant
          )
          if (selectedOption) {
            this.applicantOptions = [selectedOption]
          } else {
            this.applicantOptions = []
          }
        } else {
          this.applicantOptions = []
        }
        return
      }

      // 清除之前的定时器
      if (this.applicantSearchTimer) {
        clearTimeout(this.applicantSearchTimer)
      }

      // 使用防抖，延迟300ms执行
      this.applicantSearchTimer = setTimeout(() => {
        const trimmedQuery = query.trim()
        if (!trimmedQuery) {
          this.applicantOptions = []
          return
        }

        this.applicantLoading = true
        const request = {
          ...api.GET_ALLUSERS,
          params: {
            name: trimmedQuery
          },
          disableSuccessMsg: true
        }

        this.$request(request)
          .asyncThen((resp) => {
            const respData = resp && resp.data
            let result = []
            if (Array.isArray(respData)) {
              result = respData
            } else if (respData && Array.isArray(respData.result)) {
              result = respData.result
            } else if (respData && respData.data && Array.isArray(respData.data)) {
              result = respData.data
            }

            // 转换为选项格式：{userId: user.userId, username: user.username, userNumber: user.userNumber}
            const users = result
              .map((user) => ({
                userId: user.userId || user.id,
                username: user.username || user.name,
                userNumber: user.userNumber || user.userId || user.id
              }))
              .filter((user) => user.userId && user.userNumber)

            // 如果已选择申请人，确保已选择的人员在选项中
            const selectedOption = this.searchPanelValue.applicant
              ? this.applicantOptions.find((opt) => opt.userId === this.searchPanelValue.applicant)
              : null

            // 去重：使用 Map 确保每个 userId 只出现一次
            const optionsMap = new Map()
            // 先添加已选择的选项
            if (selectedOption) {
              optionsMap.set(selectedOption.userId, selectedOption)
            }
            // 再添加新的搜索结果
            users.forEach((user) => {
              if (user.userId && !optionsMap.has(user.userId)) {
                optionsMap.set(user.userId, user)
              }
            })
            this.applicantOptions = Array.from(optionsMap.values())
            this.applicantLoading = false
          })
          .asyncErrorCatch((err) => {
            console.error('搜索申请人失败:', err)
            // 搜索失败时，保留已选择的人员信息
            if (this.searchPanelValue.applicant) {
              const selectedOption = this.applicantOptions.find(
                (opt) => opt.userId === this.searchPanelValue.applicant
              )
              if (selectedOption) {
                this.applicantOptions = [selectedOption]
              } else {
                this.applicantOptions = []
              }
            } else {
              this.applicantOptions = []
            }
            this.applicantLoading = false
          })
      }, 300)
    },
    handleViewProgress(row) {
      // 通过API获取审批详情
      const flowId = row.flowId || row.id
      if (!flowId) {
        this.$message({
          type: 'error',
          message: '缺少审批ID，无法查看详情'
        })
        return
      }
      this.showEngineCheck = true
      this.currentCheckDetail = row
    },
    closeEngineCheck() {
      this.showEngineCheck = false
      this.currentCheckDetail = null
    },
    handleApprove(row) {
      // 打开审批弹窗
      this.currentApprovalRow = row
      this.approvalFormData = {
        operator: 'PASS',
        comment: ''
      }
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    handleApprovalSubmit() {
      // 表单验证
      this.$refs.approvalForm.validate((valid) => {
        if (valid) {
          if (!this.currentApprovalRow) {
            this.$message.error('缺少审批数据')
            return
          }

          const flowId = this.currentApprovalRow.flowId || this.currentApprovalRow.id
          if (!flowId) {
            this.$message.error('缺少流程ID，无法提交审批')
            return
          }

          // 构建提交数据
          const submitData = {
            approvalId: flowId,
            operator: this.approvalFormData.operator,
            comment: this.approvalFormData.comment,
            userId: getUserId()
          }

          // 调用审批接口
          const request = {
            ...api.HANDLE_ENGINE_CHECK,
            params: submitData
          }

          this.approvalSubmitting = true
          this.$request(request)
            .asyncThen((resp) => {
              console.log('审批提交成功')
              this.loadData()
              this.approvalDialogVisible = false
              this.currentApprovalRow = null
              this.approvalSubmitting = false
              // 重新加载数据
            })
            .asyncErrorCatch((err) => {
              console.error('审批提交失败:', err)
              this.approvalSubmitting = false
            })
        }
      })
    },
    handleApprovalDialogClose() {
      // 关闭弹窗，重置表单
      this.approvalDialogVisible = false
      this.currentApprovalRow = null
      this.approvalFormData = {
        result: 'PASS',
        opinion: ''
      }
      // 清除表单验证
      if (this.$refs.approvalForm) {
        this.$refs.approvalForm.clearValidate()
      }
    },
    handleWithdraw(row) {
      const request = {
        ...api.RETURN_ENGINE_CHECK,
        params: {
          approvalId: row.id
        }
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log('撤回成功')
          this.loadData()
        })
        .asyncErrorCatch((err) => {
          console.error('撤回失败:', err)
        })
    },
    loadData() {
      // TODO: 替换为实际的API调用
      const request = {
        ...api.ENGINE_CHECK_LIST,
        params: {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ycOrOth: '竞品',
          // userID: getUserId(),
          ...this.searchPanelValue
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.tableData = resp.data.list || []
          this.pagination.total = resp.data.totalCount || 0
        })
        .asyncErrorCatch((err) => {
          console.error('查询失败:', err)
          // 临时模拟数据
          this.tableData = []
          this.pagination.total = 0
        })
    }
  }
}
</script>

<style lang="scss">
// 申请人选择器样式
::v-deep .el-select-dropdown__item {
  display: flex !important;
  justify-content: space-between !important;
  padding-right: 20px !important;
}
.username-text {
  color: #303133 !important;
  display: inline-block;
  text-align: left !important;
}
.user-id-text {
  color: #909399 !important;
  display: inline-block;
  margin-left: 20px;
  text-align: right !important;
}

.custom-page {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  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;
    overflow: auto;

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

  .page-search-panel {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .search-fields {
      max-height: 200px;
      display: flex;
      flex-wrap: wrap;
      flex-direction: row;
      gap: 16px 32px;
      width: 100%;
    }

    .search-field {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1 1 calc((100% - 96px) / 4) !important;
      max-width: calc(25% - 32px) !important;
      .field-label {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        white-space: nowrap;
        min-width: 80px !important;
        text-align: justify;
        text-align-last: justify;
        text-justify: inter-ideograph;
      }

      .el-input,
      .el-select {
        width: 170px;
      }

      ::v-deep .el-input__inner,
      ::v-deep .el-select .el-input__inner {
        height: 32px;
        line-height: 32px;
      }
    }

    .search-actions {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12px;

      ::v-deep .el-button {
        padding: 0 16px;
        font-size: 14px;
        border-radius: 4px;
        height: 32px;
        line-height: 32px;
      }
    }
  }

  .page-data-list {
    display: flex;
    padding: 20px;

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

  .status-tag {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    line-height: 1.5;

    &.status-approving {
      background: #e6a23c;
      color: white;
    }

    &.status-approved {
      background: #67c23a;
      color: white;
    }

    &.status-withdrawn {
      background: #f56c6c;
      color: white;
    }
  }
}
</style>
