<template>

  <div class="app-container">

    <el-card>

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">

        <el-form-item label="代宰日期" prop="slaughterAgencyDate">

          <el-date-picker

            v-model="queryParams.slaughterAgencyDate"

            type="date"

            value-format="yyyy-MM-dd"

            placeholder="请选择代宰日期"

            clearable

            style="width: 200px;"

          />

        </el-form-item>

        <el-form-item label="供应商编号" prop="supplierNumber">

          <el-input v-model="queryParams.supplierNumber" placeholder="请输入供应商编号" clearable style="width: 200px;" />

        </el-form-item>

        <el-form-item label="代宰户编号" prop="slaughterAgencyNumber">

          <el-input v-model="queryParams.slaughterAgencyNumber" placeholder="请输入代宰户编号" clearable style="width: 200px;" />

        </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-download" size="mini" @click="handleExport">导出</el-button>

          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>

        </el-form-item>

      </el-form>

    </el-card>

    <br />

    <el-card>

      <el-table border stripe v-loading="loading" :data="list" style="width: 100%;">

        <el-table-column label="单据编号" align="center" prop="documentNumber" min-width="140" />

        <el-table-column label="代宰日期" align="center" prop="slaughterAgencyDate" min-width="120" />

        <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="140" />

        <el-table-column label="客户名称" align="center" prop="customerName" min-width="140" />

        <el-table-column label="计划代宰数" align="center" prop="plannedSlaughterQuantity" min-width="110" />

        <el-table-column label="已代宰数量" align="center" prop="actualSlaughterQuantity" min-width="110" />

        <el-table-column label="单价" align="center" prop="unitPrice" min-width="100" />

        <el-table-column label="计划代宰金额" align="center" prop="plannedSlaughterAmount" min-width="120" />

        <el-table-column label="已代宰金额" align="center" prop="actualSlaughterAmount" min-width="120" />

        <el-table-column label="添加时间" align="center" prop="additionTime" min-width="160" />

        <el-table-column label="修改时间" align="center" prop="modificationTime" min-width="160" />

      </el-table>

      <pagination

        v-show="total > 0"

        :total="total"

        :page.sync="queryParams.pageNum"

        :limit.sync="queryParams.pageSize"

        @pagination="getList"

      />

    </el-card>



    <!-- 新增弹框 -->

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row :gutter="16">

          <el-col :span="12">

            <el-form-item label="单据编号" prop="documentNumber">

              <el-input v-model="form.documentNumber" placeholder="请输入单据编号" clearable />

            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="代宰日期" prop="slaughterAgencyDate">

              <el-date-picker

                v-model="form.slaughterAgencyDate"

                type="date"

                value-format="yyyy-MM-dd"

                placeholder="请选择代宰日期"

                clearable

                style="width: 100%;"

              />

            </el-form-item>

          </el-col>

        </el-row>

        <el-row :gutter="16">

          <el-col :span="12">

            <el-form-item label="供应商" prop="supplierNumber">

              <el-select

                v-model="form.supplierNumber"

                placeholder="请选择供应商"

                clearable

                filterable

                style="width: 100%;"

                @change="onSupplierChange"

              >

                <el-option

                  v-for="item in supplierList"

                  :key="item.supplierNo"

                  :label="item.supplierName"

                  :value="item.supplierNo"

                />

              </el-select>

            </el-form-item>

          </el-col>

          <el-col :span="12" style="display: none;">

            <el-form-item label="供应商名称" prop="supplierName">

              <el-input v-model="form.supplierName" disabled />

            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="代宰户" prop="slaughterAgencyNumber">

              <el-select

                v-model="form.slaughterAgencyNumber"

                placeholder="请选择代宰户"

                clearable

                filterable

                style="width: 100%;"

                @change="onActingCustomerChange"

              >

                <el-option

                  v-for="item in actingCustomerList"

                  :key="item.purchaserNo"

                  :label="item.purchaserName"

                  :value="item.purchaserNo"

                />

              </el-select>

            </el-form-item>

          </el-col>

          <el-col :span="12" style="display: none;">

            <el-form-item label="客户名称" prop="customerName">

              <el-input v-model="form.customerName" disabled />

            </el-form-item>

          </el-col>

        </el-row>

        <el-row :gutter="16">

          <el-col :span="12">

            <el-form-item label="数量" prop="plannedSlaughterQuantity">

              <decimal-input v-model="form.plannedSlaughterQuantity" :precision="0" :min="1" placeholder="数量" @change="calcAmount" />

            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="单价" prop="unitPrice">

              <decimal-input v-model="form.unitPrice" :precision="2" :min="0" placeholder="单价" @change="calcAmount" />

            </el-form-item>

          </el-col>

        </el-row>

        <el-row :gutter="16">

          <el-col :span="12">

            <el-form-item label="金额" prop="plannedSlaughterAmount">

              <el-input v-model="form.plannedSlaughterAmount" disabled placeholder="数量×单价" />

            </el-form-item>

          </el-col>

        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">

        <el-button size="small" @click="cancel">取 消</el-button>

        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>

      </div>

    </el-dialog>

  </div>

</template>



<script>


import { formatDateYMS } from "@/utils";

