<template>
  <el-card shadow="always" :body-style="{ padding: '10px' }">
    <div class="app-container">
      <el-row :gutter="10">
        <el-col :span="10">
          <div class="table-area">
            <el-button
              class="mb10"
              type="success"
              size="small"
              @click="handleRefresh"
              :icon="loading ? 'el-icon-loading' : 'el-icon-refresh'"
              :disabled="loading"
              >刷新
            </el-button>

            <el-table
              :data="leftTableData"
              border
              stripe
              @selection-change="handleSelectionChange"
              @cell-click="cellClick"
              highlight-current-row
            >
              <!-- <el-table-column type="selection" width="55" /> -->
              <el-table-column type="index" label="序号" width="50" />
              <el-table-column
                align="center"
                prop="customerName"
                label="客户名称"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="saleOrderNo"
                label="销售单号"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="noticeNumber"
                label="通知单号"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="noticeDate"
                label="开单日期"
              >
              </el-table-column>
            </el-table></div
        ></el-col>
        <el-col :span="14">
          <div class="form-area">
            <el-row :gutter="20">
              <el-form
                :model="form"
                ref="form"
                label-width="80px"
                :inline="true"
                size="mini"
                :rules="rules"
              >
                <el-col :span="16">
                  <el-form-item label="通知单号" prop="noticeNumber">
                    <div class="text-area">
                      <span class="mr10">{{ form.noticeNumber }}</span>
                      <span>{{ form.documentTypeName }}</span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="销售员" prop="salesman">
                    {{ form.salesman }}
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="客户名称" prop="customerName">
                    {{ form.customerName }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="售货单位" prop="sellingUnit">
                    {{ form.sellingUnit }}
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="货车信息" prop="truckRegistration">
                    {{ form.truckRegistration }}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="发货员" prop="deliveryClerk">
                    {{ form.deliveryClerk }}
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注" prop="dispatchNoteRemark">
                    {{ form.dispatchNoteRemark }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发货日期" prop="deliveryDate">
                    <el-date-picker
                      v-model="form.deliveryDate"
                      type="date"
                      size="mini"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发货仓库" prop="deliveryWarehouse">
                    <el-select
                      v-model="form.deliveryWarehouse"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in warehouseList"
                        :key="item.id"
                        :label="item.warehouseName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
              <el-form-item label="调拨仓库" prop="transferWarehouse">
                <el-select
                  v-model="form.transferWarehouse"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
                <el-col :span="24">
                  <el-form-item>
                    <el-button type="primary" @click="outStockHandler"
                      >出库
                    </el-button>
                    <el-button @click="refreshHandler">刷新</el-button>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-row>
            <el-table
              :data="saleProductInfoList"
              border
              stripe
              :span-method="objectSpanMethod"
              :row-class-name="tableRowClassName"
            >
              <el-table-column align="center" label="编码" prop="productCode">
              </el-table-column>
              <el-table-column align="center" label="品名" prop="productName">
              </el-table-column>
              <el-table-column align="center" label="批号" prop="lotNum" v-if="this.dlotNum">
              </el-table-column>
              <el-table-column
                align="center"
                label="规格"
                prop="productSpecifications"
              >
              </el-table-column>
              <el-table-column align="center" label="颜色" prop="productColor">
              </el-table-column>
              <!-- <el-table-column align="center" label="批号" prop="lotNum">
              </el-table-column>
              <el-table-column align="center" label="等级" prop="levels">
              </el-table-column> -->
              <el-table-column align="center" label="通知">
                <el-table-column
                  align="center"
                  label="重量"
                  prop="actualWeight"
                >
                </el-table-column>
              </el-table-column>
              <el-table-column align="center" label="实发">
                <!-- <el-table-column
                  align="center"
                  label="总箱数"
                  prop="coutBoxNum"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.coutBoxNum"
                      size="mini"
                      @input="iptChange"
                    ></el-input>
                  </template>
                </el-table-column> -->
                <el-table-column
                  align="center"
                  label="箱数"
                  prop="oldActualBoxNum"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.oldActualBoxNum"
                      size="mini"
                      @input="iptChange"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  align="center"
                  label="总重量"
                  prop="coutweight"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.coutweight"
                      size="mini"
                      @input="iptChange"
                    ></el-input>
                  </template>
                </el-table-column> -->
                <el-table-column
                  align="center"
                  label="重量"
                  prop="oldActualWeight"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.oldActualWeight"
                      size="mini"
                      @input="iptChange"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script>
import {
  productInvoiceList,
  saleStorageDetails,
  queryDropDownBoxData,
  noticeOutStorage,
  oldNoticeOutStorage,
} from "@/api/tablelist/commonTable";
import { mapState } from "vuex";

export default {
  name: "OutStock",
  props: [],
  dicts: ["billing_type", "document_type"],
  components: {},
  data() {
    return {
      spanArr: [], // 用于记录每个 productCode 的跨行信息
      loading: false,
      dlotNum: false,
      currentIndex: "",
      form: {
        noticeNumber: "", //通知单号
        documentType: "", //通知单类型
        documentTypeName: "",
        salesman: "", //销售员
        sellingUnit: "", //售货单位
        truckRegistration: "", //货车信息
        drawer: "", //开票员
        deliveryClerk: "", // 发货员
        dispatchNoteRemark: "", //备注
        customerName: "", //客户名称
        deliveryDate: new Date(), //发货日期
        deliveryWarehouse: "", //发货仓库
        transferWarehouse: "", //调拨仓库
        id: "",
      },
      leftTableData: [],
      warehouseList: [],
      saleProductInfoList: [],
      rules: {
        deliveryDate: [
          { required: true, message: "请选择发货日期", trigger: "change" },
        ],
        deliveryWarehouse: [
          { required: true, message: "请选择发货仓库", trigger: "change" },
        ],
        transferWarehouse: [
          { required: true, message: "请选择调拨仓库", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    iptChange(value) {
      console.log(value);
      this.$forceUpdate(); //强制刷新
    },
    tableRowClassName({ row, rowIndex }) {
      if (!row.actualWeight && row.actualWeight != 0) {
        return "warning-row";
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 重量
      if (columnIndex === 6 || columnIndex === 7 || columnIndex === 9) {
        const prevRow2 = this.saleProductInfoList[rowIndex - 1]; //上一行数据
        let nextRow2 = this.saleProductInfoList[rowIndex + 1]; //下一行数据
        // 当上一行的数据等于当前行数据时，当前行单元格隐藏
        if (
          prevRow2 &&
          prevRow2.productCode == row.productCode &&
          prevRow2.productColor == row.productColor
        ) {
          return { rowspan: 0, colspan: 0 };
        } else {
          // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
          let countRowspan2 = 1; //用于合并计数多少单元格
          while (
            nextRow2 &&
            nextRow2.productCode == row.productCode &&
            nextRow2.productColor == row.productColor
          ) {
            nextRow2 = this.saleProductInfoList[++countRowspan2 + rowIndex];
          }
          if (countRowspan2 > 1) {
            // this.saleProductInfoList[rowIndex].coutBoxNum = 9;
            return { rowspan: countRowspan2, colspan: 1 };
          }
        }
      }
    },
    // 刷新回调
    async handleRefresh() {
      this.loading = true;
      await this.initData();
      await this.initWarehouse();
      this.loading = false;
    },
    // 左侧表格点击回调
    cellClick(row, column, cell, event) {
      this.currentIndex = this.leftTableData.findIndex(
        (item) => item.id == row.id
      );
      this.initFormData();
    },
    // 刷新回调
    refreshHandler() {
      this.initFormData();
    },
    // 出库回调
    outStockHandler() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.$confirm("是否确认出库?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              let payLoad = { ...this.form };
              payLoad.oldProductInvoiceList = this.saleProductInfoList;
              payLoad.transferWarehouse = payLoad.deliveryWarehouse;
              payLoad.saleOrderNo =
                this.leftTableData[this.currentIndex || 0].saleOrderNo;
              if (!this.form.id) {
                return;
              }
              delete payLoad.documentTypeName;
              let res = await oldNoticeOutStorage(payLoad);
              if (res.code == 200) {
                this.$message.success("出库成功");
                this.currentIndex = 0;
                await this.initData();
                this.refreshHandler();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消出库",
              });
            });
        } else {
          return false;
        }
      });
    },
    handleSelectionChange() {},
    // 初始化仓库选项数据
    async initWarehouse() {
      try {
        let payload = [
          {
            basicMap: {
              tableName: "warehouse",
            },
            conditionMap: {
              warehouse_type: ["1"],
            },
          },
        ];
        let res = await queryDropDownBoxData(payload);
        if (res.code == 200) {
          this.warehouseList = res.data.resultMap?.warehouse || [];
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {}
    },
    // 初始化数据
    async initData() {
      try {
        let payload = {
          isEnablePaging: false,
          status: 1,
        };
        let res = await productInvoiceList(payload);
        if (res.code == 200) {
          this.leftTableData = res.rows;
          if (this.leftTableData.length > 0) {
            this.currentIndex = 0;
            this.initFormData();
          }
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {}
    },
    // 根据字典获取文件类型
    getdocumentTypeName(value) {
      return (
        this.dict.type.document_type.find((item) => {
          return item.value === value;
        })?.label || ""
      );
    },
    // 加载表单数据
    async initFormData() {
      // let { id, customerName } = this.leftTableData[this.currentIndex];
      let id = false,
        customerName;
      if (this.leftTableData[this.currentIndex]) {
        id = this.leftTableData[this.currentIndex].id;
        customerName = this.leftTableData[this.currentIndex].customerName;
      }
      if (!id) {
        //重置表单数据
        Object.assign(this.form, {
          noticeNumber: "", //通知单号
          documentType: "", //通知单类型
          documentTypeName: "", //通知单类型  名
          salesman: "", //销售员
          sellingUnit: "", //售货单位
          truckRegistration: "", //货车信息
          dispatchNoteRemark: "", //备注
          customerName: "", //客户名称
          deliveryClerk: "", //发货员
          id: "",
        });
        return;
      }
      try {
        let res = await saleStorageDetails(id);
        if (res.code == 200) {
          let {
            noticeNumber, //通知单号
            documentType, //通知单类型
            salesman, //销售员
            sellingUnit, //售货单位
            truckRegistration, //货车信息
            drawer, //开票员
            dispatchNoteRemark, //备注
            saleProductInfoList, //产品信息
            id,
          } = res.data;
          let documentTypeName = this.getdocumentTypeName(documentType);
          // let list = saleProductInfoList.sort( (a,b)=>{
          //    let {productColor : colorA,productCode :codeA}=a
          //    let {productColor : colorB,productCode : codeB}=b
          //   return (colorA+codeA)-(colorB-codeB)
          // })

          this.saleProductInfoList = saleProductInfoList;
          // 使用 reduce 方法来累加相同 productCode 和 productColor 的第一条数据的 boxNum
          const codeColorSums = this.saleProductInfoList.reduce(
            (acc, curr, index) => {
              // 创建一个用于组合 productCode 和 productColor 的键
              const key = `${curr.productCode}-${curr.productColor}`;

              // 检查当前 key 是否已经存在
              if (!acc[key]) {
                // 如果不存在，添加 key 作为键，并将 boxNum 设置为当前值
                acc[key] = {
                  firstIndex: index,
                  sum: curr.boxNum,
                  weight: curr.weight,
                  count: 1,
                };
              } else {
                acc[key].count++; // 增加计数
                acc[key].sum += curr.boxNum;
                acc[key].weight += curr.weight;
              }
              return acc;
            },
            {}
          );
          this.saleProductInfoList.forEach((item, index) => {
            if (codeColorSums[`${item.productCode}-${item.productColor}`]) {
              item.coutBoxNum =
                codeColorSums[`${item.productCode}-${item.productColor}`].sum;
              item.coutweight =
                codeColorSums[
                  `${item.productCode}-${item.productColor}`
                ].weight.toFixed(2);
            }
          });
          if(this.saleProductInfoList.length > 0){
            if(this.saleProductInfoList[0].lotNum == null || this.saleProductInfoList[0].lotNum == '' || this.saleProductInfoList[0].lotNum == undefined){
              this.dlotNum = false;
            }else{
              this.dlotNum = true;
            }
          }else{
            this.dlotNum = false;
          }
          Object.assign(this.form, {
            noticeNumber, //通知单号
            documentType, //通知单类型
            documentTypeName, //通知单类型  名
            salesman, //销售员
            sellingUnit, //售货单位
            truckRegistration, //货车信息
            dispatchNoteRemark, //备注
            customerName, //客户名称
            id,
          });
          this.form.deliveryClerk = this.nickName;
        } else {
          console.log(res);
          this.$message.error("网络异常");
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
  computed: {
    ...mapState({
      nickName: (state) => state.user.nickName,
    }),
  },
  mounted() {
    this.initData();
    this.initWarehouse();
  },
};
</script>

<style scoped lang="scss">
.app-container {
  display: flex;
  width: 100%;

  .table-area {
    // width: 600px;
  }

  .form-area {
    // flex: 1;
  }
}

::v-deep .el-table__body tr.current-row > td.el-table__cell {
  background-color: #55e905 !important;
}

.table-data > .gutter {
  display: table-cell !important;
}

::v-deep .el-table .warning-row {
  color: red;
}
</style>
