<template>
  <div class="apaas-custom-page-mydemo custom-page">
    <template v-if="!showProgressDetail">
      <div class="page-search-panel">
        <el-form class="search-list">
          <div class="search-component">
            <el-form-item label="模板名称">
              <el-input v-model="searchPanelValue.templateName" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="search-component">
            <el-form-item label="状态">
              <el-select
                v-model="searchPanelValue.status"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="search-component">
            <el-form-item label="申请时间">
              <el-date-picker v-model="searchPanelValue.createDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择"></el-date-picker>
            </el-form-item>
          </div>
          <div class="search-component">
            <el-form-item label="申请人">
              <el-input v-model="searchPanelValue.username" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
        </el-form>

        <div class="search-button-group">
          <el-button native-type="reset" @click="resetSearch()">
            重置
          </el-button>
          <el-button type="primary" @click="handleSearch()">
            查询
          </el-button>
        </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 === 'status'" :key="index + '' + rowIndex">
              <span v-if="row[colConfig.prop] === '审批中' || row[colConfig.prop] === 'APPROVING'" class="status-tag status-approving">
                审批中
              </span>
              <span v-else-if="row[colConfig.prop] === '已通过' || row[colConfig.prop] === 'COMPLETE'" class="status-tag status-approved">
                已通过
              </span>
              <span v-else-if="row[colConfig.prop] === '已退回' || row[colConfig.prop] === 'REJECTED'" class="status-tag status-rejected">
                已退回
              </span>
              <span v-else-if="row[colConfig.prop] === '已撤回' || row[colConfig.prop] === 'RETURNED'" class="status-tag status-rejected">
                已撤回
              </span>
              <span v-else class="status-tag status-default">
                {{ row[colConfig.prop] }}
              </span>
            </div>
            <div v-if="colConfig.customSlot === 'version'" :key="index + '' + rowIndex">
              <span v-if="row[colConfig.prop]">
                V{{ row[colConfig.prop] }}
              </span>
              <span v-else>-</span>
            </div>
            <div v-if="colConfig.customSlot === 'currentApprover'" :key="index + '' + rowIndex">
              <span v-if="row.currentApprovers && row.currentApprovers.length > 0">
                {{ row.currentApprovers.map(item => item.username).join(',') || '-' }}
              </span>
              <span v-else>-</span>
            </div>
            <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>
              <!-- <template>
                <span v-if="row.status === 'APPROVING'" class="link-divider">|</span>
                <a
                  v-if="row.status === 'APPROVING'"
                  href="javascript:void(0)"
                  class="el-link el-link--primary"
                  @click.stop="handleApprove(row)"
                >
                  审批
                </a>
              </template>
              <template>
                <span class="link-divider">|</span>
                <a
                  href="javascript:void(0)"
                  class="el-link el-link--primary"
                  @click.stop="handleRecall(row)"
                >
                  撤回
                </a>
              </template> -->
            </div>
          </template>

          <template slot="empty">
            <div class="table-empty">
              <x-empty-page></x-empty-page>
            </div>
          </template>
        </x-vxe-table>
      </div>
    </template>
    <approval-progress-detail v-else :detail="currentApprovalDetail" @close="closeProgressDetail" @refresh="handleRefresh" />

    <!-- 审批弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="approvalDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
      @close="handleApprovalDialogClose"
    >
      <el-form ref="approvalForm" :model="approvalFormData" label-width="80px">
        <el-form-item label="审核">
          <el-radio-group v-model="approvalFormData.result">
            <el-radio label="PASS">
              通过
            </el-radio>
            <el-radio label="REJECT">
              退回
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="approvalFormData.opinion"
            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 ApprovalProgressDetail from './approvalProgressDetail.vue'

