<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="新增入库单"
      @clickLeft="back"
    >
      <!-- @clickRight="handleScan"
      right-icon="scan"
    > -->
      <!--右菜单-->
      <template slot="float">
        <!-- <view class="nav-icon-caozuo rightNav" @click="getsure">
					<u-button type="success" size="small" class="u-reset-button" text="确定"></u-button>
				</view> -->
      </template>
    </uni-nav-bar>

    <u-form
      labelPosition="left"
      :model="formData"
      :rules="rules"
      ref="formRef"
      labelWidth="260"
      labelAlign="right"
      class="baseForm"
    >
      <!-- <u-form-item label="入库单号" borderBottom prop="bizNum">
        <u-input
          :value="formData.bizNum"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
        />
      </u-form-item> -->
      <u-form-item
        label="物品类型"
        class="required-form"
        borderBottom
        prop="assetType"
      >
        <picker
          @change="
            (e) => handleDictPicker(e, dict[dictEnum.物品类型], 'assetType')
          "
          :value="pickerIndex"
          :range="dict[dictEnum.物品类型]"
          :disabled="
            !!(warehousingMaterialList && warehousingMaterialList.length)
          "
          range-key="dictValue"
        >
          <u-input
            :value="warehousingName"
            :disableColor="
              !!(warehousingMaterialList && warehousingMaterialList.length)
                ? '#F5F7FA'
                : '#fff'
            "
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item
        label="入库场景"
        class="required-form"
        prop="bizScene"
        borderBottom
      >
        <picker
          :disabled="
            !!(warehousingMaterialList && warehousingMaterialList.length)
          "
          @change="(e) => handlePicker(e, sceneState, 'bizScene')"
          :value="pickerIndex"
          :range="sceneState"
          range-key="name"
        >
          <u-input
            :value="getDictName(sceneState, formData.bizScene)"
            :disableColor="
              !!(warehousingMaterialList && warehousingMaterialList.length)
                ? '#F5F7FA'
                : '#fff'
            "
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="来源单据" prop="documentSource" borderBottom>
        <u-input
          type="text"
          placeholder="请输入"
          v-model="formData.documentSource"
        />
      </u-form-item>
      <u-form-item label="权属部门" prop="workOrder" borderBottom>
        <u-input
          :value="formData.deptName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
          @click.native="$refs.treePicker._show()"
        />
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="入库登记人" prop="createUserName" borderBottom>
        <u-input
          disableColor="#ffffff"
          :value="formData.createUserName"
          placeholder="请选择"
          disabled
          type="text"
        />
      </u-form-item>
      <u-form-item label="审核人部门" prop="verifyDeptName" borderBottom>
        <u-input
          :value="formData.verifyDeptName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
          clearable
          @click.native="$refs.verifyTreePicker._show()"
        />
        <view slot="right" style="display: flex; align-item: center">
          <u-icon
            v-show="formData.verifyDeptName"
            name="close-circle-fill"
            @click="verifyDeptConfirm([], '')"
          ></u-icon>
          <u-icon name="arrow-right"></u-icon>
        </view>
      </u-form-item>
      <u-form-item label="审核人" prop="verifyId" borderBottom>
        <picker
          @change="(e) => handlePicker(e, userList, 'verifyId', 'verifyName')"
          :value="pickerIndex"
          :range="userList"
          range-key="name"
        >
          <u-input
            :value="formData.verifyName"
            disableColor="#ffffff"
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <view slot="right" style="display: flex; align-item: center">
          <u-icon
            v-show="formData.verifyName"
            name="close-circle-fill"
            @click="handlePicker(null, [], 'verifyId', 'verifyName')"
          ></u-icon>
          <u-icon name="arrow-right"></u-icon>
        </view>
      </u-form-item>
      <u-form-item label="供应商" prop="supplierId" borderBottom>
        <picker
          @change="
            (e) => handlePicker(e, supplierList, 'supplierId', 'supplierName')
          "
          :value="pickerIndex"
          :range="supplierList"
          range-key="name"
        >
          <u-input
            :value="formData.supplierName"
            disableColor="#ffffff"
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="送货人" prop="deliveryName" borderBottom>
        <u-input
          type="text"
          placeholder="请输入"
          v-model="formData.deliveryName"
        />
      </u-form-item>
      <u-form-item label="送货人联系方式" prop="deliveryPhone" borderBottom>
        <u-input
          type="text"
          placeholder="请输入"
          v-model="formData.deliveryPhone"
        />
      </u-form-item>
      <u-form-item label="紧急状态" prop="urgent" borderBottom>
        <picker
          @change="(e) => handlePicker(e, emergencyState, 'urgent')"
          :value="pickerIndex"
          :range="emergencyState"
          range-key="name"
        >
          <u-input
            :value="getDictName(emergencyState, formData.urgent)"
            disableColor="#ffffff"
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <!-- <u-form-item label="附件" prop="contentImage" borderBottom>
        <u-button type="success" @click="chooseFile">选择文件</u-button>
      </u-form-item> -->
      <u-form-item label="备注" prop="remark" borderBottom>
        <u-textarea
          confirmType="done"
          :maxlength="-1"
          height="80"
          v-model="formData.remark"
          placeholder="请输入"
        ></u-textarea>
      </u-form-item>
    </u-form>

    <uni-collapse ref="collapse" v-model="collapseOpen">
      <uni-collapse-item
        :typeOpen="1"
        title=""
        name="collapse1"
        :open="true"
        :key="detailOpen"
        :show-animation="true"
      >
        <template v-slot:title>
          <view class="detail-box">
            <view data-v-41027c34="" class="uni-collapse-item__title-wrap"
              ><view
                data-v-41027c34=""
                class="uni-collapse-item__title-box uni-collapse-item__title-box-base"
                ><!----><text data-v-41027c34="" class="tag tag-base"
                  ><text></text></text
                ><text data-v-41027c34="" class="uni-collapse-item__title-text"
                  ><text>入库明细</text></text
                ></view
              ></view
            >
            <u-button
              type="success"
              size="small"
              class="selectEnterType"
              text="手动添加"
              @click.native.stop="selectType"
            ></u-button>
          </view>
        </template>
        <u-form
          labelPosition="left"
          :model="{ warehousingMaterialList: warehousingMaterialList }"
          ref="lisrFormRef"
          labelWidth="190"
          :rules="listRules"
          errorType="none"
          labelAlign="right"
          :labelStyle="{
            fontSize: '28rpx',
          }"
        >
          <view class="listContent">
            <view
              class="listBox"
              v-for="(item, index) in warehousingMaterialList"
              :key="index"
            >
              <view class="listTit">
                <view class="name">{{ item.assetCode }}</view>
                <view class="delete" @click="getDelete(index)">
                  <uni-icons
                    custom-prefix="iconfont"
                    type="icon-shanchu"
                    size="24"
                    color="#fa3534"
                  ></uni-icons>
                </view>
              </view>
              <view class="listCont" :class="{ save: item.isSave }">
                <view class="item w100">
                  <u-form-item :label="`名称`">
                    {{ item.assetName }}
                  </u-form-item>
                </view>
                <view
                  class="item"
                  v-for="(itm, index) in tableHeader"
                  :key="index"
                >
                  <u-form-item :label="itm.label">
                    {{ item[itm.prop] }}
                  </u-form-item>
                </view>
                <view class="item">
                  <u-form-item
                    label="批次号"
                    :prop="`warehousingMaterialList.${index}.batchNum`"
                  >
                    <text
                      class="text-primary"
                      @click="handleBatchSetting(item, index)"
                      >{{ item.batchNum || "设置" }}</text
                    >
                  </u-form-item>
                </view>
                <view class="item">
                  <u-form-item
                    label="最小包装单元"
                    :prop="`warehousingMaterialList.${index}.measurementUnit`"
                    >{{ item.measurementUnit }}{{ item.unit }} /{{
                      item.minPackUnit
                    }}
                  </u-form-item>
                </view>
                <view class="item">
                  <u-form-item
                    label="包装数量"
                    :prop="`warehousingMaterialList.${index}.outInNum`"
                  >
                    {{ item.outInNum }}
                  </u-form-item>
                </view>

                <view class="item">
                  <u-form-item label="单价" prop="univalence">
                    {{ item.univalence
                    }}{{ { yuan: "元", wanyuan: "万元" }[item.univalenceUnit] }}
                  </u-form-item>
                </view>
                <view class="item">
                  <u-form-item
                    label="总额"
                    prop="contentImage"
                    :show-overflow-tooltip="true"
                  >
                    {{
                      calcSum(
                        item.outInNum,
                        item.measurementUnit,
                        item.univalence,
                        item
                      )
                    }}
                  </u-form-item>
                </view>
                <view class="item" style="width: 100%">
                  <u-form-item
                    style="width: 100%"
                    label="仓库"
                    :prop="`warehousingMaterialList.${index}.cargoSpaceCode`"
                  >
                    {{
                      `${item.warehouseName}-${item.areaName}-${item.shelfCode}-${item.cargoSpaceCode}`
                    }}
                  </u-form-item>
                </view>
              </view>
            </view>
          </view>
        </u-form>
      </uni-collapse-item>
    </uni-collapse>
    <view class="footBox">
      <view class="reg" @click="getsure">
        <uni-icons custom-prefix="iconfont" size="20" color="#fff"></uni-icons>
        提交
      </view>
    </view>

    <ba-tree-picker
      ref="treePicker"
      :multiple="false"
      @select-change="deptConfirm"
      key="dept"
      title="选择部门"
      :localdata="deptList"
      valueKey="code"
      textKey="name"
      childrenKey="children"
    />
    <ba-tree-picker
      ref="verifyTreePicker"
      key="verify"
      :multiple="false"
      @select-change="verifyDeptConfirm"
      title="选择部门"
      :localdata="deptList"
      valueKey="code"
      textKey="name"
      childrenKey="children"
    />
    <WarehouseChoose ref="warehouseChooseRef" />
    <!-- <ScanCode></ScanCode> -->
    <!-- <l-file ref="lFile" @up-success="upSuccess"></l-file> -->
  </view>
