<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="新增出库单"
      @clickLeft="back"
      right-icon="scan"
      @clickRight="handleScan"
    >
      <!--右菜单-->
      <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.物品类型]"
          range-key="dictValue"
          :disabled="
            !!(warehousingMaterialList && warehousingMaterialList.length)
          "
        >
          <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
          @change="(e) => handlePicker(e, outputSceneState, 'bizScene')"
          :value="pickerIndex"
          :range="outputSceneState"
          :disabled="
            !!(warehousingMaterialList && warehousingMaterialList.length)
          "
          range-key="name"
        >
          <u-input
            :value="getDictName(outputSceneState, 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="来源单据"
        :rules="[{ required: true, errorMessage: '请选择来源单据' }]"
        v-if="formData.assetType == 7 && formData.bizScene == 4"
        prop="documentSource"
        class="required-form"
        borderBottom
      >
        <luyj-select-lay
          :value.sync="formData.documentSource"
          clearable
          :disabled="
            !!(formData.documentSource && warehousingMaterialList.length)
          "
          name="name"
          placeholder="请选择"
          :options="datalist"
          @selectitem="handleDocumentSourceChange"
        />
      </u-form-item>
      <u-form-item label="来源单据" prop="documentSource" v-else 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"
        />
        <!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
      </u-form-item>
      <u-form-item label="出库登记人" prop="createUserName" borderBottom>
        <u-input
          disableColor="#ffffff"
          disabled
          :value="formData.createUserName"
          placeholder="请选择"
          type="text"
        />
      </u-form-item>
      <u-form-item label="审核人部门" prop="verifyDeptName" borderBottom>
        <u-input
          :value="formData.verifyDeptName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
          @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="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>
        <UploadFileNew v-model="formData.contentImage" />
      </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" :show-animation="true">
      <uni-collapse-item
        :typeOpen="1"
        title=""
        :open="true"
        :key="detialOpen"
        :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="110"
          :rules="listRules"
          errorType="none"
          labelAlign="right"
          :labelStyle="{
            fontSize: '24rpx',
          }"
        >
          <view class="listContent">
            <view
              class="listBox codeMsg"
              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">
                <view class="item" style="width: 100%">
                  <text class="label">名称</text>
                  <text class="content">{{ item.assetName }}</text>
                </view>
                <view
                  class="item"
                  v-for="(itm, index) in tableHeader"
                  :key="index"
                >
                  <text class="label">{{ itm.label }}</text>
                  <text class="content">{{ item[itm.prop] }}</text>
                </view>

                <view class="item">
                  <text class="label">出库数量</text>
                  <text class="content" style="white-space: nowrap"
                    ><text style="margin-right: 20rpx"
                      >{{ item.selfSum }} {{ item.unit }}</text
                    >
                    <template v-if="!item.isUnpack"
                      >{{ item.outInNum }}{{ item.minPackUnit }}</template
                    >
                    <text
                      class="text-primary"
                      @click="handleNumSet(item, index)"
                      >设置</text
                    ></text
                  >
                </view>
              </view>
            </view>
          </view>
        </u-form>
      </uni-collapse-item>
      <uni-collapse-item
        :typeOpen="1"
        :title="`${warehousingName}明细`"
        :open="true"
        :key="codeOpen + '1'"
        :show-animation="true"
      >
        <view
          class="listBox codeMsg"
          v-for="(item, index) in this.warehousingMaterialList
            .map((i) => i.warehouseLedgerDetails || [])
            .flat()"
          :key="item.onlyCode + index + forceUpdate"
        >
          <view class="listCont">
            <view class="delete-code" @click="deleteCode(item)">
              <uni-icons
                custom-prefix="iconfont"
                type="icon-shanchu"
                size="24"
                color="#fa3534"
              ></uni-icons>
            </view>
            <view class="item" style="width: 100%">
              <text class="label long">{{ warehousingName }}编码</text>
              <text class="content">{{ item.onlyCode }}</text>
            </view>
            <view class="item">
              <text class="label">批次号</text
              ><text class="content">{{ item.batchNum }}</text>
            </view>
            <view class="item" v-if="!item.isUnpack">
              <text class="label">最小包装单元</text
              ><text class="content"
                >{{ item.measurementUnit }}{{ item.unit }} /{{
                  item.minPackUnit
                }}</text
              >
            </view>
            <view class="item">
              <text class="label">包装编码</text
              ><text class="content">{{ item.num }}</text>
            </view>
            <view class="item">
              <text class="label">转消耗</text
              ><text class="content">
                <u-checkbox-group @change="handleChange($event, item)">
                  <u-checkbox
                    :size="30"
                    :name="true"
                    :checked="item.isTransferAsset"
                  ></u-checkbox>
                </u-checkbox-group>
              </text>
            </view>
            <view
              class="item"
              style="width: 100%"
              v-if="item.manufactureTime || !item.procurementTime"
            >
              <text class="label">生产日期</text
              ><text class="content">{{ item.manufactureTime }}</text>
            </view>
            <view class="item" v-if="item.procurementTime" style="width: 100%">
              <text class="label">采购日期</text
              ><text class="content">{{ item.procurementTime }}</text>
            </view>
            <view class="item" style="width: 100%">
              <text class="label">货位</text
              ><text class="content">
                {{ item.warehouseName }}-{{ item.areaName }}-{{
                  item.shelfCode
                }}-{{ item.cargoSpaceCode }}</text
              >
            </view>
          </view>
        </view>
      </uni-collapse-item>
      <uni-collapse-item
        :typeOpen="1"
        title="已失效"
        v-if="
          formData.assetType == 7 &&
          formData.bizScene == 4 &&
          uselessList.length
        "
        :open="true"
        :show-animation="true"
      >
        <view class="listBox codeMsg" v-for="(item, index) in uselessList">
          <view class="listCont">
            <view class="item" style="width: 100%">
              <text class="label long">{{ warehousingName }}编码</text>
              <text class="content">{{ item.onlyCode }}</text>
            </view>
            <view class="item">
              <text class="label">批次号</text
              ><text class="content">{{ item.batchNum }}</text>
            </view>
            <view class="item" v-if="!item.isUnpack">
              <text class="label">最小包装单元</text
              ><text class="content"
                >{{ item.measurementUnit }}{{ item.unit }} /{{
                  item.minPackUnit
                }}</text
              >
            </view>
            <view class="item">
              <text class="label">包装编码</text
              ><text class="content">{{ item.barrelNum }}</text>
            </view>
            <view
              class="item"
              style="width: 100%"
              v-if="item.manufactureTime || !item.procurementTime"
            >
              <text class="label">生产日期</text
              ><text class="content">{{ item.manufactureTime }}</text>
            </view>
            <view class="item" v-if="item.procurementTime" style="width: 100%">
              <text class="label">采购日期</text
              ><text class="content">{{ item.procurementTime }}</text>
            </view>
            <view class="item" style="width: 100%">
              <text class="label">货位</text
              ><text class="content">
                {{ item.warehouseName }}-{{ item.areaName }}-{{
                  item.shelfCode
                }}-{{ item.cargoSpaceCode }}</text
              >
            </view>
          </view>
        </view>
      </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"
    />
    <!-- <ba-tree-picker
      ref="assetsTreePicker"
      key="assetsTree"
      :selectParent="false"
      :multiple="false"
      @select-change="assetsConfirm"
      title="选择资产类型"
      :localdata="assetsList"
      valueKey="id"
      textKey="name"
      childrenKey="children"
    /> -->
    <!-- <ScanCode @scancodedate="scancodedate"></ScanCode> -->
  </view>
