<template>
  <div>
    <el-dialog :close-on-click-modal="false" :title="outDialogTiltle" :visible.sync="outDialogVisible"
      :append-to-body="true" width="70%" @close="handleCloseDetail" fullscreen>
      <!-- 基本信息 -->
      <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">批量选择</el-radio>
                <el-radio :label="2">单项选择</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">新增</el-button>
        <el-table :data="sizeForm.inTableData" border style="width: 100%">
          <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='inDialogType != "details" && sizeForm.options == 2' 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 prop="departmentName" label="部门" v-if="sizeForm.options === 2">
            <template slot-scope="scope">
              <el-select v-model="scope.row.department" placeholder="请选择部门名称" style="width: 100%;"
                v-if='inDialogType != "details"'>
                <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">
          </el-table-column>
          <el-table-column prop="outboundQuantity" label="已出库数量" v-if="sizeForm.options == 1">
            <template slot-scope="scope">
              {{ scope.row.outboundQuantity || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="theOutboundQuantity" label="本次出库数量">
            <template slot-scope="scope">
              <el-input-number size="mini" v-model="scope.row.theOutboundQuantity" :min="1" style="width: 100%;"
                @change="syncInboundQuantity(scope.row)" :disabled="outDialogType == 'details'"></el-input-number>
              <!-- <span v-else>{{ scope.row.theOutboundQuantity || 0 }}</span> -->
            </template>
          </el-table-column>
          <!-- <el-table-column prop="status" label="出库情况">
            <template slot-scope="scope">
              <el-button type="text" @click="putIn(scope.row)" v-if="scope.row.status == 1">出库</el-button>
              <span v-if="scope.row.status == 0">已出库</span>
            </template>
          </el-table-column> -->
        </el-table>
        <div class="form-title" v-if="outDialogType !== 'details'">出库账目表格：</div>
        <el-table :data="sizeForm.inTableData" 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="departmentName" label="部门" v-if="sizeForm.options == 2">
              <template slot-scope="scope">
                <span>
                  {{ getDepartmentName(scope.row.department) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="theOutboundQuantity" label="本次出库数量">
            </el-table-column>
          </el-table-column>
          <el-table-column prop="date" label="出库信息" v-if="sizeForm.options == 1">
            <el-table-column prop="outboundQuantity" label="数量">
              <template slot-scope="scope">
      {{ scope.row.outboundQuantity || 0 }}
    </template>
            </el-table-column>
          </el-table-column>
          <!-- <el-table-column prop="date" label="出库后库存" v-if="sizeForm.options == 1">
            <el-table-column prop="str10" label="数量">
            </el-table-column>
          </el-table-column> -->
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <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%;">
                  <el-option v-for="item in quarterList" :key="item.ids" :label="item.quarterName" :value="item.ids">
                  </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%;">
                <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-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>
    <!-- 选择弹窗 -->
    <el-dialog :close-on-click-modal="false" title="选择耐用品" :visible.sync="goodsVisible" :append-to-body="true"
      width="70%">
      <el-table :data="goodsList" border style="width: 100%" @selection-change="goodsListSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <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="unit" label="单位">
        </el-table-column>
        <el-table-column prop="departmentName" label="部门">
        </el-table-column>
        <el-table-column prop="applicationQuantity" label="申请数量">
        </el-table-column>
        <el-table-column prop="outboundQuantity" label="已出库数量">
          <template slot-scope="scope">
            {{ scope.row.outboundQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="theOutboundQuantity" label="本次出库数量">
          <template slot-scope="scope">
            <el-input-number size="mini" v-model="scope.row.theOutboundQuantity" :min="1" style="width: 100%;"
              @change="syncInboundQuantity(scope.row)" :disabled="outDialogType == 'details'"></el-input-number>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsVisible = false">取 消</el-button>
        <el-button type="primary" @click="goodsSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getQuarterList, getDepartmentList, getDetailedList, getDetailedItems, submitData, getMaterialList, editList } from "@/api/firstOrder/outbound";
export default {
  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 {
      goodsVisible: false,
      quarterList: [],
      departmentList: [],
      outDialogVisible: false,
      sizeForm: {
        orderNo: '',//出库单号
        reason: '',//事由
        // inAccountsTableData: [],//总计
        inTableData: [],
        ldOneOutStorageDetailVOList: [],
        demandEndInfo: '',//需求单名称
        outDate: '',//出库日期
        options: 2,//出库类型
        materialType: '1',//物资类型
        status: '',//1暂存 2提交
        // materialld: '',//物资Id
        userInfoVO: {
          userId: "用户ID",
          name: "用户名称"
        },
      },
      uniqueListDialogVisible: false, // 新增：控制弹窗显示
      uniqueList: [],
      goodsList: [],
      goodsSelectList: [],
      inTableData: [],
      inBatchDialogVisible: false,//选择采购单的数据
      batchType: '',//需求单选择类型
      inBatchForm: {
        batchType: '',
        department: ''
      },
      quarterYearMap: {},
      quarterQuarterMap: {}
    }
  },
  computed: {
    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.getMaterialList()
  },
  methods: {
    //本次出库数量
    syncInboundQuantity(row) {
      row.theOutboundQuantity = Number(row.theOutboundQuantity);
    },
    //关闭新增弹窗
    handleCloseDetail() {
      this.outDialogVisible = false
      this.$emit('handleCloseDetail')
    },
    // 获取需求单列表
    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) {
        console.error('获取需求单列表失败:', 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
          } else {
            this.departmentList = []
          }
        } catch (error) {
          this.$message.error('获取部门列表失败')
          this.departmentList = []
        }
      } else {
        this.departmentList = []
      }
    },
    // 采购单选择弹框关闭
    handleBatchClose() {
      this.inBatchDialogVisible = false
    },

    async batchSubmit() {
      if (!this.inBatchForm.batchType) {
        this.$message.error('请选择需求单');
        return;
      }
      if (!this.inBatchForm.department) {
        this.$message.error('请选择部门');
        return;
      }
      const res = await getDetailedList({
        ids: this.inBatchForm.batchType,
        departmentId: this.inBatchForm.department
      })

      if (res.data && res.data.result) {
        this.sizeForm.inTableData = res.data.result.duplicateList
        const selectedDept = this.departmentList.find(
          dept => dept.departmentId === this.inBatchForm.department
        );
        const deptName = selectedDept ? selectedDept.department : '';
        this.sizeForm.inTableData = res.data.result.duplicateList.map(item => ({
          ...item,
          IdDemandEndld: this.inBatchForm.batchType,
          // department: this.inBatchForm.department,
          department: deptName
        }));
        this.inBatchDialogVisible = false;
        const selectedQuarter = this.quarterList.find(
          item => item.ids === this.inBatchForm.batchType
        )
        if (selectedQuarter) {
          this.sizeForm.demandEndInfo = selectedQuarter.quarterName;
        }
        if (res.data.result.uniqueList != null && res.data.result.uniqueList.length > 0) {
          this.goodsVisible = true
          this.goodsList = res.data.result.uniqueList
        }
      } else {
        this.$message.warning('未获取到详细数据');
      }

    },
    //选择回调函数
    goodsListSelectionChange(val) {
      this.goodsSelectList = val
    },
    //批量选择弹窗点击确认按钮
    goodsSubmit() {
      if (this.goodsSelectList.length > 0) {
        this.sizeForm.inTableData.push(...this.goodsSelectList);
        this.$forceUpdate();
      } else {
        this.$message.warning('请先勾选需要添加的数据');
      }
      this.goodsVisible = false
    },
    //获取单条选择的部门名称列表
    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
      try {
        const res = await getMaterialList();
        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
    },
    // 提交
    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
      this.sizeForm.inTableData.forEach(row => {
        row.departmentName = this.getDepartmentName(row.department);
      });
      this.sizeForm.ldOneOutStorageDetailVOList.departmentName = this.sizeForm.inTableData.department

      this.sizeForm.inTableData = []
      try {
        const res = await submitData(this.sizeForm)
        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') {
        try {
          const res = await editList(this.id);
          const { ldOneOutStorage, ldOneOutStorageDetails = [] } = res.data.result || {};

          if (!ldOneOutStorage) {
            this.$message.error("回显数据异常");
            return;
          }
          const handledDetailList = ldOneOutStorageDetails.map(item => ({
            ...item,
            outboundQuantity: item.outboundQuantity || 0
          }))
          this.sizeForm = {
            ...this.sizeForm,
            ...ldOneOutStorage,
            outDate: ldOneOutStorage.outDate ? new Date(ldOneOutStorage.outDate) : '',
            options: Number(ldOneOutStorage.options) || 1,
          }
          this.sizeForm.inTableData = handledDetailList;

        } catch (error) {
          console.error("回显失败：", error);
          this.$message.error("获取详情数据失败");
        }
      }
    },
    addInit() {
      this.sizeForm.outDate = new Date()//出库时间
    },
    // 添加出库数据
    inTableAdd() {
      this.sizeForm.inTableData.push({})
    },
    // 选项选择
    async radioChange() {
      this.sizeForm.inTableData = []
      if (this.sizeForm.options === 1) {
        await this.getQuarterList()
        this.inBatchDialogVisible = true
        this.$forceUpdate()

      }
    },
  },
  watch: {
    // 监听需求单选择变化
    'inBatchForm.batchType': function (newVal) {
      if (newVal) {
        this.onQuarterSelectChange(newVal)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.form-title {
  margin: 20px 0;
}
</style>