</template>

<script>
// import ScanCode from '@/components/ScanCode.vue'
import { post, postJ, get, getJ } from "@/utils/api.js";
import WarehouseChoose from "@/components/WarehouseChoose";
import {
  warehousingType,
  sceneState,
  inputStatus,
  emergencyState,
  warehousingMaterialListTable,
  getDictName,
  materialType,
} from "../enum.js";
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
// import addDetails from '@/components/addDetails'
import UploadFileNew from "@/components/UploadFileNew";
// import { getRuleNo } from '@/utils/utils.js'
import { tableHeader } from "../common";
import dictMixins from "@/mixins/dictMixins.js";
export default {
  components: {
    WarehouseChoose,
    baTreePicker,
    UploadFileNew,
  },
  mixins: [dictMixins],
  data() {
    return {
      collapseOpen: "collapse1",
      curDateType: "manufactureTime",
      emergencyState,
      warehousingType,
      materialType,
      sceneState,
      inputStatus,
      getDictName,
      detailOpen: false,
      codeOpen: false,
      deptList: [], //部门
      supplierList: [], //供应商
      formData: {
        // bizNum: getRuleNo('IN'),
        assetType: "",
        bizScene: "",
        deptName: "",
        deptCode: "",
        deptName: "",
        createUserName: "",
        registerId: "",
        verifyId: "",
        verifyName: "",
        verifyDeptCode: "",
        verifyDeptName: "",

        // outInTime: '',
        deliveryName: "",
        deliveryPhone: "",
        urgent: "",
        contentImage: [],
        remark: "",
        supplierId: "",
        supplierName: "",
      },
      statusList: [
        {
          id: 1,
          name: "紧急",
        },
        {
          id: 2,
          name: "中等",
        },
        {
          id: 1,
          name: "普通",
        },
      ], //紧急状态
      pickerIndex: 0,
      warehousingMaterialList: [],
      userList: [],
      rules: {
        assetType: {
          type: "number",
          required: true,
          message: "请选择入库产品类型",
          trigger: ["blur", "change"],
        },
        bizScene: {
          type: "number",
          required: true,
          message: "请选择入库场景",
          trigger: ["blur", "change"],
        },
        // contentImage: {
        //   type: 'array',
        //   required: true,
        //   message: '请上传附件',
        //   trigger: ['blur', 'change']
        // }
      },
      settingIndex: 0,
    };
  },
  onShow() {
    // const _this = this
    // uni.$off('scancode') // 每次进来先 移除全局自定义事件监听器
    // uni.$on('scancode', function (data) {
    //   uni.navigateBack({
    //     delta: 1
    //   })
    //   _this.qrContent = data.code.trim()
    //   _this.handleScan()
    // })
    this.collapseOpen = "collapse1";
  },
  onLoad(options) {
    this.requestDict("物品类型");
    this.getDept();
    this.getSupplier();

    const userInfo = uni.getStorageSync("userInfo");
    this.formData.createUserName = userInfo.name;
    this.formData.registerId = userInfo.id;
    uni.$on("setSelectList", (selectList) => {
      console.log(selectList, "------------------22---------");
      if (selectList?.length) {
        this.warehousingMaterialList.push(
          ...selectList.map((next) => {
            delete next.updateTime;
            delete next.createTime;
            let cur = {};
            if (this.formData.bizScene == 5) {
              cur = {
                cargoSpaceCode: "", //货位编码
                cargoSpaceId: "", //货位id
                shelfId: "", //货架id
                shelfCode: "", //货架名称
                areaId: "", //库区id
                areaName: "", //库区名称
                warehouseId: "", //仓库id
                warehouseName: "", //仓库名称
                assetType: this.formData.assetType,
                expirationDate: "",
                batchNum: "",
                measurementUnit: "",
                bizStatus: 1,
                contentImage: [],
                ...next,
              };
            } else {
              next.realInventoryAmount = next.realInventoryAmount || 0;
              cur = {
                ...next,
                cargoSpaceCode: "", //货位编码
                cargoSpaceId: "", //货位id
                shelfId: "", //货架id
                shelfCode: "", //货架名称
                areaId: "", //库区id
                areaName: "", //库区名称
                warehouseId: "", //仓库id
                warehouseName: "", //仓库名称
                assetType: this.formData.assetType,
                expirationDate: "",
                batchNum: "",
                outInNum: "",
                measurementUnit: "",
                bizStatus: 1,
                contentImage: [],
              };
            }

            return cur;
          })
        );

        console.log(
          this.warehousingMaterialList,
          "------------------this.warehousingMaterialList---------"
        );
        setTimeout(() => {
          this.detailOpen = !this.detailOpen;
          this.$refs.collapse && this.$refs.collapse.resize();
        }, 0);
      }
    });
    // 明细信息填写
    uni.$on("batchNumBack", (warehousingMaterialList) => {
      if (warehousingMaterialList?.length) {
        this.warehousingMaterialList = warehousingMaterialList;
      }
    });
  },
  mounted() {
    // this.getAddDetails();
  },
  computed: {
    tableHeader() {
      return tableHeader(this.formData.assetType);
    },
    materialCodeReqList() {
      return this.warehousingMaterialList
        .map((i) => i.warehouseLedgerDetails || [])
        .flat();
    },
    isMaterial() {
      return this.formData.assetType == 3;
    },
    warehousingName() {
      this.warehousingMaterialList = [];
      return this.getDictValue("物品类型", this.formData.assetType);
    },
    listRules() {
      return this.warehousingMaterialList.reduce((cur, pre, index) => {
        return {
          ...cur,
          [`warehousingMaterialList.${index}.cargoSpaceCode`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
          [`warehousingMaterialList.${index}.measurementUnit`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
          [`warehousingMaterialList.${index}.outInNum`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
          [`warehousingMaterialList.${index}.batchNum`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
        };
      }, {});
    },
  },
  methods: {
    handleScan() {
      if (this.formData.bizScene !== "" && this.formData.bizScene != 5) {
        uni.showModal({
          title: "提示",
          content: "仅退还入库支持扫码,是否清除已选明细并切换至退还入库?",
          success: async (res) => {
            if (res.confirm) {
              this.warehousingMaterialList = [];
              this.formData.bizScene = 5;
              this.getData();
            }
          },
        });
        return;
      }
      this.getData();
    },
    // goScan () {
    //   uni.navigateTo({
    //     url: '/pages/ScanCode/ScanCode'
    //   })
    // },
    // 根据条码请求设备数据 @_@
    getData() {
      let par = {
        barType: this.qrContent.split("@_@")[1] || 0,
        qrContent: this.qrContent,
      };
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      postJ(this.apiUrl + "/scan/getAssetInfo", par)
        .then((res) => {
          let data = res.data;
          console.log(data, "qrContent");
          if (data.assetType === undefined) {
            uni.showToast({
              title: "请扫码物品码",
              icon: "none",
            });
            return;
          } else if (data.source == 2) {
            uni.showModal({
              title: "提示",
              content: "当前物品已在库",
              success: async (res) => {},
            });

            return;
          } else if (
            this.warehousingName &&
            this.formData.assetType != data.assetType
          ) {
            uni.showToast({
              title: `当前物品不属于${this.warehousingName}分类`,
              icon: "none",
            });
            return;
          }

          this.setScanMaterial(data);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    async setScanMaterial(data) {
      this.formData.assetType = data.assetType;
      this.formData.bizScene = 5;

      const curMap = {
        assetId: "id",
        assetCode: "informationCode", //编码
        assetName: "informationName", //名称
        materialId: "id",
        materialName: "informationName",
        batchNo: "", //批次号
        unit: "measuringUnit", //单位
        minPackUnit: "packingUnit", //最小包装单位
      };
      let obj = {};

      for (const key in curMap) {
        obj[key] = (curMap[key] && data.information[curMap[key]]) || "";
      }

      let detailObj = uni.$u.deepClone(obj);

      detailObj.onlyCode = data.assetCode;

      obj = {
        ...data.information,
        ...obj,
        ...{
          cargoSpaceCode: "", //货位编码
          cargoSpaceId: "", //货位id
          shelfId: "", //货架id
          shelfCode: "", //货架名称
          areaId: "", //库区id
          areaName: "", //库区名称
          warehouseId: "", //仓库id
          warehouseName: "", //仓库名称
          measurementUnit: "",
          bizStatus: 1,
          contentImage: [],
        },
      };
      let warehouseLedgerDetails = [detailObj];

      this.warehousingMaterialList.push(obj);

      this.$set(
        this.warehousingMaterialList[this.warehousingMaterialList.length - 1],
        "warehouseLedgerDetails",
        warehouseLedgerDetails
      );
      this.$set(
        this.warehousingMaterialList[this.warehousingMaterialList.length - 1],
        "selfWarehouseLedgerDetails",
        uni.$u.deepClone(warehouseLedgerDetails)
      );

      this.handleBatchSetting(
        obj,
        this.warehousingMaterialList.length - 1,
        true
      );
    },
    calcSum(a, b, c, row) {
      if (
        (Number.isNaN(+a) && a !== "") ||
        (Number.isNaN(+b) && b !== "") ||
        (Number.isNaN(+c) && c !== "")
      ) {
        return "";
      }

      return a * b * c + { yuan: "元", wanyuan: "万元" }[row.univalenceUnit];
    },
    handleBatchSetting(item, index, isScan = false) {
      this.settingIndex = index;
      uni.setStorageSync("inputData", item);
      uni.setStorageSync(
        "warehousingMaterialList",
        this.warehousingMaterialList || []
      );

      uni.navigateTo({
        url:
          "/pages/warehouse/enterHouse/batchNumEdit?bizScene=" +
          this.formData.bizScene +
          "&assetType=" +
          this.formData.assetType +
          "&index=" +
          index +
          "&isScan=" +
          isScan,
      });
    },
    chooseFile(file) {
      console.log(file);
      this.$refs.lFile.upload({
        //替换为你的上传接口地址
        url: this.apiUrl + "/data/doc/add",
        // 服务端接收附件的key
        name: "file",
        //根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
        header: {
          Authorization: "bearer eyJhbGciO",
          uid: "27682",
          client: "app",
        },

        // 限制选择附件的大小上限，默认10M
        // maxSize: 20,

        // 若需要在body单独添加附件名或附件大小如下方式传入组件：
        // addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
        // addSize: '后端要的附件大小字段key'

        // body参数直接写key,value,如：
        // date: '2020-1-1',
        // key2: 'value2',
      });
    },
    // 抬头下拉信息保存
    handlePicker(e, list, idKey, nameKey) {
      if (idKey) {
        this.formData[idKey] = list[e?.detail.value]?.id;
      }
      if (nameKey) {
        this.formData[nameKey] = list[e?.detail.value]?.name;
      }
      this.$nextTick(() => {
        if (idKey === "assetType" || idKey === "bizScene") {
          this.$refs.formRef.validateField(idKey);
        }
      });
    },
    // 抬头下拉信息保存
    handleDictPicker(e, list, idKey, nameKey) {
      if (idKey) {
        this.formData[idKey] = list[e?.detail.value]?.dictCode;
      }
      if (nameKey) {
        this.formData[nameKey] = list[e?.detail.value]?.dictValue;
      }
      this.$nextTick(() => {
        if (idKey === "assetType" || idKey === "bizScene") {
          this.$refs.formRef.validateField(idKey);
        }
      });
    },
    // 明细下拉信息保存
    handleListPicker(e, list, item, idKey, nameKey) {
      if (idKey) {
        item[idKey] = list[e.detail.value].id;
      }
      if (nameKey) {
        item[nameKey] = list[e.detail.value].name;
      }
    },
    //获取仓库信息
    handleWarehouseChoose(item) {
      this.$refs.warehouseChooseRef.openDefault(item, (res) => {
        Object.assign(item, res);
      });
    },
    //状态
    getstatus(e) {
      this.formData.houseType = this.statusList[e.detail.value].name;
    },
    //上传附件
    getUpFlie(res) {
      console.log(res);
      let arr = [];
      res.forEach((item) => {
        let obj = {
          accessUrl: item.accessUrl,
          docId: item.docId,
          name: item.name,
          size: item.size,
          url: item.url,
          type: 1,
        };
        // obj.type.id = item.type.id;
        // obj.type.value = item.type.name;
        arr.push(obj);
      });
      this.formData.attaments = arr;
    },
    //选择入库类别跳转
    selectType() {
      if (!this.formData.assetType) {
        uni.showToast({
          title: "请选择入库类型",
          icon: "none",
        });
        return;
      }
      if (!this.formData.bizScene) {
        uni.showToast({
          title: "请选择入库场景",
          icon: "none",
        });
        return;
      }
      uni.navigateTo({
        url:
          "/pages/warehouse/enterHouse/selectEnterType?warehousingType=" +
          this.formData.assetType +
          "&warehousingName=" +
          this.warehousingName +
          "&bizScene=" +
          this.formData.bizScene,
      });
    },
    //删除
    getDelete(index) {
      uni.showModal({
        title: "提示",
        content: "是否删除当前明细",
        success: (res) => {
          if (res.confirm) {
            this.warehousingMaterialList.splice(index, 1);
          }
        },
      });
    },
    // 入库操作
    listEdit(row) {
      this.$set(row, "isSave", false);
    },
    listSave(row, index) {
      const fileds = [
        `warehousingMaterialList.${index}.cargoSpaceCode`,
        `warehousingMaterialList.${index}.batchNum`,
      ];

      if (this.formData.bizScene != 5) {
        fileds.push(
          ...[
            `warehousingMaterialList.${index}.outInNum`,
            `warehousingMaterialList.${index}.measurementUnit`,
          ]
        );
      } else if (
        this.warehousingMaterialList.some(
          (i) => !i.selfWarehouseLedgerDetails?.length
        )
      ) {
        uni.showToast({
          title: "请选择资产编号！",
          icon: "none",
        });
        return;
      }
      Promise.all(
        fileds.map(
          (item) =>
            new Promise(async (resolve, rej) => {
              this.$refs.lisrFormRef.validateField(item, (err) => {
                if (err?.length) {
                  rej(err);
                } else {
                  resolve();
                }
              });
            })
        )
      )
        .then((res) => {
          this.$set(row, "isSave", true);
          if (this.formData.bizScene != 5) {
            this.createMaterialCode(row);
          } else {
            // 退还
            this.createMaterialCodeReturn(row);
          }
        })
        .catch((err) => {
          uni.showToast({
            icon: "error",
            title: "请填入必填项！",
          });
        });
    },
    //入库明细删除
    listDel(row, index) {
      this.warehousingMaterialList.splice(index, 1);
    },
    // 入库明细生成条码信息
    async createMaterialCode(row) {
      // 添加相同物品重新更新明细 原料编码
      const list = this.warehousingMaterialList.filter(
        (i) =>
          i.assetCode === row.assetCode &&
          i.batchNum === row.batchNum &&
          i.isSave
      );

      const num = list.reduce((num, pre) => {
        num += row.isUnpack ? pre.outInNum * pre.measurementUnit : pre.outInNum;
        return num;
      }, 0);

      const res = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
        batchNum: row.batchNum,
        assetCode: row.assetCode,
        num,
      });
      if (res?.success) {
        list.forEach((item) => {
          if (item.warehouseLedgerDetails?.length) {
            item.warehouseLedgerDetails.forEach((i) => {
              i.onlyCode = res.data.shift().onlyCode;
            });
          } else {
            this.$set(
              item,
              "warehouseLedgerDetails",
              Array.from(
                new Array(
                  item.isUnpack
                    ? item.outInNum * item.measurementUnit
                    : +item.outInNum
                ),
                (val, idx) => {
                  return {
                    ...item,
                    onlyCode: res.data.shift().onlyCode,
                    bizStatus: 1,
                    contentImage: [],
                  };
                }
              )
            );
          }
        });
      }

      // 添加相同物品，重复批次号 重新更新明细 包装编码
      const batchList = this.warehousingMaterialList.filter(
        (i) => i.batchNum === row.batchNum && i.isSave
      );
      if (batchList.length) {
        const num = batchList.reduce((num, pre) => {
          num += +pre.outInNum;
          return num;
        }, 0);
        const res1 = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
          batchNum: row.batchNum,
          num,
        });
        if (res1?.success) {
          batchList.forEach((item) => {
            let num = res1.data.shift()?.num;
            let measurementUnit = item.measurementUnit;

            if (item.warehouseLedgerDetails?.length) {
              item.warehouseLedgerDetails.forEach((i, index) => {
                this.$set(i, "num", num);
                if (!item.isUnpack) {
                  if (index < item.warehouseLedgerDetails.length - 1) {
                    num = res1.data.shift()?.num;
                  }
                } else {
                  // 拆包的包装编码一致
                  measurementUnit--;
                  if (
                    measurementUnit === 0 &&
                    index < item.warehouseLedgerDetails.length - 1
                  ) {
                    measurementUnit = item.measurementUnit;
                    num = res1.data.shift()?.num;
                  }
                }
              });
            }
          });
        }
      }
    },
    // 入库明细生成条码信息 退还
    async createMaterialCodeReturn(row) {
      // 添加相同物品重新更新明细 原料编码
      const list = this.warehousingMaterialList.filter(
        (i) => i.batchNum === row.batchNum && i.isSave
      );
      // 退还
      const res = await postJ(this.apiUrl + "/outInWarehouse/getAssetNum", {
        batchNum: row.batchNum,
        num: list.reduce((num, pre) => {
          num += pre.selfWarehouseLedgerDetails.length;
          return num;
        }, 0),
      });
      if (res?.success) {
        list.forEach((item) => {
          const num = res.data.shift().num;
          if (item.warehouseLedgerDetails?.length) {
            item.warehouseLedgerDetails.forEach((i) => {
              i.num = num;

              if (!item.isUnpack) {
                // 拆包的包装编码一致
                num = res.data.shift()?.num;
              }
            });
          } else {
            this.$set(
              item,
              "warehouseLedgerDetails",
              item.selfWarehouseLedgerDetails.map((val, idx) => {
                let obj = {
                  ...val,
                  bizStatus: 1,
                  batchNum: item.batchNum,
                  cargoSpaceCode: item.cargoSpaceCode, //货位编码
                  cargoSpaceId: item.cargoSpaceId, //货位id
                  shelfId: item.shelfId, //货架id
                  shelfCode: item.shelfCode, //货架名称
                  areaId: item.areaId, //库区id
                  areaName: item.areaName, //库区名称
                  warehouseId: item.warehouseId, //仓库id
                  warehouseName: item.warehouseName, //仓库名称
                  num,
                };
                if (!item.isUnpack) {
                  // 拆包的包装编码一致
                  num = res.data.shift()?.num;
                }
                return obj;
              })
            );
          }
        });
      }
    },
    //确定提交
    getsure() {
      this.$refs.formRef.validate().then((res) => {
        if (!this.warehousingMaterialList?.length) {
          uni.showToast({
            icon: "error",
            title: "请添加明细！",
          });
          return;
        } else if (
          this.warehousingMaterialList.some(
            (item) => !item.warehouseLedgerDetails?.length
          )
        ) {
          uni.showToast({
            icon: "error",
            title: "请完善明细信息！",
          });
          return;
        }

        const params = {
          outInWarehouse: { ...this.formData, bizStatus: 1 },
          warehouseLedgerInfos: this.warehousingMaterialList,
        };
        postJ(this.apiUrl + "/outInWarehouse/add", params).then((res) => {
          if (res?.success) {
            uni.showToast({
              icon: "success",
              title: "保存成功",
            });
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          }
        });
      });
    },
    // 部门确认
    deptConfirm(data, name) {
      this.formData.deptName = name;
      this.formData.deptCode = data[0];
    },
    // 部门确认
    verifyDeptConfirm(data, name) {
      this.formData.verifyDeptCode = data[0];
      this.formData.verifyDeptName = name;
      this.formData.verifyId = "";
      this.formData.verifyName = "";

      this.getUser(data[0]);
    },
    // 获取部门
    getDept() {
      get(this.apiUrl + "/main/org/dept/effectiveTree").then((res) => {
        if (res?.success) {
          this.deptList = res.data;
        }
      });
    },
    // 获取供应商
    getSupplier() {
      post(this.apiUrl + `/main/supplier/list?page=1&size=999`, {
        page: 1,
        size: 999,
      }).then((res) => {
        if (res?.success) {
          this.supplierList = res.data.items;
        }
      });
    },

    // 获取人员
    getUser(deptCode) {
      post(this.apiUrl + "/main/user/list", {
        deptCode,
        page: 1,
        size: 9999,
      }).then((res) => {
        if (res?.success) {
          this.userList = res.data.items.map((item) => {
            item.name = item.trueName;
            item.id = item.userId;
            return item;
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.mainBox {
  padding-bottom: 120rpx;

  /deep/.required-form .u-form-item__body__left__content__label::before {
    content: "*";
    color: red;
  }
}

.picList {
  display: flex;
  align-items: center;
  justify-items: flex-start;
  flex-wrap: wrap;
}
/deep/.baseForm {
  .u-form-item__body {
    padding: 10rpx !important;
  }
}
/deep/.picList .u-image {
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

/deep/.cLine .u-line:nth-child(1) {
  border-bottom: none !important;
}

.detail-box {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;

  /deep/uni-button {
    margin: 0 !important;
    width: 180rpx;
  }
}

.footBox {
  position: fixed;
  left: 0px;
  bottom: 0px;
  height: 100rpx;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  view {
    width: 100%;
    height: 100%;
    text-align: center;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .reg {
    background: $u-success-dark;
  }

  .add {
    background: $uni-color-primary;
  }

  .uni-icons {
    margin-right: 8rpx !important;
  }
}

.listBox {
  padding: 20rpx 10rpx;
  border-bottom: 1px #f2f2f2 solid;
  position: relative;
  &.code {
    .label {
      width: 120rpx !important;
    }
  }
  .listTit {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    /deep/uni-button {
      margin-right: 20rpx;
      width: 100rpx;

      &.assets {
        width: 180rpx;
      }
    }
    .name {
      width: 50%;
      margin-left: 10px;
      overflow: hidden;
      white-space: nowrap;
      -o-text-overflow: ellipsis;
      text-overflow: ellipsis;
      font-size: 30rpx;
    }

    .weight {
      width: 30%;
      font-size: 30rpx;
      margin-left: auto;
      margin-right: 60rpx;
      position: relative;
      display: flex;

      input {
        margin-right: 10rpx;
        border: 1px solid black;
        width: 40%;
        height: 20rpx;
      }
    }

    .weight::after {
      position: absolute;
      right: -30rpx;
      top: 50%;
      content: "";
      background: #eee;
      width: 1px;
      height: 28rpx;
      margin-top: -14rpx;
    }
  }

  .more {
    position: absolute;
    bottom: 26rpx;
    right: 30rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.listCont {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 20rpx;
  margin-left: 10rpx;

  &.save {
    .u-input {
      border: none;
    }
  }
  .u-input {
    border: 1px solid rgb(229, 229, 229);
    height: 15rpx !important;
  }

  .item {
    width: 50%;
    font-size: 28rpx;
    margin-bottom: 10rpx;
    // line-height: 45rpx;
    // overflow: hidden;
    // white-space: nowrap;
    // text-overflow: ellipsis;
    // -o-text-overflow: ellipsis;
    // color: #000;
    // display: flex;
    /deep/.u-form-item__body {
      padding: 0 !important;
    }
    /deep/.u-input__content__field-wrapper__field,
    /deep/.u-form-item {
      font-size: 28rpx !important;
    }

    text.label {
      width: 120rpx;
      display: inline-block;
      text-align: right;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
    }
    /deep/.uni-date__x-input {
      height: 40rpx;
      font-size: 28rpx;
    }

    /deep/.uni-date {
      width: 48%;
      display: inline-block;
      .uni-icons {
        display: none !important;
      }
      .uni-date-x {
        padding: 0 !important;
      }
    }
  }

  .item text {
    color: #666;
  }
}

.listBox:last-child {
  border: none !important;
}

.textBox {
  border: 1px #f2f2f2 solid;
  height: 160px;
  display: block;
  width: auto !important;
}

.saveBtn {
  width: 50%;
  margin: 40rpx auto;
}
.top-css {
  border-bottom: 1px solid rgb(207, 204, 204);
}
</style>
