<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="outDialogTiltle"
      :visible.sync="outDialogVisible"
      :append-to-body="true"
      width="70%"
      @close="handleCloseDetail"
      fullscreen
    >
      <!-- 基本信息 -->
      <div class="dialog-content">
        <el-form
          :model="sizeForm"
          ref="dynamicValidateForm"
          label-width="100px"
          class="demo-dynamic"
        >
          <div class="form-title">基本信息</div>
          <el-row>
            <el-col
              :span="12"
              v-show="sizeForm.options == 1 && outDialogType != 'add'"
            >
              <el-form-item label="出库单号">
                <el-input v-model="sizeForm.orderNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库申请日期">
                <el-date-picker
                  v-model="sizeForm.outDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  disabled
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="事由">
                <el-input
                  v-model="sizeForm.reason"
                  :disabled="outDialogType == 'details'"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物资类型">
                <el-select
                  v-model="sizeForm.materialType"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="outDialogType == 'details'"
                >
                  <el-option label="办公室物资" value="1"></el-option>
                  <el-option label="其他物资" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选项">
                <el-radio-group
                  v-model="sizeForm.options"
                  @change="radioChange()"
                  :disabled="outDialogType == 'details'"
                >
                  <el-radio :label="1" :disabled="sizeForm.type == 2"
                    ><span>批量选择</span></el-radio
                  >
                  <el-radio :label="2">单项选择</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="sizeForm.options === 2">
              <el-form-item label="选项">
                <el-radio-group
                  v-model="sizeForm.optionType"
                  :disabled="outDialogType == 'details'"
                  @change="getMaterialList"
                >
                  <el-radio label="YH">易耗品</el-radio>
                  <el-radio label="NY">耐用品</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="sizeForm.options == 1">
              <el-form-item label="需求单名称">
                <el-input v-model="sizeForm.demandEndInfo" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-title">{{ outDate }} 出库信息：</div>
          <el-button
            type="primary"
            size="mini"
            style="margin-bottom: 18px"
            @click="inTableAdd()"
            v-if="sizeForm.options == 2 && outDialogType != 'details'"
            >新增</el-button
          >
          <el-table
            :data="sizeForm.inTableData"
            border
            style="width: 100%"
            :span-method="objectSpanMethod"
          >
            <el-table-column prop="materialCode" label="物资编码">
            </el-table-column>
            <el-table-column prop="materialName" label="物资名称">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.materialitem"
                  placeholder="请选择物资名称"
                  style="width: 100%"
                  @change="
                    handleMaterialChange(scope.row.materialitem, scope.$index)
                  "
                  v-if="
                    outDialogType != 'details' &&
                    sizeForm.options == 2 &&
                    sizeForm.optionType == 'YH'
                  "
                  value-key="id"
                >
                  <el-option
                    v-for="item in materials"
                    :key="item.materialId"
                    :label="item.materialName"
                    :value="item"
                  >
                  </el-option>
                </el-select>
                <span v-else> {{ scope.row.materialName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="model" label="规格"> </el-table-column>
            <el-table-column prop="type" label="类别">
              <template slot-scope="scope">
                {{
                  scope.row.type === "NY"
                    ? "耐用品"
                    : scope.row.type === "YH"
                    ? "易耗品"
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column prop="unit" label="单位"> </el-table-column>
            <el-table-column
              label="部门"
              prop="departmentName"
              v-if="sizeForm.options === 2 || sizeForm.optionType"
              :key="'account-dept-' + sizeForm.options"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.department"
                  placeholder="请选择部门名称"
                  style="width: 100%"
                  v-if="outDialogType != 'details'"
                  @change="changeDepartment"
                >
                  <el-option
                    v-for="item in list"
                    :key="item.departmentId"
                    :label="item.department"
                    :value="item.departmentId"
                  >
                  </el-option>
                </el-select>
                <span v-else> {{ scope.row.departmentName || "无" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="applicationQuantity"
              label="申请数量"
              v-if="sizeForm.options == 1"
            >
              <template slot-scope="scope">
                {{ scope.row.applicationQuantity || 0 }}
              </template>
            </el-table-column>

            <el-table-column
              prop="outboundQuantity"
              label="已出库数量"
              v-if="sizeForm.options == 1"
            >
              <template slot-scope="scope">
                <!-- <span v-if="outDialogType != 'details'">{{ scope.row.outboundQuantity || 0 }}</span>
                <span v-else>{{ scope.row.outboundSumQuantity || 0 }}</span> -->
                <span>{{ scope.row.outboundQuantity || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="theOutboundQuantity" label="本次出库数量">
              <template slot-scope="scope">
                <div v-if="outDialogType != 'details'">
                  <el-input-number
                    size="mini"
                    v-model="scope.row.theOutboundQuantity"
                    :min="0"
                    style="width: 100%"
                    @change="syncInboundQuantity(scope.row)"
                    :disabled="outDialogType == 'details'"
                    v-if="
                      sizeForm.optionType === 'YH' ||
                      (sizeForm.options == 1 && inBatchForm.optionType === 'YH')
                    "
                  ></el-input-number>
                  <span v-else>{{ scope.row.outboundQuantity }}</span>
                </div>
                <span v-else>{{ scope.row.outboundQuantity }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              style="text-align: center"
              width="100"
              v-if="outDialogType != 'details'"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="form-title" v-if="outDialogType !== 'details'">
            出库账目表格：
          </div>
          <el-table
            :data="statisticsList"
            border
            style="width: 100%"
            v-if="outDialogType !== 'details'"
          >
            <el-table-column prop="date" label="当前库存" width="100">
              <el-table-column prop="materialCode" label="物资编码">
              </el-table-column>
              <el-table-column prop="materialName" label="物资名称">
              </el-table-column>
              <el-table-column prop="model" label="规格"> </el-table-column>
              <el-table-column prop="type" label="类别">
                <template slot-scope="scope">
                  {{
                    scope.row.type === "NY"
                      ? "耐用品"
                      : scope.row.type === "YH"
                      ? "易耗品"
                      : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="type" label="出库类型">
                <template slot-scope="scope">
                  {{
                    scope.row.type === "NY"
                      ? "出库单"
                      : scope.row.type === "YH"
                      ? "发放单"
                      : ""
                  }}
                </template>
              </el-table-column>

              <el-table-column prop="num" label="数量"> </el-table-column>
            </el-table-column>

            <el-table-column prop="date" label="出库信息">
              <el-table-column prop="theOutboundQuantity" label="数量">
                <template slot-scope="scope">
                  {{ scope.row.theOutboundQuantity || 0 }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="date" label="出库后库存">
              <el-table-column prop="totalQuantity" label="数量">
                <template slot-scope="scope">
                  {{ scope.row.totalQuantity || 0 }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="date" label="出库信息">
              <el-table-column label="出库人">
                <template slot-scope="scope">
                  {{
                    scope.row.userInfoVO
                      ? scope.row.userInfoVO.name
                      : sizeForm.userInfoVO.name
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="outDate" label="出库时间" width="150">
                <template slot-scope="scope">
                  {{ outDate }}
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
        v-if="outDialogType != 'details'"
      >
        <el-button @click="handleCloseDetail()">取 消</el-button>
        <el-button type="primary" @click="submit(1)">暂存</el-button>
        <el-button type="primary" @click="submit(2)">提交</el-button>
      </span>
    </el-dialog>
    <!-- 批量出库  选择数据源弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      title="选择数据来源"
      :visible.sync="inBatchDialogVisible"
      :append-to-body="true"
      width="40%"
      @close="handleBatchClose"
      @open="getQuarterList"
    >
      <el-form
        :model="inBatchForm"
        ref="dynamicValidateForm"
        label-width="100px"
        class="demo-dynamic"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="需求单">
              <template slot-scope="scope">
                <el-select
                  v-model="inBatchForm.batchType"
                  placeholder="请选择需求单"
                  style="width: 100%"
                  @change="onQuarterSelectChange"
                >
                  <el-option
                    v-for="item in quarterList"
                    :key="item.ids"
                    :label="item.quarterName"
                    :value="item.ids"
                    :clearable="true"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="部门">
              <el-select
                v-model="inBatchForm.department"
                placeholder="请选择"
                style="width: 100%"
                :clearable="true"
                @change="depchange"
              >
                <el-option
                  v-for="item in departmentList"
                  :key="item.departmentId"
                  :label="item.department"
                  :value="item.departmentId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选项">
              <el-radio-group
                v-model="inBatchForm.optionType"
                :disabled="outDialogType == 'details'"
              >
                <el-radio label="YH">易耗品</el-radio>
                <el-radio label="NY">耐用品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleBatchClose()">取 消</el-button>
        <el-button type="primary" @click="batchSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 单条新增耐用品弹窗 -->
    <consumableDialog
      v-if="consumableVisible"
      :consumableVisible="consumableVisible"
      :demandDialogTitle="demandDialogTitle"
      @handleCloseDetail="closeDialog"
      @confirm="confirm"
    >
    </consumableDialog>
    <!-- 批量耐用品弹窗 -->
    <batchSelectionDialog
      v-if="batchSelectionVisible"
      :batchSelectionVisible="batchSelectionVisible"
      :batchSelectionTitle="batchSelectionTitle"
      :tableData="batchTableData"
      @batchclose="batchclose"
      :inBatchForm="inBatchForm"
      @confirm-selection="handleConfirmSelection"
      @selectionChange="selectionChange"
    >
    </batchSelectionDialog>
  </div>
</template>
<script>
import {
  getQuarterList,
  getDepartmentList,
  getDetailedList,
  getDetailedItems,
  submitData,
  getMaterialList,
  editList,
  batchList,
} from "@/api/firstOrder/outbound";
import consumableDialog from "./consumableDialog.vue";
import batchSelectionDialog from "./batchSelectionDialog.vue";
import { getStatistics } from "@/api/firstOrder/inbound";
import { mapGetters } from "vuex";

export default {
  components: {
    consumableDialog,
    batchSelectionDialog,
  },
  props: {
    repairVisible: {
      type: Boolean,
      default: false,
    },
    outDialogTiltle: {
      type: String,
      default: "",
    },
    outDialogType: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "",
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      statisticsList: [], //统计明细数据
      dialogVisible: false,
      demandDialogTitle: "耐用品出库",
      batchSelectionTitle: "耐用品出库",
      batchSelectionVisible: false,
      batchSelection: true, // 保持组件渲染
      batchTableData: [],
      consumableVisible: false, //单条耐耗品弹窗显示
      batchSelection: false,
      quarterList: [],
      departmentList: [],
      outDialogVisible: false,
      sizeForm: {
        orderNo: "", //出库单号
        reason: "", //事由
        // inAccountsTableData: [],//总计
        inTableData: [],
        ldOneOutStorageDetailVOList: [],
        demandEndInfo: "", //需求单名称
        outDate: "", //出库时间
        options: 2, //出库类型
        optionType: "", // 1易耗品 2耐用品
        materialType: "1", //物资类型
        status: "", //1暂存 2提交
        // materialld: '',//物资Id
        userInfoVO: {},
      },
      // inTableData: [],
      inBatchDialogVisible: false, //选择采购单的数据
      batchType: "", //需求单选择类型
      inBatchForm: {
        //批量选择
        batchType: "", //需求单类型
        department: "", //部门
        optionType: "", //YH/NY
      },
      quarterYearMap: {},
      quarterQuarterMap: {},
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    outDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
  mounted() {
    this.outDialogVisible = this.repairVisible;
    if (this.outDialogType == "add") {
      this.addInit();
    } else {
      this.inInit();
    }
    this.getDetailedItems();
    this.sizeForm.userInfoVO = this.userInfo;
    // this.getMaterialList()
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.sizeForm.options == 1 && this.inBatchForm.optionType == "NY") {
        if (
          columnIndex === 0 ||
          columnIndex === 1 ||
          columnIndex === 5 ||
          columnIndex === 6
        ) {
          const key = `${row.materialCode}-${row.materialName}`;
          const rows = this.sizeForm.inTableData.filter(
            (item) => `${item.materialCode}-${item.materialName}` === key
          );
          if (
            rows.length > 1 &&
            rowIndex === this.sizeForm.inTableData.indexOf(rows[0])
          ) {
            return {
              rowspan: rows.length,
              colspan: 1,
            };
          }

          if (
            rows.length > 1 &&
            rowIndex !== this.sizeForm.inTableData.indexOf(rows[0])
          ) {
            return {
              rowspan: 0,
              colspan: 0,
            };
          }
        }
      }
    },
    getStatistics() {
      getStatistics(this.sizeForm.inTableData).then((res) => {
        this.statisticsList = res.data.result;
        this.statisticsList = this.statisticsList.map((stat) => {
          const detail = this.sizeForm.inTableData.find(
            (item) => item.materialCode === stat.materialCode
          );
          console.log("detail", detail, stat);
          //
          if (
            (this.sizeForm.options == 1 &&
              this.inBatchForm.optionType == "NY") ||
            (this.sizeForm.options == 2 && this.sizeForm.optionType == "NY")
          ) {
            const detailList = this.sizeForm.inTableData.filter(
              (item) =>
                item.materialCode === stat.materialCode &&
                item.materialName === stat.materialName
            );
            detail.theOutboundQuantity = detailList.reduce(
              (acc, cur) => acc + cur.num,
              0
            );
          }

          return {
            ...stat,
            theOutboundQuantity: detail.theOutboundQuantity, //本次出库数量
            unitPrice: detail.unitPrice,
            totalQuantity: stat.num - detail.theOutboundQuantity,
            department: detail.department, // 部门ID
            departmentName:
              detail.departmentName ||
              this.getDepartmentName(detail.department),
          };
        });
      });
    },
    changeDepartment() {
      this.getStatistics();
    },
    batchclose() {
      this.batchSelectionVisible = false;
    },
    selectionChange(row) {
      this.batchSelectionVisible = false;
      this.sizeForm.inTableData = row;
      this.getStatistics();
    },
    confirm(allSelectedList) {
      this.consumableVisible = false;
      this.sizeForm.inTableData = allSelectedList;
      this.getStatistics();
    }, // 处理搜索
    async handleSearch() {
      // 重置当前页
      this.currentPage = 1;
      await this.loadGoodsList();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.loadGoodsList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadGoodsList();
    },
    depchange(value) {
      this.departmentList = this.departmentList;
    },
    //关闭
    handleBatchClose() {
      this.inBatchDialogVisible = false;
    },
    // 添加出库数据
    inTableAdd() {
      const requiredFields = [
        { value: this.sizeForm.reason, message: "请填写事由" },
        { value: this.sizeForm.materialType, message: "请选择物资类型" },
        {
          value: this.sizeForm.optionType,
          message: "请选择类别（易耗品/耐用品）",
        },
      ];
      // 检查所有必填项
      for (const field of requiredFields) {
        if (!field.value) {
          this.$message.warning(field.message);
          return;
        }
      }
      this.sizeForm.inTableData.push({});
    },
    addInit() {
      this.sizeForm.outDate = new Date(); //出库时间
    },
    //本次出库数量
    syncInboundQuantity(row) {
      row.theOutboundQuantity = Number(row.theOutboundQuantity);
      if (this.sizeForm.options === 1) {
        const maxAllowQuantity =
          (row.applicationQuantity || 0) - (row.outboundQuantity || 0);
        if (row.theOutboundQuantity > maxAllowQuantity) {
          this.$message.error(`本次出库数量不能大于${maxAllowQuantity}`);
          row.theOutboundQuantity = maxAllowQuantity;
          return false;
        }
      }
      if (this.sizeForm.optionType === "NY") {
        row.theOutboundQuantity = 1;
      }
      this.getStatistics();
    },
    //关闭新增弹窗
    handleCloseDetail() {
      this.outDialogVisible = false;

      this.$emit("handleCloseDetail");
    },
    closeDialog() {
      this.consumableVisible = false;
    },
    // 获取批量需求单列表
    async getQuarterList() {
      try {
        const res = await getQuarterList();
        if (res.data && res.data.result) {
          this.quarterList = res.data.result;
          this.quarterList.forEach((item) => {
            if (item.year && item.quarter && item.ids) {
              this.quarterYearMap[item.ids] = item.year;
              this.quarterQuarterMap[item.ids] = item.quarter;
              this.sizeForm.inTableData.ldDemandEndId = item.ids;
            }
          });
        }
      } catch (error) {
        this.$message.error("获取需求单列表失败");
      }
    },
    // 批量需求单选择变化，获取部门列表
    async onQuarterSelectChange(ids) {
      if (!ids) return;
      const year = this.quarterYearMap[ids];
      const quarter = this.quarterQuarterMap[ids];
      if (year && quarter) {
        try {
          const res = await getDepartmentList({
            year: year,
            quarter: quarter,
          });
          if (res.data && res.data.result) {
            this.departmentList = res.data.result;
            console.log(this.departmentList, "departmentList");
          } else {
            this.departmentList = [];
          }
        } catch (error) {
          this.$message.error("获取部门列表失败");
          this.departmentList = [];
        }
      } else {
        this.departmentList = [];
      }
    },

    async batchSubmit() {
      if (!this.inBatchForm.batchType) {
        this.$message.error("请选择需求单");
        return;
      }
      if (!this.inBatchForm.department) {
        this.$message.error("请选择部门");
        return;
      }
      if (!this.inBatchForm.optionType) {
        this.$message.error("请选择类别");
        return;
      }

      const requestParams = {
        ids: this.inBatchForm.batchType,
        departmentId: this.inBatchForm.department,
        optionType: this.inBatchForm.optionType,
      };

      try {
        let res;
        if (this.inBatchForm.optionType === "YH") {
          res = await getDetailedList(requestParams);
        } else if (this.inBatchForm.optionType === "NY") {
          res = await batchList(requestParams);
        }

        if (res.data && res.data.result) {
          this.sizeForm.inTableData = res.data.result;
          const selectedDept = this.departmentList.find(
            (dept) => dept.departmentId === this.inBatchForm.department
          );
          const deptName = selectedDept ? selectedDept.department : "";

          this.sizeForm.inTableData = res.data.result.map((item) => ({
            ...item,
            IdDemandEndld: this.inBatchForm.batchType,
            department: deptName,
          }));

          // 关闭批量选择弹窗
          this.inBatchDialogVisible = false;

          // 设置需求单名称
          const selectedQuarter = this.quarterList.find(
            (item) => item.ids === this.inBatchForm.batchType
          );
          if (selectedQuarter) {
            this.sizeForm.demandEndInfo = selectedQuarter.quarterName;
          }

          // 耐用品特殊处理（打开批量选择弹窗）
          if (this.inBatchForm.optionType === "NY") {
            this.batchSelectionVisible = true;
            this.dialogVisible = true;
            this.batchTableData = res.data.result;
          } else {
            this.getStatistics();
          }

          // 强制更新视图
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        } else {
          this.$message.warning("未获取到详细数据");
        }
      } catch (error) {
        this.$message.error(
          `获取${
            this.inBatchForm.optionType === "YH" ? "易耗品" : "耐用品"
          }数据失败：${error.message}`
        );
        console.error("批量提交接口调用失败：", error);
      }
    },
    //获取单条选择的部门名称列表
    async getDetailedItems() {
      this.loading = true;
      try {
        const res = await getDetailedItems();
        this.list = res.data.result;
      } catch (error) {
        this.$message.error("获取数据来源失败，请重试");
      } finally {
        this.loading = false;
      }
    },
    getDepartmentName(departmentId) {
      const department = this.list.find(
        (item) => item.departmentId === departmentId
      );
      return department ? department.department : "";
    },
    //获取单条选择的物资名称列表
    async getMaterialList() {
      this.loading = true;
      this.consumableVisible = false;
      try {
        if (
          this.sizeForm.optionType === "NY" &&
          this.outDialogType !== "details"
        ) {
          this.consumableVisible = true;
        } else {
          const res = await getMaterialList({
            optionType: this.sizeForm.optionType,
          });
          this.materials = res.data.result;
        }
      } catch (error) {
        this.$message.error("获取数据来源失败，请重试");
      } finally {
        this.loading = false;
      }
    },
    // 处理物资选择变化
    handleMaterialChange(row, index) {
      this.sizeForm.inTableData[index].materialId = row.materialId;
      this.sizeForm.inTableData[index].model = row.model;
      this.sizeForm.inTableData[index].materialCode = row.materialCode;
      this.sizeForm.inTableData[index].materialName = row.materialName;
      this.sizeForm.inTableData[index].type = row.type;
      this.sizeForm.inTableData[index].unit = row.unit;
      this.getStatistics();
    },
    // 提交
    async submit(index) {
      if (!this.sizeForm.reason) {
        this.$message.error("事由不能为空");
        return;
      }
      if (!this.sizeForm.materialType) {
        this.$message.error("请选择物资类型");
        return;
      }
      if (this.sizeForm.options === 1) {
        if (!this.sizeForm.demandEndInfo) {
          this.$message.error("请选择需求单名称");
          return;
        }
        if (
          !this.sizeForm.inTableData ||
          this.sizeForm.inTableData.length === 0
        ) {
          this.$message.error("请添加批量选择数据");
          return;
        }
        if (this.sizeForm.options === 2) {
          for (const row of this.sizeForm.inTableData) {
            if (!row.departmentName) {
              this.$message.error("请选择部门");
              return;
            }
          }
        }
      }
      // status == 1 暂存 ，2提交
      this.sizeForm.status = index;
      this.sizeForm.ldOneOutStorageDetailVOList = this.sizeForm.inTableData;
      let arr = this.departmentList.find(
        (item) => item.departmentId === this.inBatchForm.department || {}
      );
      this.sizeForm.ldOneOutStorageDetailVOList = this.sizeForm.inTableData.map(
        (row) => {
          console.log(row, "row");
          const deptId = row.department;
          const dept = this.list.find((item) => item.departmentId === deptId);
          const oneFormId = row.id;
          return {
            ...row,
            department:
              this.sizeForm.options == "1" ? arr.departmentId : deptId,
            departmentName:
              this.sizeForm.options == "1" ? arr.department : dept.department,
            oneFormId: oneFormId,
          };
        }
      );
      if(this.sizeForm.status ==  1){
        this.sizeForm.id = this.id
      }
      console.log(this.sizeForm, "111");
      // this.sizeForm.inTableData = [];
      if (this.sizeForm.options === 1) {
        this.sizeForm.optionType = this.inBatchForm.optionType;
      }
      try {
        const res = await submitData(this.sizeForm);
        console.log(this.sizeForm, "222");
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "提交成功",
          });
          this.$emit("submitSuccess");
          this.handleCloseDetail();
        } else {
          this.$message.error(res.data.message || "提交失败");
        }
      } catch (error) {
        this.$message.error(error.message || "服务器错误");
      }
    },

    //编辑和详情
    async inInit() {
      if (this.outDialogType == "details" || this.outDialogType == "edit") {
        editList(this.id).then((res) => {
          console.log(res.data.result, "详情数据");
          const { ldOneOutStorage, ldOneOutStorageDetails } =
            res.data.result || {};
          // this.sizeForm = res.data.result.ldOneOutStorage
          this.sizeForm.inTableData = res.data.result.ldOneOutStorageDetails;
          this.sizeForm.orderNo = ldOneOutStorage.orderNo;
          this.sizeForm.reason = ldOneOutStorage.reason;
          this.sizeForm.demandEndInfo = ldOneOutStorage.demandEndInfo;
          this.sizeForm.outDate = ldOneOutStorage.outDate;
          this.sizeForm.options = Number(ldOneOutStorage.options);
          this.sizeForm.optionType = ldOneOutStorage.optionType;
          this.batchSelectionVisible = false;
          console.log(
            res.data.result.ldOneOutStorageDetails,
            "this.sizeForm.options"
          );
          ldOneOutStorageDetails.foreach(item=>{
            item.materialId = item.materialId+'';
          })
          this.$set(
            this.sizeForm,
            "inTableData",
            ldOneOutStorageDetails
          );
          this.getStatistics();
        });
      }
    },

    // 选项选择
    radioChange() {
      this.sizeForm.inTableData = [];
      this.statisticsList = [];
      this.sizeForm.optionType = "";
      this.inBatchDialogVisible = false;
      this.consumableVisible = false;
      this.inBatchDialogVisible = false;
      this.batchSelectionVisible = false;
      this.sizeForm.optionType = "";
      this.batchTableData = [];
      if (this.sizeForm.options === 1) {
        this.getQuarterList();
        this.inBatchDialogVisible = true;
        (this.inBatchForm.batchType = ""), (this.inBatchForm.department = "");
        this.inBatchForm.optionType = "";
      }
    },
    // 删除表格行数据
    handleDelete(index, row) {
      this.sizeForm.inTableData.splice(index, 1);
      this.$message.success("已成功删除该条记录");
    },
  },
  watch: {
    // 监听需求单选择变化
    // "inBatchForm.batchType": function (newVal) {
    //   (this.inBatchForm.department = ""), (this.inBatchForm.optionType = 1);
    //   if (newVal) {
    //     this.onQuarterSelectChange(newVal);
    //   }
    // },
    // "sizeForm.optionType": function (newVal) {
    //   if (newVal && this.outDialogType === "add") {
    //     this.sizeForm.inTableData = [];
    //     this.getMaterialList();
    //   } else if (newVal && this.outDialogType !== "add") {
    //     this.getMaterialList();
    //   }
    // },
  },
};
</script>
<style lang="scss" scoped>
.form-title {
  margin: 20px 0;
}

::v-deep.el-dialog__footer {
  position: fixed !important;
  bottom: 0 !important;
  right: 0 !important;
}

::v-deep.dialog-content {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  padding-right: 10px;
}
::v-deep.el-table th.el-table__cell {
  background: #f5f7fa;
  font-weight: 500;
}
</style>
