<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="stockIoCode" style="min-width:200px;max-width:220px;">
        <el-input
          v-model="queryParams.stockIoCode"
          placeholder="请输入出入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="ioType">
        <el-select v-model="queryParams.ioType" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.stock_io_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="bizType">
        <el-select v-model="queryParams.bizType" placeholder="请选择业务类型" clearable>
          <el-option
            v-for="dict in dict.type.stock_biz_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择单据状态" clearable>
          <el-option :key="0" label="草稿" :value="0" />
          <el-option :key="1" label="待审核" :value="1" />
          <el-option :key="2" label="已完成" :value="2" />
        </el-select>
      </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"
          v-hasPermi="['klp:stockIo: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="['klp:stockIo: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="['klp:stockIo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['klp:stockIo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockIoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出入库单ID" align="center" prop="stockIoId" v-if="true"/>
      <el-table-column label="出入库单号" align="center" prop="stockIoCode" />
      <el-table-column label="类型" align="center" prop="ioType">
        <template slot-scope="scope">
          <el-tag :type="getIoTypeTagType(scope.row.ioType)">
            {{ getIoTypeLabel(scope.row.ioType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="bizType">
        <template slot-scope="scope">
          <el-tag :type="getBizTypeTagType(scope.row.bizType)">
            {{ getBizTypeLabel(scope.row.bizType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 2 ? 'success' : (scope.row.status === 1 ? 'warning' : 'info')">
            {{ scope.row.status === 2 ? '已完成' : (scope.row.status === 0 ? '草稿' : '待审核') }}
          </el-tag>
        </template>
      </el-table-column>
      <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)"
            v-hasPermi="['klp:stockIo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['klp:stockIo:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="showDetail(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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出入库单号" prop="stockIoCode">
          <el-input v-model="form.stockIoCode" placeholder="请输入出入库单号" />
        </el-form-item>
        <el-form-item label="类型" prop="ioType">
          <el-select v-model="form.ioType" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.stock_io_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-select v-model="form.bizType" placeholder="请选择业务类型">
            <el-option
              v-for="dict in dict.type.stock_biz_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态" prop="status">
          <el-input v-model="form.status" :value="0" readonly disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </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>
    <!-- 明细弹窗 -->
    <el-dialog
      title="出入库单详情"
      :visible.sync="detailDialogVisible"
      width="1000px"
      append-to-body
      @close="onDetailClosed"
    >
      <StockIoDetailPanel 
        :stockIo="detailStockIo" 
        @status-changed="onStatusChanged"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listStockIo, getStockIo, delStockIo, addStockIo, updateStockIo } from "@/api/wms/stockIo";
import StockIoDetailPanel from './panels/detail.vue';

export default {
  name: "StockIo",
  dicts: ['stock_biz_type', 'stock_io_type', 'stock_status'],
  components: { StockIoDetailPanel },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库单主表格数据
      stockIoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stockIoCode: undefined,
        ioType: undefined,
        bizType: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stockIoId: [
          { required: true, message: "出入库单ID不能为空", trigger: "blur" }
        ],
        stockIoCode: [
          { required: true, message: "出入库单号不能为空", trigger: "blur" }
        ],
        ioType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        bizType: [
          { required: true, message: "业务类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "单据状态不能为空", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      },
      detailDialogVisible: false,
      detailStockIo: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询出入库单主列表 */
    getList() {
      this.loading = true;
      listStockIo(this.queryParams).then(response => {
        this.stockIoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stockIoId: undefined,
        stockIoCode: undefined,
        ioType: undefined,
        bizType: undefined,
        status: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: 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.stockIoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.status = 0; // 新增时默认草稿状态
      this.open = true;
      this.title = "添加出入库单主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const stockIoId = row.stockIoId || this.ids
      getStockIo(stockIoId).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.stockIoId != null) {
            updateStockIo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addStockIo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const stockIoIds = row.stockIoId || this.ids;
      this.$modal.confirm('是否确认删除出入库单主编号为"' + stockIoIds + '"的数据项？').then(() => {
        this.loading = true;
        return delStockIo(stockIoIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('klp/stockIo/export', {
        ...this.queryParams
      }, `stockIo_${new Date().getTime()}.xlsx`)
    },
    showDetail(row) {
      this.detailStockIo = { ...row };
      this.detailDialogVisible = true;
    },
    onDetailClosed() {
      this.getList();
    },
    onStatusChanged(updatedStockIo) {
      // 更新主表中的对应记录状态
      const index = this.stockIoList.findIndex(item => item.stockIoId === updatedStockIo.stockIoId);
      if (index !== -1) {
        this.$set(this.stockIoList, index, updatedStockIo);
      }
      // 刷新列表
      this.getList();
    },
    getIoTypeTagType(type) {
      if (type === 'in') return 'success';
      if (type === 'out') return 'primary';
      if (type === 'transfer') return 'warning';
      return '';
    },
    getIoTypeLabel(type) {
      if (type === 'in') return '入库';
      if (type === 'out') return '出库';
      if (type === 'transfer') return '移库';
      return type;
    },
    getBizTypeTagType(type) {
      if (type === 'purchase') return 'success';
      if (type === 'sales') return 'primary';
      if (type === 'return') return 'warning';
      if (type === 'relocation') return 'info';
      return 'default';
    },
    getBizTypeLabel(type) {
      const map = {
        purchase: '采购',
        sales: '销售',
        return: '退货',
        relocation: '调拨',
        other: '其他'
      };
      return map[type] || type;
    }
  }
};
</script>
