<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="stockOrder">
            <el-input
              v-model="queryParams.stockOrder"
              placeholder="请输入成品备货单"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="装运单" prop="deliveryOrder">
            <el-input
                 v-model="queryParams.deliveryOrder"
                   placeholder="请输入交货单号"
                  clearable
                  @keyup.enter.native="handleQuery"
               />
             </el-form-item>

                <el-form-item label="交货单" prop="itemNumber">
                  <el-input
                   v-model="queryParams.itemNumber"
                   placeholder="请输入交货单号"
                     clearable
                    @keyup.enter.native="handleQuery"
                    />
          </el-form-item>
                        <el-form-item label="产品名称" prop="productName">
                            <el-input
                                    v-model="queryParams.productName"
                                    placeholder="请输入产品名称"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="产品编码" prop="productCode">
                            <el-input
                                    v-model="queryParams.productCode"
                                    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"
                       v-hasPermi="['wms:outorder:add']">生成出库单</el-button>
          </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="selloutList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
                    <el-table-column label="ID" align="center" prop="id"  v-if="false" />
                     <el-table-column label="备货单" align="center" prop="stockOrder"  width="250"/>
                    <el-table-column label="装运单" align="center" prop="deliveryOrder"  width="250"/>
                     <el-table-column label="交货单" align="center" prop="attr1" v-if="false" />
                    <el-table-column label="交货单" align="center" prop="itemNumber" width="150"/>
                    <el-table-column label="工厂编码" align="center" prop="factoryCode"  v-if="false" />
                    <el-table-column label="出库仓" align="center" prop="whCode"  />
          <el-table-column label="库区" align="center" prop="waCode" width="250"/>
                    <el-table-column label="库区编码" align="center" prop="waCode"  v-if="false" />
                    <el-table-column label="库位编码" align="center" prop="wlCode"  v-if="false" />
                    <el-table-column label="出库地点" align="center" prop="deliveryPlace"  v-if="false" />
                    <el-table-column label="产品名称" align="center" prop="productName" width="250"/>

                     <el-table-column label="产品编码" align="center" prop="productCode" width="250">
                       <template slot-scope="scope">
                       <span>{{ formatProductCode(scope.row.productCode) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="产品分类" align="center" prop="productSort"  v-if="false" />
                    <el-table-column label="规格型号" align="center" prop="specification"  v-if="false" />
                    <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
                    <el-table-column label="批号" align="center" prop="lotNumber"/>
                    <el-table-column label="计划出库数量" align="center" prop="planQuantity"/>
                    <el-table-column label="出库数量" align="center" prop="outQuantity"/>
          <el-table-column label="出库状态" width="100" align="center" prop="status">
            <template slot-scope="scope">
              <span v-if="scope.row.status ===  '1' ">出库中</span>
              <span v-else-if="scope.row.status ==='0' ">未出库</span>
              <span v-else-if="scope.row.status === '2' ">出库完成</span>
            </template>
          </el-table-column>

          <el-table-column label="SAP过账状态" width="100" align="center" prop="sapstatus">
            <template slot-scope="scope">
              <span v-if="scope.row.sapstatus ===  '1' ">完成</span>
              <span v-else-if="scope.row.sapstatus  === '0'  ">未过账</span>
              <span v-else-if="scope.row.sapstatus === '2'  ">失败</span>
            </template>
          </el-table-column>
                    <el-table-column label="过账SAP凭证" align="center" prop="sapProof"/>
                    <el-table-column label="过账SAP返回信息" align="center" prop="sapMessage"/>
                    <el-table-column label="交货日期" align="center" prop="outDate" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.outDate, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="送达方" align="center" prop="attr4"/>
                    <el-table-column label="送达方描述" align="center" prop="attr3"/>
<!--                    <el-table-column label="货运代理" align="center" prop="attr4"/>-->
<!--                    <el-table-column label="货运代理描述" align="center" prop="attr5"/>-->
                    <el-table-column label="售达方" align="center" prop="attr6"/>
                    <el-table-column label="售达方描述" align="center" prop="attr5"/>
                   <el-table-column label="渠道类型" align="center" prop="attr7"/>
<!--                    <el-table-column label="计划日期" align="center" prop="attr8"/>-->
                    <el-table-column label="发货点名称" align="center" prop="attr9"v-if="false" />
                    <el-table-column label="发货点编码" align="center" prop="attr10"v-if="false" />
                    <el-table-column label="备注" align="center" prop="remark"/>
        </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="1200px" append-to-body>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handlequeryform">查询</el-button>
          </el-col>
        </el-row>
        <el-table :data="addoutorderList" @selection-change="handleSelectionChange1">
          <el-table-column type="selection" width="55" align="center" :index="indexMethod" />
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column label="id" align="center" prop="id" v-if="false" />
          <el-table-column label="装运单" prop="deliveryOrder" width="150"/>
          <el-table-column label="交货单"  prop="itemNumber" width="150"/>
          <el-table-column label="产品名称" prop="productName" width="150"/>
          <el-table-column label="产品编码" align="center" prop="productCode" width="150">
            <template slot-scope="scope">
              <span>{{ formatProductCode(scope.row.productCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unitOfMeasure" />
          <el-table-column label="批号" prop="lotNumber" />
          <el-table-column label="计划数量" align="center" prop="planQuantity" />
          <el-table-column label="交货日期" align="center" prop="outDate" width="150"/>
          <el-table-column label="送达方" align="center" prop="attr4" />
          <el-table-column label="送达方描述" align="center" prop="attr3" />
          <el-table-column label="售达方" align="center" prop="attr6" />
          <el-table-column label="售达方描述" align="center" prop="attr5" />
          <el-table-column label="渠道类型" align="center" prop="attr7" />
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="deleteOutOrder(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 装运单信息弹窗 -->
      <el-dialog :title="'库存物料'" :visible.sync="showMaterialDialog" width="1500px">
        <div>
          <!-- 查询条件 -->
          <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="装运单">
              <el-input v-model="queryParams.deliveryOrder" placeholder="请输入装运单"></el-input>
            </el-form-item>
            <el-form-item label="交货单">
              <el-input v-model="queryParams.itemNumber" placeholder="请输入装运单"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchMaterials">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="materialList" @selection-change="handleMaterialSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="id" align="center" prop="id" v-if="false" />
            <el-table-column label="装运单" prop="deliveryOrder" width="150"/>
            <el-table-column label="交货单"  prop="itemNumber" width="150"/>
            <el-table-column label="产品名称" prop="productName" width="150"/>
            <el-table-column label="产品编码" align="center" prop="productCode" width="150">
              <template slot-scope="scope">
                <span>{{ formatProductCode(scope.row.productCode) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unitOfMeasure" />
            <el-table-column label="批号" prop="lotNumber" />
            <el-table-column label="计划数量" align="center" prop="planQuantity" />
            <el-table-column label="交货日期" align="center" prop="outDate" width="150"/>
            <el-table-column label="送达方" align="center" prop="attr4" />
            <el-table-column label="送达方描述" align="center" prop="attr3" />
            <el-table-column label="售达方" align="center" prop="attr6" />
            <el-table-column label="售达方描述" align="center" prop="attr5" />
            <el-table-column label="渠道类型" align="center" prop="attr7" />

          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalMaterials"
            layout="total, prev, pager, next, jumper"
          />
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="confirmMaterialSelection">确 定</el-button>
            <el-button @click="showMaterialDialog = false">取 消</el-button>
          </div>
        </div>
      </el-dialog>

    </div>
</template>

<script>
    import {
        listSellout,
        getSellout,
      addRE,
      listSelloutlistRE,
        delSellout,
        addSellout,
        updateSellout } from "@/api/wms/sellout";

    export default {
        name: "Sellout",
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 成品销售出库表格数据
                    selloutList: [],
              materialList: [], // 领料单数据
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
              showMaterialDialog: false, // 领料单信息弹窗状态
              addoutorderList: [],
                // 查询参数
              currentPage: 1, // 当前页码
              pageSize: 10, // 每页显示的条目数
              totalMaterials: 0, // 领料单总数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    deliveryOrder: null,
                    itemNumber: null,
                    factoryCode: null,
                    whCode: null,
                    waCode: null,
                    wlCode: null,
                    deliveryPlace: null,
                    productName: null,
                    productCode: null,
                    productSort: null,
                    specification: null,
                    unitOfMeasure: null,
                    lotNumber: null,
                    planQuantity: null,
                    outQuantity: null,
                    status: null,
                    sapStatus: null,
                    sapProof: null,
                    sapMessage: null,
                    outDate: null,
                    attr1: null,
                    attr2: null,
                    attr3: null,
                    attr4: null,
                    attr5: null,
                    attr6: null,
                    attr7: null,
                    attr8: null,
                    attr9: null,
                    attr10: null,
        },
            // 表单参数
            form: {
            }
        ,
            // 表单校验
            rules: {
            }
        }
            ;
        },
        created() {
            this.getList();
        },
        methods: {
            /** 查询成品销售出库列表 */
            getList() {
                this.loading = true;
              listSelloutlistRE(this.queryParams).then(response => {
                    this.selloutList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
          indexMethod(index) {
            return index + 1;
          },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                        id: null,
                        deliveryOrder: null,
                        itemNumber: null,
                        factoryCode: null,
                        whCode: null,
                        waCode: null,
                        wlCode: null,
                        deliveryPlace: null,
                        productName: null,
                        productCode: null,
                        productSort: null,
                        specification: null,
                        unitOfMeasure: null,
                        lotNumber: null,
                        planQuantity: null,
                        outQuantity: null,
                        status: null,
                        sapStatus: null,
                        sapProof: null,
                        sapMessage: null,
                        outDate: null,
                        attr1: null,
                        attr2: null,
                        attr3: null,
                        attr4: null,
                        attr5: null,
                        attr6: null,
                        attr7: null,
                        attr8: null,
                        attr9: null,
                        attr10: null,
                        createBy: null,
                        createTime: null,
                        updateBy: null,
                        updateTime: null,
                        remark: null
            }
                ;
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
          handleMaterialSelectionChange(selection) {
            this.selectedMaterials = selection; // 记录选中的领料单
          },
          async submitForm() {
            const payload = this.addoutorderList.map(item => ({
              id: item.id,
            }));

            console.log("payload:", payload); // 使用逗号分隔符来打印对象

            try {
              await this.$confirm('确认生成备货单吗?', '确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
              });

              // 调用接口提交数据
              const response = await addRE(payload);
              this.$message.success('备货单生成成功');
              this.open = false; // 关闭对话框
              this.addoutorderList = []; // 清空列表或根据需求更新
            } catch (error) {
              if (error === 'cancel') {
                this.$message.info('已取消提交');
              } else {
                console.error('提交失败:', error);
                this.$message.error('提交失败，请重试');
              }
            }
            this.getList();
          },
            /** 重置按钮操作 */

            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
          handleSelectionChange1(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
            this.selectedRows = selection;
          },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length !== 1
                this.multiple = !selection.length
            },
          handlequeryform() {
            this.showMaterialDialog = true; // 显示领料单信息弹窗
            this.fetchMaterials(); // 加载领料单数据
            // this.queryParams1.pageNum = 1;
            // this.getList1();
          },
          handleCurrentChange(page) {
            this.currentPage = page; // 更新当前页码
            this.fetchMaterials(page); // 重新加载材料数据
          },

          /** 新增按钮操作 */
          handleAdd() {
            this.reset();
            this.open = true;
            this.title = "成本中心出库任务新增";
            this.queryParams1 = {}
            this.addoutorderList = []
          },
          async confirmMaterialSelection() {
            const materialsToAdd = []; // 临时存储待添加的材料信息
            for (const material of this.selectedMaterials) {
              try {
                materialsToAdd.push({
                  id: material.id,
                  deliveryOrder: material.deliveryOrder,
                  itemNumber: material.itemNumber,
                  productName: material.productName,
                  productCode: material.productCode,
                  unitOfMeasure: material.unitOfMeasure,
                  lotNumber: material.lotNumber,
                  planQuantity: material.planQuantity,
                  outDate: material.outDate,
                  attr4: material.attr4,
                  attr3: material.attr3,
                  attr6: material.attr6,
                  attr5: material.attr5,
                  attr7: material.attr7
                });
              } catch (error) {
                console.error('Error fetching batches:', error);
              }
            }
            // 将待添加的材料一次性添加到 addoutorderList 中
            this.addoutorderList = this.addoutorderList.concat(materialsToAdd);
            console.log("Materials processed");
            this.showMaterialDialog = false; // 关闭领料单弹窗
          },
          deleteOutOrder(row) {
            // 确认删除操作
            this.$confirm('确认删除该装运单吗?', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 从 addoutorderList 中删除选定的行
              this.addoutorderList = this.addoutorderList.filter(item => item !== row);
              this.$message.success('删除成功!');
            }).catch(() => {
              this.$message.info('已取消删除');
            });
          },
          formatProductCode(code) {
            // 检查是否有效，去掉前7个零
            if (!code) return code; // 处理 null 或 undefined 情况
            return code.replace(/^0{1,7}/, ''); // 替换前1到7个0
          },
          /** 重置按钮操作 */
          async fetchMaterials(pageNum = 1) { // 这里的参数名称为 pageNum
            this.loading = true; // 显示加载状态
            try {
              const response = await listSellout({
                ...this.queryParams, // 假设 queryParams 包含其他查询条件
                pageNum: pageNum,    // 将当前页码传递给后端
                pageSize: this.pageSize // 确保将每页显示的数量传递给后端
              });

              // 更新物料列表，并计算索引
              this.materialList = response.rows.map((item, index) => {
                item.index = (pageNum - 1) * this.pageSize + index + 1; // 更新索引
                return item;
              });

              this.totalMaterials = response.total; // 更新总条目数
            } catch (error) {
              console.error('获取装运单失败:', error);
              this.$message.error('加载装运单失败，请稍后重试。');
            } finally {
              this.loading = false; // 隐藏加载状态
            }
          }
          ,
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id =
                row.id || this.ids
                getSellout(id).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改成品销售出库";
                });
            },


    }
    }
    ;
</script>
