<!-- 采购委外发货审批(委外发货出库) 出库标识 -->
<template>
  <div class="ele-body">
    <el-card shadow="never">
      <el-form
        :model="formData"
        ref="formName"
        label-width="110px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出库场景123" prop="bizType">
              <span>{{ outboundTypeMapping[formData.bizType] }}</span>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="退货处理单" prop="sourceBizNo">
              <span>{{ formData.sourceBizNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库物品类型" prop="extInfo.assetType">
              <span>{{ assetTypeMapping[formData.extInfo.assetType] }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="权属部门" prop="deptName">
              <el-input
                v-if="!isStorage"
                placeholder="权属部门"
                disabled
                v-model="formData.extInfo.deptName"
                clearable
              />
              <span v-else>{{ formData.extInfo.deptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库登记人">
              <el-input
                v-if="!isStorage"
                placeholder="登记人"
                disabled
                v-model="formData.extInfo.createUserName"
                clearable
              />
              <span v-else>{{ formData.extInfo.createUserName }}</span>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="领料人部门" prop="verifyDeptName">
              <selectTree
                v-if="!isStorage"
                ref="tree"
                class="form-ipt"
                size="medium"
                style="width: 100%"
                clearable
                :options="treeList"
                :props="{
                  value: 'code',
                  label: 'name',
                  children: 'children'
                }"
                @getValue="auditorDeptClick"
              />
              <span v-else>{{ formData.extInfo.verifyDeptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="领料人" prop="fromUser">
              <el-select
                v-if="!isStorage"
                v-model="formData.fromUser"
                filterable
                placeholder="请选择领料人"
              >
                <el-option
                  v-for="item in llrLsit"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="
                    () => (formData.extInfo.fromUserPhone = item.phone)
                  "
                >
                </el-option>
              </el-select>
              <span v-else>{{ formData.fromUser }}</span>
            </el-form-item></el-col
          >
          <el-col :span="8">
            <el-form-item label="领料人联系方式" prop="fromUserPhone">
              <el-input
                v-if="!isStorage"
                placeholder="请输入"
                disabled
                v-model="formData.extInfo.fromUserPhone"
                clearable
              />
              <span v-else>{{ formData.fromUserPhone }}</span>
            </el-form-item></el-col
          >
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-if="!isStorage"
                v-model="formData.remark"
                clearable
                type="textarea"
                placeholder="请详细说明"
                :rows="4"
              ></el-input>
              <span v-else>{{ formData.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="!isStorage">
        <el-button
          style="margin-bottom: 20px; float: right; margin-right: 20px"
          type="primary"
          @click="addStock"
          >添加</el-button
        >
      </div>
      <div class="material">
        <div style="width: 100%; text-align: right"></div>
        <div>
          <header-title title="物品清单"></header-title>
          <div class="mt10 form-table">
            <el-form
              ref="warehousingMaterialListRef"
              :model="{ warehousingMaterialList: warehousingMaterialList }"
              :show-message="false"
            >
              <el-table
                ref="multipleTable"
                :data="warehousingMaterialList"
                tooltip-effect="dark"
                style="width: 100%"
                stripe
                :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
              >
                <el-table-column label="序号" type="index" width="50">
                </el-table-column>
                <el-table-column
                  label="编码"
                  prop="assetCode"
                  width="150"
                ></el-table-column>

                <el-table-column
                  label="名称"
                  prop="assetName"
                  width="150"
                ></el-table-column>

                <el-table-column
                  v-for="(item, index) in tableHeader"
                  :key="index"
                  align="center"
                  :label="item.label"
                  width="150"
                  :prop="item.prop"
                >
                  <template slot-scope="{ row }">
                    <template v-if="item.formatter">{{
                      item.formatter(row)
                    }}</template>
                    <template v-else>{{ row[item.prop] }}</template>
                  </template>
                </el-table-column>
                <el-table-column
                  label="批号"
                  prop="manualBatchNo"
                  width="100"
                ></el-table-column>
                <el-table-column
                  label="批次号"
                  prop="batchNo"
                ></el-table-column>
                <el-table-column label="最小包装单元" width="120">
                  <template slot-scope="{ row }">
                    {{ row.minPackingCount }}{{ row.measuringUnit }}/{{
                      row.minUnit
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="包装数量" prop="availableCountBase">
                  <template slot-scope="{ row }">
                    {{ row.packingCountBase }}{{ row.minUnit }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="计量数量"
                  prop="availableCountBase"
                ></el-table-column>
                <el-table-column
                  label="计量单位"
                  prop="measuringUnit"
                ></el-table-column>
                <el-table-column label="重量" prop="weight"></el-table-column>
                <el-table-column
                  label="重量单位"
                  prop="weightUnit"
                ></el-table-column>
                <el-table-column
                  v-if="!isStorage"
                  label="仓库"
                  width="300"
                  prop="warehouseName"
                ></el-table-column>
                <el-table-column
                  v-else
                  label="仓库"
                  width="300"
                  prop="position"
                >
                </el-table-column>
                <!-- <el-table-column v-if="!isStorage" label="操作" width="200">
                  <template slot-scope="{ row, $index }">
                    <el-button type="text" @click="listDel(row, $index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column> -->
              </el-table>
            </el-form>
          </div>
          <header-title class="mt20" title="包装清单"></header-title>
          <div class="mt10 form-table">
            <BatchDetail
              :assetType="formData.extInfo.assetType"
              :data="batchDetailsVOList"
            />
          </div>
        </div>
        <div class="mt20">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane :label="`${title}明细`" name="a">
              <el-table
                ref="multipleTable"
                :data="materialCodeReqList"
                tooltip-effect="dark"
                style="width: 100%"
                stripe
                :header-cell-style="rowClass"
              >
                <el-table-column label="序号" type="index" width="50">
                </el-table-column>

                <el-table-column
                  :label="`编码`"
                  width="150"
                  prop="assetCode"
                ></el-table-column>
                <el-table-column label="名称" prop="name" width="150">
                </el-table-column>
                <el-table-column
                  label="批号"
                  prop="manualBatchNo"
                  width="100"
                ></el-table-column>
                <el-table-column label="批次号" prop="batchNo">
                </el-table-column>
                <el-table-column
                  label="发货条码"
                  prop="barcodes"
                  width="80"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  v-if="dimension == 4"
                  label="包装编码"
                  width="150"
                  prop="onlyCode"
                ></el-table-column>
                <el-table-column
                  v-for="(item, index) in tableHeader"
                  :key="index"
                  align="center"
                  :label="item.label"
                  width="150"
                  :prop="item.prop"
                >
                  <template slot-scope="{ row }">
                    <template v-if="item.formatter">{{
                      item.formatter(row)
                    }}</template>
                    <template v-else>{{ row[item.prop] }}</template>
                  </template>
                </el-table-column>
                <el-table-column
                  label="物料编码"
                  width="250"
                  prop="no"
                ></el-table-column>
                <el-table-column label="计量数量" prop="">
                  <template slot-scope="{ row }">1</template>
                </el-table-column>
                <el-table-column
                  label="计量单位"
                  prop="measuringUnit"
                ></el-table-column>
                <el-table-column
                  label="物料代号"
                  prop="meterielCode"
                  width="130"
                >
                </el-table-column>
                <el-table-column
                  label="客户代号"
                  prop="clientCode"
                ></el-table-column>
                <el-table-column label="刻码" prop="engrave"></el-table-column>
                <el-table-column label="重量" prop="weight"></el-table-column>
                <el-table-column
                  label="重量单位"
                  prop="weightUnit"
                ></el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>

    <AssetsDialog
      ref="assetsDialogRef"
      :title="title"
      :warehousingMaterialList="selectionList"
      :assetType="formData.extInfo.assetType"
      @detailData="detailData"
    />
  </div>
</template>

<script>
  import outin from '@/api/warehouseManagement/outin';
  import { getPurchaseOutSourceSendDetailAPI } from '@/api/bpm/components/purchasingManage/outSourceSend';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import { deepClone } from '@/components/FormGenerator/utils/index';
  import {
    getTreeByPid,
    getTreeByGroup,
    getOutInBySourceBizNoOrError
  } from '@/api/classifyManage';
  import pickOrder from '@/views/bpm/outgoingManagement/components/pickOrder.vue';
  import {
    warehousingType,
    outputSceneState,
    emergencyState,
    materialType
  } from '@/utils/dict/index';
  import selectTree from '@/components/selectTree';
  import AssetsDialog from '@/views/bpm/outgoingManagement/components/AssetsDialog.vue';
  import { tableHeader } from '@/views/bpm/handleTask/components/inoutBound/common';
  import BatchDetail from '@/views/bpm/outgoingManagement/components/batchDetail.vue';
  import { getLoginUser } from '@/api/login';
  export default {
    components: {
      BatchDetail,
      pickOrder,
      selectTree,
      AssetsDialog
    },
    props: {
      taskDefinitionKey: {
        type: String,
        default: ''
      },
      activeComp: {
        type: String,
        default: ''
      },
      businessId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        form: {}, // 用于传参
        outboundTypeMapping: {}, // 出库类型映射表
        outputSceneState, // 出库类型类型
        codeList: [], // 物品类型列表
        assetTypeMapping: {}, // 物品类型映射表
        isStorage: false, // 是否出库
        dimension: '3',
        materialType,
        warehousingType,
        emergencyState,
        title: '',
        warehousingMaterialList: [],
        activeName: 'a',
        treeList: [],
        formData: {
          extInfo: {
            assetType: '', //物品类型
            deptCode: '', //部门code
            deptName: '', //部门名称
            verifyDeptCode: '', //审核部门编码
            verifyDeptName: '', //审核部门名称
            deliveryName: '', //送货人名称
            fromUserPhone: '', //送货人电话
            sourceBizNo: '', //销售订单
            urgent: '', //紧急状态
            supplierId: '', //供应商ID
            supplierName: '', //供应商名称
            createUserName: '' //创建人名字
          },
          fromUser: '', //送货人
          bizType: '', //物品类型
          verifyId: '', //审核人Id
          verifyName: '', //审核人名称
          createUserId: '',
          remark: ''
        },

        rules: {
          bizType: {
            required: true,
            message: '请选择出库场景',
            trigger: 'change'
          },
          fromUser: {
            required: true,
            message: '请选择领料人',
            trigger: 'change'
          }
        },
        llrLsit: [],
        options: [],
        onSelectTableDataVal: [],
        batchDetailsVOList: [],
        materialCodeReqList: [],
        selectionList: [],
        materialObj: {},
        wlParams: {}
      };
    },
    computed: {
      tableHeader() {
        return tableHeader(this.formData.extInfo.assetType);
      }
    },
    async mounted() {
      await this.initData();
      let returnDetailsForm = await getPurchaseOutSourceSendDetailAPI(
        this.businessId
      );
      this.form = returnDetailsForm;
      console.log(returnDetailsForm);
      getOutInBySourceBizNoOrError(returnDetailsForm.code)
        .then((data) => {
          // 已经出库(详情)
          console.log('有订单来源');
          this.isStorage = true; // 已经出库
          this.formData = deepClone(data);
          // 填充遍历数据
          console.log('this.formData-----', this.formData);
          if (this.formData.outInDetailVOList?.length > 0) {
            this.warehousingMaterialList = []; // 物品列表
            this.batchDetailsVOList = []; // 包装列表
            this.materialCodeReqList = []; // 物料列表
            this.formData.outInDetailVOList.forEach((goodsiItem) => {
              goodsiItem.assetName = goodsiItem.name;
              goodsiItem.assetCode = goodsiItem.categoryCode;
              goodsiItem.outInNum = goodsiItem.packingCount;
              this.warehousingMaterialList.push(goodsiItem);
              goodsiItem.outInDetailRecordVOList.forEach((wrapItem) => {
                wrapItem.assetName = goodsiItem.name;
                wrapItem.assetCode = goodsiItem.categoryCode;
                // wrapItem.count =
                //   wrapItem.outInDetailRecordMaterialDetailVOList.length; // 增加包装计量数量
                this.batchDetailsVOList.push(wrapItem);
                wrapItem.outInDetailRecordMaterialDetailVOList.forEach(
                  (materialItem) => {
                    materialItem.isPack = true;
                    this.materialCodeReqList.push(materialItem);
                  }
                );
              });
            });
          }
        })
        .catch(() => {
          //未出库
          this.isStorage = false;
          // 物品类型
          this.formData.extInfo.assetType =
            returnDetailsForm.categoryLevelTopId;
          // 出库类型(委外出库)
          this.formData.bizType = '6';
          // 增加添加物品判断条件
          this.title = this.assetTypeMapping[this.formData.extInfo.assetType];
          // 添加单据来源
          this.formData.sourceBizNo = returnDetailsForm.code;
          // 将出库状态改成出库状态 2出库 1入库
          this.formData.type = 2;
          this.$forceUpdate();
        });
    },
    methods: {
      //获取回执附件
      getQualityFile() {
        return {};
      },
      detailData(data, dimension) {
        this.dimension = dimension;
        console.log('总数居', data);
        this.onSelectTableDataVal = data.realTimeInventoryVOList;
        this.warehousingMaterialList = data.realTimeInventoryVOList.map(
          (next) => {
            delete next.updateTime;
            delete next.createTime;
            return {
              ...next,
              realInventoryAmount: 0,
              assetType: this.formData.extInfo.assetType,
              outInNum: '',
              assetCode: next.code,
              assetName: next.name,
              bizStatus: 2,
              contactCode: next.contactCode
            };
          }
        );
        // this.batchDetailsVOList = data.batchDetailsVOList;

        if (dimension == 4) {
          this.materialCodeReqList = data.wlList;
          this.selectionList = data.wlList;

          //包装维度出库
          const list = data.realTimeInventoryVOList;
          //获取包装维度
          let packArr = [];
          for (const item of list) {
            if (item.inventoryDetailsVOList.length != 0) {
              for (const iterator of item.inventoryDetailsVOList) {
                packArr.push({ ...iterator, batchNo: iterator.batchNum });
              }
            }
          }
          this.batchDetailsVOList = packArr.map((item) => {
            return {
              ...item,
              packingCountBase:
                dimension == 4 || dimension == 3 ? 1 : item.packingCountBase
              // weight: 0
            };
          });

          let params = {
            realTimeInventoryNewPOList: data.realTimeInventoryVOList
          };

          for (const item of params.realTimeInventoryNewPOList) {
            item.inventoryDetailsNewPOList = item.inventoryDetailsVOList;

            for (const detail of item.inventoryDetailsNewPOList) {
              detail.outInMaterialDetailsAddPOList = [];

              for (const wlItem of data.wlList) {
                if (detail.id === wlItem.recordId) {
                  detail.outInMaterialDetailsAddPOList.push({
                    ...wlItem
                  });
                }
              }
            }
          }
          this.wlParams = params;

          this.materialObj = data;
        } else if (dimension == 3) {
          //包装维度出库
          const list = data.realTimeInventoryVOList;
          //获取包装维度
          let packArr = [];
          for (const item of list) {
            if (item.inventoryDetailsVOList.length != 0) {
              for (const iterator of item.inventoryDetailsVOList) {
                packArr.push({ ...iterator, batchNo: iterator.batchNum });
              }
            }
          }
          this.batchDetailsVOList = packArr.map((item) => {
            return {
              ...item,
              packingCountBase:
                dimension == 4 || dimension == 3 ? 1 : item.packingCountBase
              // weight: 0
            };
          });
          //物料维度数据
          let meteArr = [];
          for (const item of packArr) {
            if (item.materialDetailsVOList.length != 0) {
              for (const iterator of item.materialDetailsVOList) {
                meteArr.push({
                  ...iterator
                });
              }
            }
          }
          this.materialCodeReqList = meteArr;
          //再次打开选择上
          this.selectionList = list;
          //send数据
          this.wlParams = { realTimeInventoryNewPOList: list };
          this.wlParams.realTimeInventoryNewPOList.forEach((item) => {
            item.inventoryDetailsNewPOList = item.inventoryDetailsVOList;
            item.inventoryDetailsNewPOList.forEach((ite) => {
              ite.weight = 0;
              ite.outInMaterialDetailsAddPOList = ite.materialDetailsVOList;
            });
          });
        } else {
          //   else if (dimension == 2) {
          //   this.batchDetailsVOList = data.wlList;
          //   this.selectionList = data.wlList;
          // }
          //物品维度出库
          const list = data.realTimeInventoryVOList;
          //获取包装维度
          let packArr = [];
          for (const item of list) {
            if (item.inventoryDetailsVOList.length != 0) {
              for (const iterator of item.inventoryDetailsVOList) {
                packArr.push({ ...iterator, batchNo: iterator.batchNum });
              }
            }
          }
          this.batchDetailsVOList = packArr.map((item) => {
            return {
              ...item,
              packingCountBase: dimension == 3 ? 1 : item.packingCountBase
              // weight: 0
            };
          });
          //物料维度数据
          let meteArr = [];
          for (const item of packArr) {
            if (item.materialDetailsVOList.length != 0) {
              for (const iterator of item.materialDetailsVOList) {
                meteArr.push({
                  ...iterator
                });
              }
            }
          }
          this.materialCodeReqList = meteArr;
          //再次打开选择上
          this.selectionList = list;
          //send数据
          this.wlParams = { realTimeInventoryNewPOList: list };
          this.wlParams.realTimeInventoryNewPOList.forEach((item) => {
            item.inventoryDetailsNewPOList = item.inventoryDetailsVOList;
            item.inventoryDetailsNewPOList.forEach((ite) => {
              ite.weight = 0;
              ite.outInMaterialDetailsAddPOList = ite.materialDetailsVOList;
            });
          });
        }
      },
      getStatus() {
        return true;
      },
      getReturnStorage() {
        return new Promise((resolve) => {
          this.$refs.formName.validate((valid) => {
            if (valid) {
              if (!this.warehousingMaterialList?.length) {
                return this.$message.error('请添加出库明细！');
              }
              let obj = { ...this.formData, type: 2 };
              obj.extInfo.sourceBizNo = obj.sourceBizNo;
              obj.fromType = obj.type;
              obj = { ...obj, ...this.wlParams };
              if (this.dimension == 4) {
                obj.num = this.materialObj.wlList.length;
              } else {
                obj.num = this.materialCodeReqList.length;
              }
              let isPass = false;
              // 1按数量计费 2按重量计费
              if (this.form.pricingWay == 2) {
                if (this.materialCodeReqList.length > 0) {
                  // 判断物料
                  isPass = this.materialCodeReqList.every(
                    (item) => item.weight > 0
                  );
                } else {
                  // 判断包装重量是否全部大于0
                  isPass = this.batchDetailsVOList.every(
                    (item) => item.weight > 0
                  );
                }
              } else {
                isPass = true;
              }
              if (isPass) {
                resolve(obj);
              } else {
                this.$message.error('委外发货重量不能为空');
              }
            }
          });
        });
      },
      rowClass({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 1) {
          return {
            display: 'none',
            background: '#EEEEEE',
            border: 'none'
          };
        }
        return { background: '#EEEEEE', border: 'none' };
      },
      // 部门点击事件
      async auditorDeptClick(data) {
        console.log(data);
        this.formData.extInfo.verifyDeptCode = data?.id;
        this.formData.extInfo.verifyDeptName = data?.name;
        this.formData.verifyId = '';
        this.formData.verifyName = '';

        this.$refs.formName.validateField('verifyDeptName');
        if (data) {
          this.getStaffList(data);
        }
      },
      // 获取领料人列表
      async getStaffList(data) {
        let res = await warehouseDefinition.getUserPage({
          groupId: data.id,
          size: 9999,
          page: 1
        });
        this.llrLsit = res.list;
      },
      //出库明细删除
      listDel(row, index) {
        this.warehousingMaterialList.splice(index, 1);
        if (this.warehousingMaterialList.length == 0) {
          this.formData.sourceBizNo = '';
          this.formData.extInfo.clientName = '';
          this.formData.extInfo.clientUser = '';
          this.formData.extInfo.clientUserPhone = '';
        }
        // 从 this.batchDetailsVOList 中删除满足条件的对象
        this.removeItemsFromArray(
          this.batchDetailsVOList,
          (item) => item.code.substr(0, 12) === row.code
        );

        // 从 this.materialCodeReqList 中删除满足条件的对象
        this.removeItemsFromArray(
          this.materialCodeReqList,
          (item) => item.assetCode === row.code
        );
      },
      // 删除数组中满足条件的对象
      removeItemsFromArray(arr, condition) {
        for (let i = arr.length - 1; i >= 0; i--) {
          if (condition(arr[i])) {
            arr.splice(i, 1);
          }
        }
      },
      // 获取物品类型列表
      async getAssetTypeOptions() {
        const { data } = await getTreeByGroup({ type: 1 });
        this.codeList = data;
        let obj = {};
        data.forEach((item) => {
          obj[item.id] = item.name;
        });
        this.assetTypeMapping = obj;
      },
      // 出库类型映射表
      async getOutboundTypeMapping() {
        let obj = {};
        this.outputSceneState.forEach((item) => {
          obj[item.code] = item.label;
        });
        this.outboundTypeMapping = obj;
      },
      async initData() {
        await this.getAssetTypeOptions();
        await this.getOutboundTypeMapping();
        const res = await warehouseDefinition.tree();
        this.treeList = this.$util.toTreeData({
          data: res,
          idField: 'id',
          parentIdField: 'parentId'
        });
        const info = await getLoginUser();
        let obj = res.find(
          (item) => item.id === info.deptId[info.deptId.length - 1]
        );
        if (!obj) return;
        this.formData.extInfo.deptCode = obj.id;
        this.formData.extInfo.deptName = obj.name;
        this.formData.extInfo.createUserName = info.name;
        this.formData.createUserId = info.id;
      },
      addStock() {
        if (!this.title) return this.$message.error('请选择出库产品类型');
        if (!this.formData.bizType && this.formData.bizType !== 0) {
          return this.$message.error('请选择出库场景');
        }
        this.$refs.assetsDialogRef.open();
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep.form-table {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-input__inner {
      padding: 0 10px;
    }
  }

  .p20 {
    padding: 20px;
  }
  .el-select,
  .el-date-editor {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 22px;
  }
  .material {
    margin-top: 20px;
    .flex {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      align-items: center;
      .red {
        color: #ff4949;
      }
    }
  }
  .mt10 {
    margin-top: 10px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .center {
    text-align: center;
  }
</style>
