<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="procurementNo">
            <el-input
              v-model="queryParams.procurementNo"
              placeholder="请输入采购编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入采购标题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="queryParams.urgency" placeholder="请选择紧急程度" clearable>
              <el-option
                v-for="dict in (dict.type.procurement_urgency || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </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.procurement_status || [])"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <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-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:procurement: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:procurement: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:procurement:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="procurementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="采购编号" align="center" prop="procurementNo" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="采购标题" align="center" prop="title" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="紧急程度" align="center" prop="urgency" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.procurement_urgency" :value="scope.row.urgency || 'normal'" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.procurement_status" :value="scope.row.status || 'draft'" />
        </template>
      </el-table-column>
      <el-table-column label="中标供应商" align="center" prop="awardedSupplierName" :show-overflow-tooltip="true" width="150" />
      <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:procurement:edit']"
            v-if="scope.row.status === 'draft' || scope.row.status === 'rejected'"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewItems(scope.row)"
            v-hasPermi="['resource:procurement:query']"
          >查看明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewQuotes(scope.row)"
            v-hasPermi="['resource:procurement:query']"
            v-if="scope.row.status === 'approved' || scope.row.status === 'in_progress' || scope.row.status === 'received'"
          >查看报价</el-button>
          <el-dropdown v-if="scope.row.status !== 'received'">
            <span class="el-dropdown-link">
              状态<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.status === 'draft'"
                v-hasPermi="['resource:procurement:edit']"
                @click.native="handleSubmit(scope.row)"
              >提交</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'submitted'"
                v-hasPermi="['resource:procurement:approve']"
                @click.native="handleApprove(scope.row)"
              >审核通过</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'submitted'"
                v-hasPermi="['resource:procurement:approve']"
                @click.native="handleReject(scope.row)"
              >审核驳回</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'approved'"
                v-hasPermi="['resource:procurement:edit']"
                @click.native="handleAward(scope.row)"
              >确认中标</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'in_progress'"
                v-hasPermi="['resource:procurement:edit']"
                @click.native="handleReceive(scope.row)"
              >入库</el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status === 'rejected'"
                v-hasPermi="['resource:procurement:edit']"
                @click.native="handleResubmit(scope.row)"
              >重新提交</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:procurement:remove']"
            v-if="scope.row.status === 'draft'"
          >删除</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="procurementNo">
              <el-input v-model="form.procurementNo" placeholder="请输入采购编号" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入采购标题" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select v-model="form.urgency" placeholder="请选择紧急程度" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.procurement_urgency || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" v-if="form.id">
              <dict-tag :options="dict.type.procurement_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-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>

    <!-- 明细管理弹窗 -->
    <procurement-item-dialog
      :visible.sync="itemDialogOpen"
      :procurement-id="currentProcurementId"
      :procurement-title="currentProcurementTitle"
      :readonly="currentProcurementStatus !== 'draft' && currentProcurementStatus !== 'rejected'"
      @success="handleItemSuccess"
    />

    <!-- 报价管理弹窗 -->
    <procurement-quote-dialog
      :visible.sync="quoteDialogOpen"
      :procurement-id="currentProcurementId"
      :procurement-title="currentProcurementTitle"
      :procurement-status="currentProcurementStatus"
      @success="handleQuoteSuccess"
    />

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

<script>
import {
  listProcurement,
  getProcurement,
  addProcurement,
  updateProcurement,
  delProcurement,
  submitProcurement,
  resubmitProcurement
} from '@/api/resource/procurement'
import ProcurementItemDialog from './components/ProcurementItemDialog'
import ProcurementQuoteDialog from './components/ProcurementQuoteDialog'
import ProcurementStatusDialog from './components/ProcurementStatusDialog'

export default {
  name: 'ResourceProcurement',
  dicts: ['procurement_status', 'procurement_urgency'],
  components: {
    ProcurementItemDialog,
    ProcurementQuoteDialog,
    ProcurementStatusDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      procurementNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请表格数据
      procurementList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 明细管理弹窗
      itemDialogOpen: false,
      // 报价管理弹窗
      quoteDialogOpen: false,
      // 状态流转弹窗
      statusDialogOpen: false,
      // 当前采购申请
      currentProcurementId: null,
      currentProcurementTitle: '',
      currentProcurementStatus: '',
      currentProcurement: null,
      currentAction: null,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        procurementNo: undefined,
        title: undefined,
        urgency: undefined,
        status: undefined
      },
      // 表单校验
      rules: {
        procurementNo: [
          { required: true, message: '采购编号不能为空', trigger: 'blur' },
          { max: 50, message: '采购编号长度不能超过50个字符', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '采购标题不能为空', trigger: 'blur' },
          { max: 200, message: '采购标题长度不能超过200个字符', trigger: 'blur' }
        ],
        urgency: [
          { max: 16, message: '紧急程度长度不能超过16个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询采购申请列表 */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      this.addDateRange(params, this.dateRange, 'Time')
      listProcurement(params).then(response => {
        this.procurementList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        procurementNo: undefined,
        title: undefined,
        urgency: 'normal',
        status: 'draft',
        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.procurementNos = selection.map(item => item.procurementNo)
      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]
      getProcurement(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          procurementNo: data.procurementNo,
          title: data.title,
          urgency: data.urgency || 'normal',
          status: data.status || 'draft',
          remark: data.remark
        }
        this.open = true
        this.title = '编辑采购申请'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProcurement(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProcurement(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.procurementNo)
      } else if (this.procurementNos.length > 0) {
        curNames.push(...this.procurementNos)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除采购编号为' + resNames + '的数据项？').then(() => {
        return delProcurement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 查看明细 */
    handleViewItems(row) {
      this.currentProcurementId = row.id
      this.currentProcurementTitle = row.title
      this.currentProcurementStatus = row.status
      this.itemDialogOpen = true
    },
    /** 查看报价 */
    handleViewQuotes(row) {
      this.currentProcurementId = row.id
      this.currentProcurementTitle = row.title
      this.currentProcurementStatus = row.status
      this.quoteDialogOpen = true
    },
    /** 提交采购申请 */
    handleSubmit(row) {
      this.$modal.confirm('提交后采购申请将进入审核流程，是否确认提交？').then(() => {
        return submitProcurement(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交成功')
      }).catch(() => {})
    },
    /** 审核通过 */
    handleApprove(row) {
      this.currentProcurement = row
      this.currentAction = 'approve'
      this.statusDialogOpen = true
    },
    /** 审核驳回 */
    handleReject(row) {
      this.currentProcurement = row
      this.currentAction = 'reject'
      this.statusDialogOpen = true
    },
    /** 确认中标 */
    handleAward(row) {
      this.currentProcurement = row
      this.currentAction = 'award'
      this.statusDialogOpen = true
    },
    /** 入库 */
    handleReceive(row) {
      this.currentProcurement = row
      this.currentAction = 'receive'
      this.statusDialogOpen = true
    },
    /** 重新提交 */
    handleResubmit(row) {
      this.$modal.confirm('确认重新提交该采购申请？重新提交后将直接进入审核流程。').then(() => {
        return resubmitProcurement(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('重新提交成功，已进入审核流程')
      }).catch(() => {})
    },
    /** 明细操作成功回调 */
    handleItemSuccess() {
      this.getList()
    },
    /** 报价操作成功回调 */
    handleQuoteSuccess() {
      this.getList()
    },
    /** 状态流转成功回调 */
    handleStatusSuccess() {
      this.getList()
    }
  }
}
</script>

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