<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="征用编号" prop="requisitionNo">
            <el-input
              v-model="queryParams.requisitionNo"
              placeholder="请输入征用编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="队伍" prop="teamId">
            <el-select v-model="queryParams.teamId" placeholder="请选择队伍" clearable filterable style="width: 100%">
              <el-option
                v-for="team in teamOptions"
                :key="team.id"
                :label="team.teamName"
                :value="team.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in (dict.type.requisition_status || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resource:requisition:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['resource:requisition:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['resource:requisition:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="requisitionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="征用编号" align="center" prop="requisitionNo" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="队伍名称" align="center" prop="teamName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="征用原因" align="center" prop="reason" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.requisition_status" :value="scope.row.status || 'draft'" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approverName" width="100" />
      <el-table-column label="审批时间" align="center" prop="approvedAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvedAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:requisition:edit']"
            v-if="scope.row.status === 'draft' || scope.row.status === 'rejected'"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewAgreements(scope.row)"
            v-hasPermi="['resource:requisition:query']"
          >查看协议</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewCompensations(scope.row)"
            v-hasPermi="['resource:requisition:query']"
            v-if="scope.row.status === 'active' || scope.row.status === 'ended'"
          >查看补偿</el-button>
          <el-dropdown v-if="getAvailableActions(scope.row).length > 0">
            <span class="el-dropdown-link">
              状态<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="action in getAvailableActions(scope.row)"
                :key="action.key"
                v-hasPermi="[action.permission]"
                @click.native="handleStatusAction(scope.row, action.key)"
              >{{ action.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:requisition:remove']"
            v-if="scope.row.status === 'draft' || scope.row.status === 'rejected'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改征用申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="征用编号" prop="requisitionNo">
              <el-input v-model="form.requisitionNo" placeholder="请输入征用编号" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="队伍" prop="teamId">
              <el-select
                v-model="form.teamId"
                :placeholder="form.id ? '请选择队伍' : '请选择可用状态的队伍'"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="team in (form.id ? teamOptions : availableTeamOptions)"
                  :key="team.id"
                  :label="team.teamName"
                  :value="team.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="征用原因" prop="reason">
              <el-input v-model="form.reason" type="textarea" placeholder="请输入征用原因" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" v-if="form.id">
              <dict-tag :options="dict.type.requisition_status" :value="form.status || 'draft'" />
              <el-tooltip content="状态只能通过状态流转操作修改" placement="top">
                <i class="el-icon-question" style="margin-left: 5px; color: #909399;"></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startAt">
              <el-date-picker
                v-model="form.startAt"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endAt">
              <el-date-picker
                v-model="form.endAt"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 状态流转弹窗 -->
    <requisition-status-dialog
      :visible.sync="statusDialogOpen"
      :requisition="currentRequisition"
      :action="currentAction"
      @success="handleStatusSuccess"
    />

    <!-- 协议管理弹窗 -->
    <requisition-agreement-dialog
      :visible.sync="agreementDialogOpen"
      :requisition-id="currentRequisitionId"
      :requisition-title="currentRequisitionTitle"
      :requisition-status="currentRequisitionStatus"
      @success="handleAgreementSuccess"
    />

    <!-- 补偿管理弹窗 -->
    <requisition-compensation-dialog
      :visible.sync="compensationDialogOpen"
      :requisition-id="currentRequisitionId"
      :requisition-title="currentRequisitionTitle"
      :requisition-status="currentRequisitionStatus"
      @success="handleCompensationSuccess"
    />
  </div>
</template>

<script>
import {
  listRequisition,
  getRequisition,
  addRequisition,
  updateRequisition,
  delRequisition,
  approveRequisition,
  rejectRequisition,
  startRequisition,
  endRequisition,
  resubmitRequisition
} from '@/api/resource/requisition'
import { listTeam } from '@/api/resource/team'
import RequisitionStatusDialog from './components/RequisitionStatusDialog'
import RequisitionAgreementDialog from './components/RequisitionAgreementDialog'
import RequisitionCompensationDialog from './components/RequisitionCompensationDialog'

export default {
  name: 'ResourceRequisition',
  dicts: ['requisition_status'],
  components: {
    RequisitionStatusDialog,
    RequisitionAgreementDialog,
    RequisitionCompensationDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      requisitionNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 征用申请表格数据
      requisitionList: [],
      // 队伍选项（用于搜索和编辑）
      teamOptions: [],
      // 可用队伍选项（用于新增）
      availableTeamOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态流转弹窗
      statusDialogOpen: false,
      // 协议管理弹窗
      agreementDialogOpen: false,
      // 补偿管理弹窗
      compensationDialogOpen: false,
      // 当前征用申请
      currentRequisitionId: null,
      currentRequisitionTitle: '',
      currentRequisitionStatus: '',
      currentRequisition: null,
      currentAction: null,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        requisitionNo: undefined,
        teamId: undefined,
        status: undefined
      },
      // 表单校验
      rules: {
        requisitionNo: [
          { required: true, message: '征用编号不能为空', trigger: 'blur' },
          { max: 50, message: '征用编号长度不能超过50个字符', trigger: 'blur' }
        ],
        teamId: [
          { required: true, message: '队伍不能为空', trigger: 'change' }
        ],
        reason: [
          { max: 500, message: '征用原因长度不能超过500个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getTeamList()
    this.getAvailableTeamList()
    this.getList()
  },
  methods: {
    /** 查询征用申请列表 */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      this.addDateRange(params, this.dateRange, 'Time')
      listRequisition(params).then(response => {
        this.requisitionList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查询所有队伍列表（用于搜索和编辑） */
    getTeamList() {
      listTeam({}).then(response => {
        this.teamOptions = response.rows || []
      })
    },
    /** 查询可用队伍列表（用于新增） */
    getAvailableTeamList() {
      listTeam({ status: 'available' }).then(response => {
        this.availableTeamOptions = response.rows || []
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        requisitionNo: undefined,
        teamId: undefined,
        reason: undefined,
        status: 'draft',
        startAt: undefined,
        endAt: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.requisitionNos = selection.map(item => item.requisitionNo)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加征用申请'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getRequisition(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          requisitionNo: data.requisitionNo,
          teamId: data.teamId,
          reason: data.reason,
          status: data.status || 'draft',
          startAt: data.startAt,
          endAt: data.endAt,
          remark: data.remark
        }
        this.open = true
        this.title = '编辑征用申请'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRequisition(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRequisition(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = this.ids;
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.requisitionNo)
      } else if (this.requisitionNos.length > 0) {
        curNames.push(...this.requisitionNos)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除征用编号为' + resNames + '的数据项？').then(() => {
        return delRequisition(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 查看协议 */
    handleViewAgreements(row) {
      this.currentRequisitionId = row.id
      this.currentRequisitionTitle = row.requisitionNo
      this.currentRequisitionStatus = row.status
      this.agreementDialogOpen = true
    },
    /** 查看补偿 */
    handleViewCompensations(row) {
      this.currentRequisitionId = row.id
      this.currentRequisitionTitle = row.requisitionNo
      this.currentRequisitionStatus = row.status
      this.compensationDialogOpen = true
    },
    /** 获取可用操作 */
    getAvailableActions(row) {
      const actions = []
      if (row.status === 'draft') {
        actions.push({ key: 'approve', label: '审批通过', permission: 'resource:requisition:approve' })
        actions.push({ key: 'reject', label: '审批驳回', permission: 'resource:requisition:approve' })
      } else if (row.status === 'approved') {
        actions.push({ key: 'start', label: '开始征用', permission: 'resource:requisition:edit' })
      } else if (row.status === 'active') {
        actions.push({ key: 'end', label: '结束征用', permission: 'resource:requisition:edit' })
      } else if (row.status === 'rejected') {
        actions.push({ key: 'resubmit', label: '重新提交', permission: 'resource:requisition:edit' })
      }
      return actions
    },
    /** 状态操作 */
    handleStatusAction(row, action) {
      if (action === 'resubmit') {
        // 重新提交不需要弹窗，直接确认即可
        this.$modal.confirm('确认重新提交该征用申请？重新提交后将直接进入已审批状态，可以开始征用。').then(() => {
          return resubmitRequisition(row.id)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('重新提交成功，已进入已审批状态')
        }).catch(() => {})
      } else {
        this.currentRequisition = row
        this.currentAction = action
        this.statusDialogOpen = true
      }
    },
    /** 状态流转成功回调 */
    handleStatusSuccess() {
      this.getList()
    },
    /** 协议操作成功回调 */
    handleAgreementSuccess() {
      this.getList()
    },
    /** 补偿操作成功回调 */
    handleCompensationSuccess() {
      this.getList()
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  margin: 0 6px;
}
</style>