</template>

<script>
import ScanCode from "@/components/ScanCode.vue";
import { post, postJ, get, getJ } from "@/utils/api.js";
import {
  warehousingType,
  outputSceneState,
  inputStatus,
  emergencyState,
  getDictName,
  materialType,
} from "../enum.js";
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
import luyjSelectLay from "@/components/luyj-select-lay/luyj-select-lay.vue";
// import addDetails from '@/components/addDetails'
import UploadFileNew from "@/components/UploadFileNew";
import { mapGetters, mapActions } from "vuex";
import { tableHeader } from "../common";
import dictEnum from "@/enum/dict";
// import { getRuleNo } from '@/utils/utils.js'
export default {
  components: {
    baTreePicker,
    UploadFileNew,
    luyjSelectLay,
    ScanCode,
  },
  data() {
    return {
      dictEnum,
      datalist: [],
      loading: false,
      forceUpdate: false,
      detialOpen: false,
      codeOpen: false,
      emergencyState,
      warehousingType,
      materialType,
      outputSceneState,
      inputStatus,
      getDictName,
      deptList: [], //部门
      supplierList: [], //供应商
      formData: {
        // bizNum: getRuleNo('OUT'),
        assetType: "",
        bizScene: "",
        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']
        // }
      },
      assetsList: [], //转资产
      curIndex: 0,
      assetsindex: 0,
      uselessList: [],
    };
  },
  watch: {
    "formData.documentSource": {
      handler() {
        if (!this.formData.documentSource && this.formData.bizScene == 4) {
          this.warehousingMaterialList = [];
        }
      },
    },
  },
  onShow() {
    uni.$off("bucketSelect");
    uni.$on("bucketSelect", (res) => {
      this.$set(
        this.warehousingMaterialList[this.curIndex],
        "warehouseLedgerDetails",
        (res || []).map((item) => {
          delete item.updateTime;
          delete item.createTime;
          item.isTransferAsset = false;
          item.isUnpack = this.warehousingMaterialList[this.curIndex].isUnpack;
          return item;
        })
      );
      this.$set(
        this.warehousingMaterialList[this.curIndex],
        "outInNum",
        res.length
      );
      this.$set(
        this.warehousingMaterialList[this.curIndex],
        "minPackUnit",
        res[0].minPackUnit
      );

      this.warehousingMaterialList[this.curIndex].selfSum =
        this.warehousingMaterialList[
          this.curIndex
        ].warehouseLedgerDetails.reduce((sum, pre) => {
          if (this.warehousingMaterialList[this.curIndex].isUnpack) {
            return ++sum;
          }
          return sum + pre.measurementUnit;
        }, 0);
      this.forceUpdate = !this.forceUpdate;
    });
    uni.$off("setSelectList");
    uni.$on("setSelectList", (selectList) => {
      if (selectList?.length) {
        this.warehousingMaterialList = selectList;

        this.$nextTick(() => {
          this.detialOpen = !this.detialOpen;
        });
      }
    });

    const _this = this;

    uni.$off("outHouseScanView"); // 每次进来先 移除全局自定义事件监听器
    uni.$on("outHouseScanView", function (data) {
      _this.setScanMaterial(data);
    });

    uni.$off("scancodedate"); // 每次进来先 移除全局自定义事件监听器
    uni.$on("scancodedate", function (data) {
      _this.scancodedate(data);
    });
  },
  onUnload() {
    uni.$off("scancodedate");
  },
  onHide() {
    uni.$off("scancodedate");
  },
  onLoad(options) {
    this.getDept();
    this.getAssetList();
    this.remoteMethod();
    this.getSupplier();
    this.requestDict("物品类型");

    const userInfo = uni.getStorageSync("userInfo");
    this.formData.createUserName = userInfo.name;
    this.formData.deptName = userInfo.dept.name;
    this.formData.deptCode = userInfo.dept.code;
    this.formData.registerId = userInfo.id;
  },
  mounted() {},
  computed: {
    ...mapGetters(["getDictValue", "dict"]),
    tableHeader() {
      return tableHeader(this.formData.assetType);
    },
    curDateType() {
      return this.materialCodeReqList[0]?.manufactureTime
        ? "manufactureTime"
        : "procurementTime";
    },
    // 条码信息
    // materialCodeReqList () {
    //   return this.warehousingMaterialList
    //     .map(i => i.warehouseLedgerDetails || [])
    //     .flat()
    // },
    warehousingName() {
      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}.minPackUnit`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
          [`warehousingMaterialList.${index}.outInNum`]: {
            type: "string",
            required: true,
            trigger: ["blur", "change"],
          },
        };
      }, {});
    },
  },
  methods: {
    ...mapActions("dict", ["requestDict"]),

    scancodedate(data) {
      if (!this.formData.bizScene && this.formData.bizScene !== 0) {
        uni.showToast({
          title: "请选择出库场景",
          icon: "none",
        });
        return;
      }
      if (this.formData.bizScene == 4 && !this.formData.documentSource) {
        uni.showToast({
          title: "请选择来源单据",
          icon: "none",
        });
        return;
      }
      this.qrContent = data.code.trim();
      this.getData();
    },

    async handleDocumentSourceChange(index, item) {
      if (!item?.value) return;
      uni.showLoading({
        title: "加载中...",
      });

      this.formData.documentSource = item.value;
      const res = await get(
        this.apiUrl + `/outInWarehouse/select/getSparePartsInfo`,
        {
          code: this.formData.documentSource,
        }
      );
      if (res?.success && res.data.length) {
        const curMap = {
          assetId: "classificationId",
          assetCode: "informationCode", //编码
          assetName: "informationName", //名称
          materialId: "classificationId",
          materialName: "informationName",
          batchNo: "", //批次号
          unit: "measuringUnit", //单位
          minPackUnit: "packingUnit", //最小包装单位
        };

        res.data.forEach((item) => {
          let obj = {};
          for (const key in curMap) {
            obj[key] = curMap[key] ? item[curMap[key]] : "";
          }
          obj.curId = obj.assetCode;
          const index = this.warehousingMaterialList.findIndex(
            (i) => i.curId === obj.curId
          );
          if (index === -1) {
            obj.warehouseLedgerDetails = [];
            this.warehousingMaterialList.push({ ...item, ...obj });
          }
        });
        const res1 = await get(
          this.apiUrl + `/outInWarehouse/getWarehouseActualDetail`,
          {
            onlyCodeList: res.data.map((i) => i.assetCode).join(","),
          }
        );

        if (res1?.success) {
          this.uselessList = res.data
            .filter(
              (i) => !res1.data.find((itm) => itm.onlyCode === i.assetCode)
            )
            .map((item) => ({
              ...item,
              onlyCode: item.assetCode,
            }));

          res1.data.forEach((item) => {
            item.curId = item.assetCode;
            const index = this.warehousingMaterialList.findIndex(
              (i) => i.curId === item.curId
            );
            if (index === -1) {
              // obj.sparePartsNum = item.num
              this.warehouseLedgerDetailsSet(item, [uni.$u.deepClone(item)]);
              this.warehousingMaterialList.push(item);
            } else {
              // this.warehousingMaterialList[index].sparePartsNum = item.num

              const idx = this.warehousingMaterialList[
                index
              ].warehouseLedgerDetails.findIndex(
                (itm) => itm.onlyCode === item.onlyCode
              );

              if (idx === -1) {
                this.warehouseLedgerDetailsSet(
                  this.warehousingMaterialList[index],
                  [
                    item,
                    ...this.warehousingMaterialList[index]
                      .warehouseLedgerDetails,
                  ]
                );
              }
            }
          });
        }
      }
      uni.hideLoading();
    },
    warehouseLedgerDetailsSet(row, res = []) {
      this.$set(
        row,
        "warehouseLedgerDetails",
        (res || []).map((item) => {
          delete item.updateTime;
          delete item.createTime;
          this.$set(item, "isTransferAsset", false);
          item.isUnpack = row.isUnpack;
          return item;
        })
      );
      this.$set(row, "outInNum", res.length);
      this.$set(row, "minPackUnit", res[0].minPackUnit);
      this.$set(
        row,
        "selfSum",
        row.warehouseLedgerDetails.reduce((sum, pre) => {
          if (row.isUnpack) {
            return ++sum;
          }
          return sum + pre.measurementUnit;
        }, 0)
      );
    },
    // 备品备件来源单号
    async remoteMethod(code) {
      const res = await get(this.apiUrl + `/outInWarehouse/getDocumentSource`, {
        code,
      });
      if (res?.success) {
        this.datalist = res.data.map((item) => ({
          label: item,
          value: item,
        }));
      }
    },

    handleScan() {
      if (!this.formData.bizScene && this.formData.bizScene !== 0) {
        uni.showToast({
          title: "请选择出库场景",
          icon: "none",
        });
        return;
      }
      if (this.formData.bizScene == 4 && !this.formData.documentSource) {
        uni.showToast({
          title: "请选择来源单据",
          icon: "none",
        });
        return;
      }
      const _this = this;
      uni.scanCode({
        onlyFromCamera: true,
        success: function (res) {
          console.log("条码类型：" + res.scanType);
          console.log("条码内容：" + res.result);
          _this.isCamera = true;
          _this.qrContent = res.result.trim();
          _this.getData();
        },
      });
    },
    // 根据条码请求设备数据 @_@
    getData() {
      console.log("根据条码请求设备数据");
      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?.warehouseDetail?.bizStatus != 1) {
            uni.showModal({
              title: "提示",
              content: "当前物品不在仓库内",
              success: async (res) => {},
            });

            return;
          } else if (data.underApproval) {
            uni.showModal({
              title: "提示",
              content: `【${data.assetCode}】正在待审批单据中`,
              success: async (res) => {},
            });

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

          uni.setStorageSync("outHouseScan", data);
          uni.navigateTo({
            url: "/pages/warehouse/inventoryAllocation/scanView?emitName=outHouseScanView&key=outHouseScan",
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    setScanMaterial(data) {
      this.formData.assetType = data.assetType;
      this.$nextTick(() => {
        this.$refs.formRef.validateField("assetType");
      });

      const onlyCode = data.assetCode;

      const curMap = {
        assetId: "id",
        assetCode: "informationCode", //编码
        assetName: "informationName", //名称
        materialId: "id",
        materialName: "informationName",
        batchNo: "", //批次号
        unit: "measuringUnit", //单位
        minPackUnit: "packingUnit", //最小包装单位
      };
      const detailMap = [
        "areaId",
        "areaName",
        "assetCode",
        "assetName",
        "assetType",
        "batchNum",
        "cargoSpaceCode",
        "cargoSpaceId",
        "expirationDate",
        "expirationDateUnit",
        "expirationTime",
        "isTransferAsset",
        "manufactureTime",
        "measurementUnit",
        "unit",
        "minPackUnit",
        "num",
        "onlyCode",
        "procurementTime",
        "shelfCode",
        "shelfId",
        "warehouseId",
        "warehouseName",
      ];

      let obj = data.information;

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

      Object.assign(obj, data.information, {
        outInNum: 1,
        assetType: data.assetType,
        realInventoryNum: data.realInventoryNum,
        warehouseId: data.warehouseDetail?.warehouseId,
        curId: obj.assetCode,
      });
      let details = {};
      detailMap.forEach((key) => {
        details[key] = data.warehouseDetail[key] || data.information[key];
      });
      details.realInventoryNum = data.realInventoryNum;
      obj.warehouseLedgerDetails = [
        {
          ...details,
          onlyCode,
          isTransferAsset: false,
        },
      ];

      delete obj.createTime;
      delete obj.updateTime;

      let index = this.warehousingMaterialList.findIndex(
        (item) => item.curId === obj.curId
      );
      console.log(this.warehousingMaterialList, obj.curId, index);
      if (index > -1) {
        const idx = (
          this.warehousingMaterialList[index].warehouseLedgerDetails || []
        ).findIndex((item) => item.onlyCode === onlyCode);
        if (idx > -1) {
          setTimeout(() => {
            uni.showToast({
              title: `【${onlyCode}】已存在，请勿重复添加`,
              icon: "none",
            });
          }, 10);

          return;
        } else {
          if (this.warehousingMaterialList[index].warehouseLedgerDetails) {
            this.warehousingMaterialList[index].warehouseLedgerDetails.push(
              obj.warehouseLedgerDetails[0]
            );
          } else {
            this.$set(
              this.warehousingMaterialList[index],
              "warehouseLedgerDetails",
              obj.warehouseLedgerDetails
            );
          }
        }
      } else {
        this.warehousingMaterialList.push(obj);
        index = this.warehousingMaterialList.length - 1;
      }
      console.log(this.warehousingMaterialList, "this.warehousingMaterialList");
      this.$set(
        this.warehousingMaterialList[index],
        "outInNum",
        this.warehousingMaterialList[index].warehouseLedgerDetails.length
      );
      this.$set(
        this.warehousingMaterialList[index],
        "minPackUnit",
        obj.warehouseLedgerDetails[0].minPackUnit
      );

      this.warehousingMaterialList[index].selfSum =
        this.warehousingMaterialList[index].warehouseLedgerDetails.reduce(
          (sum, pre) => {
            if (this.warehousingMaterialList[index].isUnpack) {
              return ++sum;
            }
            return sum + pre.measurementUnit;
          },
          0
        );

      this.forceUpdate = !this.forceUpdate;
    },
    handleChange(e, item) {
      console.log(e);
      this.$set(item, "isTransferAsset", !!(e && e[0]));
      this.forceUpdate = !this.forceUpdate;
    },
    // 转资产
    // turnToAssets (index) {
    //   this.assetsindex = index
    //   this.$refs.assetsTreePicker._show()
    // },
    // 转资产确认
    // assetsConfirm (data, name) {
    //   this.materialCodeReqList[this.assetsindex].materialId = data[0]
    //   this.materialCodeReqList[this.assetsindex].transferType =
    //     this.getAssetsName(data[0])
    //   this.materialCodeReqList[this.assetsindex].materialName = name
    // },
    // 转资产分类
    async getAssetList() {
      const res = await get(this.apiUrl + "/classify/getClassify", { id: 0 });
      if (res.success) {
        this.assetsList = res.data;
      }
    },
    // 转资产获取父级
    getAssetsName(value) {
      let res = "";
      const fn = (list, parent = []) => {
        if (res) return;
        for (const p of list) {
          const str = p.name;

          if (res) break;
          if (p.id === value) {
            res = [...parent, str].join("/");
            return;
          }

          if (p.children?.length) {
            fn(p.children, [...parent, str]);
          }
        }
      };
      fn(this.assetsList);

      return res;
    },
    handleNumSet({ assetCode }, index) {
      this.curIndex = index;
      uni.setStorageSync(
        "outputInfoData",
        this.warehousingMaterialList[this.curIndex]
      );
      uni.navigateTo({
        url: `/pages/warehouse/outHouse/bucketSelect?assetCode=${assetCode}&assetType=${this.formData.assetType}`,
      });
    },
    // 抬头下拉信息保存
    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 === "bizScene") {
          this.$refs.formRef.validateField(idKey);
        }
      });
      if (idKey === "bizScene" && this.formData.assetType == 7) {
        this.formData.documentSource = "";
      }
    },
    // 抬头下拉信息保存
    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);
        }
      });
      if (idKey === "assetType" && this.formData.bizScene == 4) {
        this.formData.documentSource = "";
      }

      this.$nextTick(() => {
        if (idKey === "assetType") {
          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;
      }
    },
    //上传附件
    getUpFlie(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 && this.formData.bizScene !== 0) {
        uni.showToast({
          title: "请选择出库场景",
          icon: "none",
        });
        return;
      }
      if (this.formData.bizScene == 4 && !this.formData.documentSource) {
        uni.showToast({
          title: "请选择来源单据",
          icon: "none",
        });
        return;
      }
      const storageKey = Date.now() + "";
      uni.setStorageSync(storageKey, this.warehousingMaterialList);
      uni.navigateTo({
        url:
          "/pages/warehouse/outHouse/selectOutType?warehousingType=" +
          this.formData.assetType +
          "&warehousingName=" +
          this.warehousingName +
          "&storageKey=" +
          storageKey,
      });
    },
    // //接收添加出库明细
    // getChooseInfo(res) {
    // 	this.formData.numDetails = res;
    // 	//console.log(this.form);
    // },
    //删除
    getDelete(index) {
      uni.showModal({
        title: "提示",
        content: "是否删除当前明细",
        success: (res) => {
          if (res.confirm) {
            this.warehousingMaterialList.splice(index, 1);
          }
        },
      });
    },
    // 条码删除
    deleteCode(item) {
      uni.showModal({
        title: "提示",
        content: `是否删除当前${this.warehousingName}明细`,
        success: (res) => {
          if (res.confirm) {
            const parent = this.warehousingMaterialList.find(
              (i) => i.assetCode === item.assetCode
            );

            if (parent) {
              const index = parent.warehouseLedgerDetails.findIndex(
                (i) => i.onlyCode === item.onlyCode
              );
              if (index > -1) {
                parent.warehouseLedgerDetails.splice(index, 1);
                parent.outInNum -= 1;
                parent.selfSum = parent.warehouseLedgerDetails.reduce(
                  (sum, pre) => {
                    if (parent.isUnpack) {
                      return ++sum;
                    }
                    return sum + pre.measurementUnit;
                  },
                  0
                );

                this.forceUpdate = !this.forceUpdate;
              }
            }
          }
        },
      });
    },
    //确定提交
    getsure() {
      this.$refs.formRef.validate().then((res) => {
        if (!this.warehousingMaterialList?.length) {
          uni.showToast({
            icon: "none",
            title: "请添加出库明细！",
          });
          return;
        } else if (
          this.warehousingMaterialList.some((item) => !item.outInNum)
        ) {
          uni.showToast({
            icon: "none",
            title: `请添加${this.warehousingName}明细！`,
          });
          return;
        }

        const params = {
          outInWarehouse: { ...this.formData, bizStatus: 2 },
          warehouseLedgerInfos: this.warehousingMaterialList,
        };

        console.log("getsure-----", params);
        postJ(this.apiUrl + "/outInWarehouse/add", params).then((res) => {
          console.log("outInWarehouse/add", 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;
  height: 80rpx;
  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;

  .listTit {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    /deep/uni-button {
      margin-right: 20rpx;
    }
    .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;
  }
  .operation {
    padding-right: 20rpx;
    font-size: 28rpx;
    /deep/.u-text {
      justify-content: flex-end !important;
    }
  }
}
.codeMsg {
  .item {
    display: flex;
    align-items: center;

    .content {
      flex: 1;
    }
  }

  .label {
    width: 180rpx !important;

    &.long {
      // width: 300rpx !important;
    }
  }
}
.listCont {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 20rpx;
  margin-left: 10rpx;
  position: relative;
  .delete-code {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
  }
  // .u-input,
  // input {
  //   margin-right: 10rpx;
  //   border: 1px solid rgb(229, 229, 229);
  //   width: 40%;
  //   height: 10rpx !important;
  // }

  .item {
    width: 50%;
    font-size: 28rpx;
    margin-bottom: 20rpx;
    // 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: 24rpx !important;
    }
    &:nth-of-type(2n) {
      width: 50%;
    }

    text.label {
      width: 100rpx;
      display: inline-block;
      text-align: right;
      margin-right: 20rpx;
    }
    /deep/.uni-date__x-input {
      height: 40rpx;
      flex: 1;
    }
    /deep/.uni-date {
      width: 100%;
      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>
