<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入采购物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="项目代号" prop="projectCode">
        <el-select v-model="queryParams.projectCode" placeholder="请选择代号类型" style="width: 100%" filterable
                   @change="handleQuery" :filter-method="filterCode">
          <el-option v-for="dict in dict.type.sys_project_code" :key="dict.value" :label="dict.label"
                     :value="dict.value">
            <span style="float: left">{{ dict.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.value }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNum">
        <el-input
          v-model="queryParams.projectNum"
          placeholder="请输入编号例如XSDM20250909"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="owner">
        <el-input
          v-model="queryParams.owner"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <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-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"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="oaWarehouseRequestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="物品名称" align="center" prop="itemName"/>
      <el-table-column label="数量" align="center" prop="quantity"/>
      <el-table-column label="项目" align="center" prop="projectName"/>
      <el-table-column label="负责人" align="center" prop="owner"/>
      <!-- 表格中的状态列（替换原有列） -->
      <el-table-column label="状态" align="center" prop="status" width="160">
        <template slot-scope="{ row }">
          <el-select
            v-model="row.status"
            size="mini"
            placeholder="选择状态"
            @visible-change="vis => vis && (row._lastStatus = row.status)"
            @change="val => onStatusChange(row, val)"
          >
            <el-option
              v-for="opt in statusOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="accessories" max-width="180">
        <template slot-scope="{ row }">
          <file-preview v-model="row.accessories" :simple="true"/>
        </template>
      </el-table-column>
      <el-table-column label="采购原因" align="center" prop="reason"/>


      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </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="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="97px">
        <el-form-item label="物品名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入采购物品名称"/>
        </el-form-item>
        <el-form-item label="采购数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入采购数量"/>
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" filterable placeholder="请选择">
            <el-option
              v-for="item in projectList"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="owner">
          <el-input v-model="form.owner" placeholder="请输入负责人"/>
        </el-form-item>
        <el-form-item label="采购原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="附件" prop="accessories">
          <file-upload v-model="form.accessories"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOaWarehouseRequest,
  getOaWarehouseRequest,
  delOaWarehouseRequest,
  addOaWarehouseRequest,
  updateOaWarehouseRequest
} from "@/api/oa/oaWarehouseRequest";
import {listByIds} from "../../../api/system/oss";
import {listProject} from "../../../api/oa/project";
import FilePreview from "@/components/FilePreview/index.vue";

export default {
  name: "OaWarehouseRequest",
  dicts: ['warehouse_request'],
  components: {FilePreview},
  data() {
    return {
      // 0未采购 1采购中 2完成 3取消
      statusOptions: [
        {value: 0, label: '未采购'},
        {value: 1, label: '采购中'},
        {value: 2, label: '完成'},
        {value: 3, label: '取消'},
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购需求表格数据
      oaWarehouseRequestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: undefined,
        quantity: undefined,
        projectId: undefined,
        accessories: undefined,
        owner: undefined,
        reason: undefined,
      },
      // 表单参数
      form: {},
      projectList: [],
      // 表单校验
      rules: {
        requestId: [
          {required: true, message: "主键ID不能为空", trigger: "blur"}
        ],
        itemName: [
          {required: true, message: "采购物品名称不能为空", trigger: "blur"}
        ],
        quantity: [
          {required: true, message: "采购数量不能为空", trigger: "blur"}
        ],

        owner: [
          {required: true, message: "负责人不能为空", trigger: "blur"}
        ],


      }
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    /** 输入时同时按 label / value 本地过滤 */
    filterCode (query) {
      query = (query || '').toLowerCase();
      this.dict.type.sys_project_code = this.dictBackup.filter(item => {
        return item.label.toLowerCase().indexOf(query) > -1 || item.value.toLowerCase().indexOf(query) > -1;
      });
    },
    /** 获取项目列表 */
    getProjectList() {
      listProject({pageSize: 9999, pageNum: 1}).then(res => {
        this.projectList = res.rows;
      })
    },
    statusLabel(val) {
      const m = {0: '未采购', 1: '采购中', 2: '完成', 3: '取消'}
      return m[val] ?? String(val)
    },

    async onStatusChange(row, newVal) {
      row._updating = true

      // 如果后端需要字符串，可改为 String(newVal)
      row.status = Number(newVal)

      // 调用你的更新接口（行内已含 request_id 等主键字段）
      updateOaWarehouseRequest(row).then(res=>{
        row._updating = false
        this.$message.success(`状态已更新为「${this.statusLabel(row.status)}」`)

      })


    },
    /** 查询采购需求列表 */
    getList() {
      this.loading = true;
      listOaWarehouseRequest(this.queryParams).then(response => {
        this.oaWarehouseRequestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        requestId: undefined,
        itemName: undefined,
        quantity: undefined,
        projectId: undefined,
        accessories: undefined,
        owner: undefined,
        reason: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requestId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购需求";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const requestId = row.requestId || this.ids
      getOaWarehouseRequest(requestId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改采购需求";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.requestId != null) {
            updateOaWarehouseRequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addOaWarehouseRequest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const requestIds = row.requestId || this.ids;
      this.$modal.confirm('是否确认删除采购需求编号为"' + requestIds + '"的数据项？').then(() => {
        this.loading = true;
        return delOaWarehouseRequest(requestIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/oaWarehouseRequest/export', {
        ...this.queryParams
      }, `oaWarehouseRequest_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