import { getActingAdminPage, addActingAdmin, editActingAdmin, delActingAdmin } from "@/api/production/actingAdmin";
import { getAllSupplier } from "@/api/app/supplier";
import { getAllPurchaser } from "@/api/app/purchaser";

export default {

  name: "ActingAdmin",

  data() {

    return {

      loading: false,

      total: 0,

      list: [],

      open: false,

      title: "新增",

      form: {},

      rules: {

        documentNumber: [{ required: true, message: "请输入单据编号", trigger: "blur" }],

        slaughterAgencyDate: [{ required: true, message: "请选择代宰日期", trigger: "change" }],

        supplierNumber: [{ required: true, message: "请选择供应商", trigger: "change" }],

        slaughterAgencyNumber: [{ required: true, message: "请选择代宰户", trigger: "change" }],

        plannedSlaughterQuantity: [{ required: true, message: "请输入数量", trigger: "blur" }],

        unitPrice: [{ required: true, message: "请输入单价", trigger: "blur" }],

      },

      supplierList: [],

      actingCustomerList: [],

      queryParams: {

        pageNum: 1,

        pageSize: 10,

        slaughterAgencyDate: null,

        supplierNumber: null,

        slaughterAgencyNumber: null,

      },

    };

  },

  created() {

    /** 查询条件代宰日期默认明天 */

    this.queryParams.slaughterAgencyDate = formatDateYMS(new Date().getTime() + 24 * 60 * 60 * 1000);

    this.getList();

    this.getSupplierList();

    this.getActingCustomerList();

  },

  methods: {

    /** 获取代宰管理列表（分页） */

    getList() {

      this.loading = true;

      getActingAdminPage(this.queryParams).then((res) => {
        this.list = res.data.records || [];
        this.total = res.data.total || 0;
        this.loading = false;
      });

    },

    /** 获取供应商列表，用于新增弹框供应商编号下拉 */

    getSupplierList() {

      getAllSupplier({}).then((res) => {

        this.supplierList = res.data || [];

      });

    },

    /** 获取代宰户列表，预留：对接接口后在此调用并赋值 this.actingCustomerList，数据结构需含 actingCustomerNo、actingCustomerName */

    getActingCustomerList() {

      // TODO: 替换为实际接口，例如：

      // getActingCustomerList({}).then((res) => {

      //   this.actingCustomerList = res.data || [];

      // });

      getAllPurchaser({}).then((res) => {
        this.actingCustomerList = res.data || [];
      });

    },

    /** 供应商编号变更时，同步填充隐藏字段供应商名称 */

    onSupplierChange(val) {

      const item = (this.supplierList || []).find((s) => s.supplierNo === val);

      this.form.supplierName = item ? item.supplierName : "";

      this.form.supplierId = item ? item.id : null;

    },

    /** 代宰户编号变更时，同步填充客户名称（与列表 customerName 字段一致） */

    onActingCustomerChange(val) {

      const item = (this.actingCustomerList || []).find((c) => c.purchaserNo === val);

      this.form.customerName = item ? item.purchaserName : "";
      this.form.slaughterAgencyId = item ? item.id : null;

    },

    /** 根据计划代宰数、单价计算计划代宰金额（数量×单价） */

    calcAmount() {

      const qty = this.form.plannedSlaughterQuantity != null && this.form.plannedSlaughterQuantity !== "" ? Number(this.form.plannedSlaughterQuantity) : NaN;

      const price = this.form.unitPrice != null && this.form.unitPrice !== "" ? Number(this.form.unitPrice) : NaN;

      if (!isNaN(qty) && !isNaN(price)) {

        this.form.plannedSlaughterAmount = (qty * price).toFixed(2);

      } else {

        this.form.plannedSlaughterAmount = "";

      }

    },

    /** 重置新增/编辑表单字段及校验状态 */

    reset() {

      this.form = {

        documentNumber: null,

        slaughterAgencyDate: null,

        supplierNumber: null,
        supplierName: null,
        supplierId: null,
        slaughterAgencyNumber: null,
        customerName: null,
        slaughterAgencyId: null,
        plannedSlaughterQuantity: null,
        unitPrice: null,

        plannedSlaughterAmount: null,


      };

      this.resetForm("form");

    },

    /** 关闭弹框并重置表单 */

    cancel() {

      this.open = false;

      this.reset();

    },

    /** 打开新增弹框，代宰日期默认明天 */

    handleAdd() {

      this.reset();

      this.form.slaughterAgencyDate = formatDateYMS(new Date().getTime() + 24 * 60 * 60 * 1000);

      this.title = "新增";

      this.open = true;

    },

    /** 提交新增/编辑表单，校验通过后调用接口并刷新列表 */

    submitForm() {

      this.$refs.form.validate((valid) => {

        if (!valid) return;

        // TODO: 调用新增接口
        addActingAdmin(this.form).then((res) => {
          this.$message.success("操作成功");
          this.open = false;
          this.getList();
        });

      });

    },

    /** 查询：页码置 1 并重新拉取列表 */

    handleQuery() {

      this.queryParams.pageNum = 1;

      this.getList();

    },

    /** 导出发货数据，按当前查询条件 */

    handleExport() {

      console.log("导出", this.queryParams);

    },

  },

};

</script>