export default {
  name: 'ApprovalManagement',
  components: {
    ApprovalProgressDetail
  },
  data: function() {
    return {
      searchPanelValue: {
        templateName: '',
        status: '',
        createDate: '',
        username: ''
      },
      statusOptions: [
        { id: 'APPROVING', label: '审批中' },
        { id: 'COMPLETE', label: '已通过' },
        { id: 'REJECTED', label: '已退回' },
        { id: 'RETURNED', label: '已撤回' }
      ],
      tableData: [],
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      showProgressDetail: false,
      currentApprovalDetail: null,
      approvalDialogVisible: false,
      approvalFormData: {
        result: '',
        opinion: ''
      },
      approvalSubmitting: false,
      currentApprovalRow: null
    }
  },
  computed: {
    tableConfig() {
      return {
        rowDraggable: false,
        colConfigs: [
          { prop: 'templateName', label: '模板名称', showOverflowTooltip: true, minWidth: '120' },
          { prop: 'version', label: '版本', customSlot: 'version', showOverflowTooltip: true, minWidth: '140' },
          { prop: 'username', label: '申请人', showOverflowTooltip: true, minWidth: '100' },
          {
            prop: 'createdTime',
            label: '申请时间',
            showOverflowTooltip: true,
            minWidth: '160'
          },
          {
            prop: 'status',
            label: '当前状态',
            customSlot: 'status',
            showOverflowTooltip: true,
            minWidth: '100',
            align: 'center'
          },
          {
            prop: 'currentApprovers',
            label: '当前审批人',
            customSlot: 'currentApprover',
            showOverflowTooltip: true,
            minWidth: '120'
          },
          {
            prop: 'options',
            label: '操作',
            customSlot: 'options',
            align: 'center',
            width: '200',
            fixed: 'right'
          }
        ],
        seqType: 'seq',
        layout: 'total, prev, pager, next, sizes'
      }
    }
  },
  created() {
    this.loadUserSelfRole()
    this.loadData()
  },
  methods: {
    // 加载用户自身角色权限
    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)
    },
    handleViewProgress(row) {
      // 通过API获取审批详情
      const flowId = row.flowId
      if (!flowId) {
        this.$message.error('缺少审批ID，无法查看详情')
        return
      }
      this.showProgressDetail = true
      console.log(row)
      this.currentApprovalDetail = row // 先清空，等待加载
    },
    handleApprove(row) {
      this.currentApprovalRow = row
      this.approvalFormData = {
        result: '',
        remarks: ''
      }
      this.approvalSubmitting = false
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    handleApprovalDialogClose() {
      this.approvalDialogVisible = false
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      this.currentApprovalRow = null
      // 清除表单验证
      if (this.$refs.approvalForm) {
        this.$refs.approvalForm.clearValidate()
      }
    },
    handleApprovalSubmit() {
      // 验证是否选择了审核结果
      if (!this.approvalFormData.result) {
        this.$message.warning('请选择审核结果（通过或退回）')
        return
      }

      if (!this.currentApprovalRow) {
        this.$message.error('缺少审批信息')
        return
      }

      // 构建提交数据
      const submitData = {
        flowId: this.currentApprovalRow.flowId,
        userId: getUserId(),
        result: this.approvalFormData.result, // 'PASS' 或 'REJECT'
        opinion: this.approvalFormData.opinion || ''
      }

      this.approvalSubmitting = true
      const request = {
        ...api.HANDLE_APPROVAL,
        params: submitData
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.approvalSubmitting = false
          this.handleApprovalDialogClose()
          this.loadData() // 重新加载数据
        })
        .asyncErrorCatch((err) => {
          this.approvalSubmitting = false
          console.error('审批提交失败:', err)
          this.handleApprovalDialogClose()
        })
    },
    canRecall(row) {
      return row.status === 'APPROVING' && row.createdBy === getUserId()
    },
    handleRecall(row) {
      const submitData = {
        flowId: row.flowId,
        userId: getUserId(),
        result: 'RETURN', // 'PASS' 或 'REJECT'
        opinion: ''
      }

      this.approvalSubmitting = true
      const request = {
        ...api.RETURN_APPROVAL,
        params: submitData
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.approvalSubmitting = false
          this.loadData() // 重新加载数据
        })
        .asyncErrorCatch((err) => {
          this.approvalSubmitting = false
          console.error('审批提交失败:', err)
        })
    },
    currentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.loadData()
    },
    selectDataChange(data) {
      this.$emit('select-data-change', data)
    },
    resetSearch() {
      this.searchPanelValue = {
        templateName: '',
        status: '',
        createDate: '',
        username: ''
      }
      this.handleSearch()
    },
    isApprover(row) {
      if (!row.currentApprovers || !Array.isArray(row.currentApprovers)) {
        return false
      }
      return row.currentApprovers.some(item => item.userId === getUserId())
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadData()
    },
    loadData() {
      const request = {
        ...api.GET_APPROVAL_LIST,
        params: {
          userId: getUserId(),
          templateName: this.searchPanelValue.templateName,
          status: this.searchPanelValue.status,
          createDate: this.searchPanelValue.createDate,
          username: this.searchPanelValue.username,
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.tableData = resp.data.result
          this.pagination.total = resp.data.count
        })
        .asyncErrorCatch((err) => {
          console.error('加载数据失败:', err)
        })
      // TODO: 实现实际的数据加载逻辑
      // const request = {
      //   ...api.GET_APPROVAL_LIST,
      //   params: {
      //     userId: JSON.parse(localStorage.getItem('__vuex__local')).authModule.userInfo.userName
      //       ? JSON.parse(localStorage.getItem('__vuex__local')).authModule.userInfo.userName
      //       : JSON.parse(localStorage.getItem('__vuex__local')).authModule.userInfo.username
      //   }
      // }
      // this.$request(request)
      //   .asyncThen((resp) => {
      //     // 处理响应数据
      //   })
      //   .asyncErrorCatch((err) => {
      //     console.error('加载数据失败:', err)
      //   })
    },
    closeProgressDetail() {
      this.showProgressDetail = false
      this.currentApprovalDetail = null
    },
    handleRefresh() {
      // 刷新列表数据
      this.loadData()
    }
  }
}
</script>

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

  .page-search-panel {
    display: flex;
    background: white;
    padding: 16px 20px 16px 20px;
    position: relative;
    justify-content: space-between;

    .search-list {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      margin-right: -16px;
      margin-bottom: 16px;

      .search-component {
        width: calc(25% - 16px);
        padding: 0 16px 16px 0;
        box-sizing: border-box;

        ::v-deep .el-form-item {
          margin-bottom: 0;
          display: flex;
          flex-direction: column;

          .el-form-item__label {
            font-size: 14px;
            line-height: 1.5;
            color: #303133;
            padding: 0;
            text-align: left;
            width: 100% !important;
            margin-bottom: 8px;
            height: auto;
            display: block;
            float: none;
          }

          .el-form-item__content {
            font-size: 14px;
            line-height: 32px;
            margin-left: 0 !important;
            width: 100%;

            .el-input,
            .el-select {
              width: 100%;

              .el-input__inner {
                height: 32px;
                line-height: 32px;
              }
            }
          }
        }
      }
    }

    .search-button-group {
      position: absolute;
      bottom: 16px;
      right: 20px;
      display: flex;
      gap: 8px;

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

        &.el-button--default {
          border-color: #409eff;
          color: #409eff;
          background: white;

          &:hover {
            background: #ecf5ff;
            border-color: #66b1ff;
            color: #66b1ff;
          }

          &:active {
            background: #409eff;
            color: white;
          }
        }

        &.el-button--primary {
          background: #409eff;
          border-color: #409eff;
          color: white;

          &:hover {
            background: #66b1ff;
            border-color: #66b1ff;
          }
        }
      }
    }
  }

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

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

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

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

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

    &.status-default {
      background: #f5f7fa;
      color: #606266;
    }
  }

  .link-divider {
    margin: 0 8px;
    color: #dcdfe6;
  }
}
</style>
