<template>
  <div>
    <el-form label-position="right" label-width="140px" :model="addForm" :rules="rules"
             :ref="(el) => dataFormRef = el" v-loading="formLoding" :inline-message="true">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>
        <div>
          <el-form-item label="备货单号" prop="applyNo" v-if="typeOption !== 'add'">
            <el-input maxlength="60" v-trim clearable v-model="addForm.applyNo" :disabled="true"/>
          </el-form-item>
          <el-form-item label="入库仓库名称" prop="storeCode">
            <el-select clearable v-model="addForm.storeCode" placeholder="请选择仓库名称"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">
              <el-option v-for="item in interfaceLowerListArr" :key="item.code" :label="item.name"
                         :value="item.code"/>
            </el-select>
          </el-form-item>
          <el-form-item label="产权" prop="ownType">
            <el-select clearable v-model="addForm.ownType" placeholder="请选择产权"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">
              <el-option v-for="item in OWN_TYPE" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="入库设备类型" prop="inventoryType">
            <el-select clearable v-model="addForm.inventoryType" placeholder="请选择入库设备类型"
                       :disabled="typeOption === 'view' || typeOption === 'sure'" @change="changeDeviceType">
              <el-option v-for="item in deviceTypeList" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号" prop="version">
            <el-select clearable v-model="addForm.version" placeholder="请选择设备型号"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">

              <el-option v-if="addForm.inventoryType === 'CARD'" v-for="item in cardDeviceVersion"
                         :key="item.value" :label="item.label" :value="item.value"/>
              <el-option v-if="addForm.inventoryType === 'OBU'" v-for="item in obuDeviceVersion"
                         :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="采购厂商" prop="brand">
            <el-select clearable v-model="addForm.brand" placeholder="请选择设备厂商"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">

              <el-option v-if="addForm.inventoryType === 'OBU'" v-for="item in manufacturerList"
                         :key="item?.value" :label="item.label" :value="item.value"/>
              <el-option v-if="addForm.inventoryType === 'CARD'" v-for="item in cardManufacturerList"
                         :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item label="签类型" prop="obuType" v-if="addForm.inventoryType === 'OBU'">
            <el-select clearable v-model="addForm.obuType" placeholder="请选择签类型"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">
              <el-option v-for="item in obuType" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>

          <el-form-item label="卡种" prop="cardType" v-if="addForm.inventoryType === 'CARD'">

            <el-select clearable v-model="addForm.cardType" placeholder="请选择卡类型"
                       :disabled="typeOption === 'view' || typeOption === 'sure'">
              <el-option v-for="item in cardType" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>设备明细</span>
            <el-upload style="display: inline-block; margin-left: 20px" ref="upload"
                       v-if="typeOption === 'add' || typeOption === 'edit'" :on-exceed="handleExceed"
                       :before-upload="beforeAvatarUpload" :data="data" :action="uploadUrl"
                       @success="onSuccess($event)" accept=".xlsx" :limit="1" :multiple="false"
                       :show-file-list="false">
              <el-button type="primary">导入备货号段</el-button>
            </el-upload>
            <el-button v-if="typeOption === 'add' || typeOption === 'edit'"
                       style="display: inline-block; margin-left: 20px" type="primary"
                       @click="templateDownload">下载模板
            </el-button>
          </div>
        </template>
        <div>
          <el-table :data="addForm.detailList" :border="true" show-summary :span-method="arraySpanMethod"
                    :ref="(el) => tableListRef = el" :summary-method="getSummaries">
            <el-table-column type="index" header-align="center" align="center" width="60"></el-table-column>
            <el-table-column label="起始号段">
              <template v-slot="scope">
                <div class="input-wrap">
                  <el-form-item label="" :prop="`startId-${scope.$index}-${scope.row.startId}`"
                                label-width="0px" style="width: 100%" :rules="{
                                            validator: validateStartId,
                                            trigger: 'blur',
                                            required: true,
                                        }">
                    <el-input maxlength="60" v-trim clearable v-model="scope.row.startId"
                              placeholder="请输入起始号段"
                              :disabled="typeOption === 'view' || typeOption === 'sure'"
                              @input="handleApplyCount(scope.row, scope.$index)"/>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="结束号段">
              <template v-slot="scope">
                <div class="input-wrap">
                  <el-form-item label="" :prop="`endId-${scope.$index}-${scope.row.endId}`"
                                label-width="0px" style="width: 100%" :rules="{
                                            validator: validateEndId,
                                            trigger: 'blur',
                                            required: true,
                                        }">
                    <el-input maxlength="60" v-trim clearable v-model="scope.row.endId"
                              placeholder="请输入结束号段"
                              :disabled="typeOption === 'view' || typeOption === 'sure'"
                              @input="handleApplyCount(scope.row, scope.$index)"/>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <!-- addForm.deviceType === 'OBU' addForm.obuType === 'SINGLE_CHIP'-->
            <!-- <el-table-column label="到期时间" width="200">
                <template v-slot="scope"> -->
            <!-- <el-select clearable  v-model="scope.row.warranty" style="width: 100%" placeholder="请选择设备质保期"
                        :disabled="typeOption === 'view' || typeOption === 'sure'">
                        <el-option v-for="item in warrantyList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select> -->
            <!-- <el-date-picker unlink-panels v-model="scope.row.warranty" type="date"
                        placeholder="请选择到期时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        style="width: 100%" /> -->
            <!-- </template>
            </el-table-column> -->
            <el-table-column label="操作" width="340" v-if="typeOption === 'add' || typeOption === 'edit'">
              <template v-slot="scope">
                <el-button class="op-btn" type="primary"
                           @click="validHandle(scope.row, scope.$index)">校验
                </el-button>
                <el-button class="op-btn" type="danger" v-if="scope.$index > 0"
                           @click="deleteHandle(scope.row, scope.$index)">删除
                </el-button>
                <el-button class="op-btn" type="success"
                           v-if="scope.$index === (addForm.detailList.length - 1)"
                           @click="addMoreHandle(scope.row)">继续添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

    </el-form>
    <div class="btn-wrap">
      <el-button type="primary" @click="backHandle">关闭</el-button>
      <el-button type="primary" v-if="typeOption === 'add' || typeOption === 'edit'" @click="saveHandle"
                 v-loading="btnLoding">备货保存
      </el-button>
      <el-button type="primary" v-if="typeOption === 'sure'" @click="sureHandle"
                 v-loading="btnLoding">确认入库
      </el-button>
    </div>
  </div>
</template>
<script setup lang='ts'>
import {reactive, ref, toRaw, getCurrentInstance, onMounted, toRefs, nextTick, computed} from 'vue'
import {ElNotification, ElMessage, UploadInstance, UploadProps, UploadRawFile, genFileId} from "element-plus";
import {IObject} from "@/types/interface";
import {useDebounce, getDictLabel, isNumber, treeDataTranslate, bigNumSub, bigNumAdd} from "@/utils/utils";
import {cloneDeep} from "lodash"
import BaseService from "@/utils/baseService";
import {
  getInfoApi,
  sureApi,
  checkNumApi,
  checkNumDetailApi,
  addApi,
  updateApi,
  lowerListApi,
  agencyApi,
  importReturnApi
} from "@/api/inventoryControl/putInstorage";
import $storeinitData from "@/store/initData"; //引入tab vuex
// 声明事件
const emit = defineEmits([
  "closeHandle",
  "refreshDataList"
])
const handleChange = (value) => {
}

const uploadUrl = "/minIo/upload"
const data = {bucket: ""};
const upload = ref<UploadInstance>()
const dataFormRef = ref();
const tableListRef = ref();
const formLoding = ref(false);
const active = ref(1);
const typeOption = ref(""); // 是新增还是修改
const dateValue = ref();
const initForm = {
  id: "",
  storeId: "",
  inventoryType: "",
  version: "",
  applyId: "",
  brand: "",
  detailList: [
    {
      startId: "",
      endId: "",
      // warranty: "",
      count: 0,
      isShowBtn: false,
      failTotal: 0,
      successTotal: 0,
      total: 0
    }
  ]
}
const templateDownload = () => {
  let url = import.meta.env.VITE_APP_UPLOAD_URL + 'zhywpt-issuer/template/invw/设备备货号段导入模板.xlsx';
  console.log(url, 'bizContent.exportExcelUrlbizContent.exportExcelUrl')
  BaseService.getDownload(url, '设备备货号段导入模板')
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'application/vnd.android.package-archive') {
  //     ElMessage.error('请上传正确的应用文件')
  //     return false
  // } else if (rawFile.size / 1024 / 1024 > 200) {
  //     ElMessage.error('文件大小不能超过 200MB!')
  //     return false
  // }
  return true
}
const state = reactive({
  btnLoding: false,
  addForm: cloneDeep(initForm),
  warrantyList: [] as IObject[],
  allList: [] as IObject[],
  treeData: [] as IObject[],
  summary: false
})
const interfaceLowerListArr = ref([]);
const interfaceAgencyArr = ref([]);
const deviceTypeList = computed(() => {
  // return $storeinitData.state.dictData['DEVICE_TYPE'] || [];
  return $storeinitData.state.dictData['INVENTORY_TYPE'] || [];
})
const OWN_TYPE = computed(() => {
  return $storeinitData.state.dictData['OWN_TYPE'] || [];
})
const cardDeviceVersion = computed(() => {
  return $storeinitData.state.dictData['DEVICE_VERSION'] || [];
})
const obuDeviceVersion = computed(() => {
  return $storeinitData.state.dictData['DEVICE_VERSION'] || [];
  // return $storeinitData.state.dictData['DEVICE_VERSION_OBU'] || [];
})

const deviceModelList = computed(() => {
  return $storeinitData.state.dictData['UNIT_TYPE'] || [];
})
const manufacturerList = computed(() => {
  // return $storeinitData.state.dictData['EQUIPMENT_MANUFACTURER_TYPE'] || [];
  return $storeinitData.state.dictData['OBU_BRAND'] || [];
})
const cardManufacturerList = computed(() => {
  // return $storeinitData.state.dictData['CARD_EQUIPMENT_MANUFACTURER_TYPE'] || [];
  return $storeinitData.state.dictData['CARD_BRAND'] || [];
})

const cardType = computed(() => {
  return $storeinitData.state.dictData['CARD_TYPE'] || [];
})
const obuType = computed(() => {
  return $storeinitData.state.dictData['OBU_TYPE'] || [];
})
const {addForm, warrantyList, allList, treeData, btnLoding, summary}: any = toRefs(state)
const rules = reactive({
  storeCode: [{required: true, message: "请选择入库仓库", trigger: "blur"}],
  ownType: [{required: true, message: "请选择产权", trigger: "blur"}],
  version: [{required: true, message: "请选择设备型号", trigger: "blur"}],
  inventoryType: [{required: true, message: "请选择设备类型", trigger: "blur"}],
  brand: [{required: true, message: "请选择设备厂商", trigger: "blur"}],
})
const props2 = {
  value: "code",
  label: "name",
  children: "subordinateModel",
  // multiple: true,
  checkStrictly: true,
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()

}

function changeDeviceType() {
  addForm.value.version = ''
  addForm.value.brand = ''
}

// 初始化
function init(row: any) {
  getLowerList();
  // getAgency();
  clearData();
  warrantyList.value = [
    {
      label: "一年质保期",
      value: "1年"
    },
    {
      label: "两年质保期",
      value: "2年"
    },
    {
      label: "三年质保期",
      value: "3年"
    },
    {
      label: "四年质保期",
      value: "4年"
    },
    {
      label: "五年质保期",
      value: "5年"
    }
  ]
  if (row && row.id) {
    getInfo(row.id)
  }
}

// 获取详情
function getInfo(id: string) {
  formLoding.value = true;
  ///invw/inventory/inventorydetailbyid
  BaseService.postN('/invw/api/enterApply/view', {id: id}).then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.enterApply || {};
      let detailList = bizContent.applyDetailsList || [];
      let list: any = [];
      detailList.map((item) => {
        let start = item.startId.slice(3);
        let end = item.endId.slice(3);
        let num = parseInt(end) - parseInt(start) + 1;
        list.push(
            {
              ...item,
              count: num,
              isShowBtn: true,
              failTotal: 0,
              successTotal: 0,
              total: 0
            }
        )
      })
      addForm.value = {
        ...data,
        detailList: list
      }
      //addForm.value.detailList = list;
      formLoding.value = false;
    } else {
      formLoding.value = false;
      ElMessage.error(res.message)
    }
  })
}

function onSuccess(response: any) {
  console.log(response)
  BaseService.postN('/invw/api/enterApply/parseExcel', {excelUrl: response.data.ossFilePath}).then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data;
      // console.log(bizContent)
      let info = bizContent.modelList || "";
      let data = bizContent.modelList
      let newarr: any = []
      data.forEach((column, index) => {

        return newarr.push(
            {
              startId: column.startId,
              endId: column.endId,
              count: column.endId - column.startId,
              isShowBtn: false
            }
        );
      })
      addForm.value.detailList = newarr;
      //进行排序
      startIdSort();
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
    }

  })
}

//号段排序，空格排到最后
function startIdSort() {
  addForm.value.detailList = addForm.value.detailList.sort((a, b) => {
    const isAEmpty = a.startId === "" || a.startId === undefined || a.startId === null;
    const isBEmpty = b.startId === "" || b.startId === undefined || b.startId === null;
    if (isAEmpty && !isBEmpty) return 1;  // a是空，b不是，a排在后面
    if (!isAEmpty && isBEmpty) return -1; // a不是空，b是空，a排在前面
    return a.startId - b.startId;         // 正常比较startId
  });
}

// 初始化还原数据
function clearData() {
  addForm.value = cloneDeep(initForm);
  allList.value = [];
  treeData.value = [];
}

function backHandle() {
  clearData();
  emit("closeHandle");
}

function validHandle(row: IObject, index) {
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    let params: any = {
      startId: row.startId,
      endId: row.endId,
      cardType: addForm.value.cardType,
      obuType: addForm.value.obuType,
      inventoryType: addForm.value.inventoryType,
    }
    if (row.id) {
      params.detailId = row.id;
    }
    ///invw/inventory/checkinventorysegment
    BaseService.postN('/invw/api/enterApply/codeValid', params).then((res: any) => {
      if (res && res.code === 0) {
        // let bizContent = res.data
        // let data = {
        //      failTotal: bizContent.failTotal,
        //      successTotal: bizContent.successTotal,
        //      total: bizContent.total,
        // }
        // summary.value = true;
        // addForm.value.detailList[index] = {
        //     ...addForm.value.detailList[index],
        //     isShowBtn: true,
        //     failTotal: bizContent.failTotal,
        //     successTotal: bizContent.successTotal,
        //     total: bizContent.total,
        // }
        // let msg = `${bizContent.info}, 总数:${bizContent.total},成功:${bizContent.successTotal},失败:${bizContent.failTotal}`
        ElMessage.success(res.message);
      } else {
        addForm.value.detailList[index].isShowBtn = true;
        ElMessage.error(res.message)
      }
    })
  })

}

function validDetailHandle(row: IObject) {
  let params: any = {
    startId: row.startId,
    endId: row.endId
  }
  if (row.applyId) {
    params.applyId = row.applyId;
  }
  if (row.id) {
    params.detailId = row.id;
  }
  BaseService.postN('/invw/inventory/checkinventorysegmentdetail', params).then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let url = bizContent.url || "";
      let fileName = bizContent.fileName ? `${bizContent.fileName}` : '校验结果明细'
      if (url) {
        // window.open(import.meta.env.VITE_APP_UPLOAD_URL+url);
        BaseService.getDownload(import.meta.env.VITE_APP_UPLOAD_URL + url, fileName);
      } else {
        ElMessage.error("未返回文件地址");
      }

    } else {
      ElMessage.error(res.message)
    }
  })


}

function deleteHandle(row: IObject, index: number) {
  let list = [...addForm.value.detailList];
  list.splice(index, 1);
  addForm.value.detailList = list;
}

// 继续添加
function addMoreHandle(row: IObject) {
  addForm.value.detailList.push({
    startId: "",
    endId: "",
    // warranty: "",
    count: 0,
    isShowBtn: false,
    failTotal: 0,
    successTotal: 0,
    total: 0
  });
}

// 校验起始编号
function validateStartId(
    rule: any,
    value: string,
    callback: (e?: Error) => any
) {
  let inventoryType = addForm.value.inventoryType;
  let indexArr = rule.field.split("-");
  let index = indexArr[1];
  let val = indexArr[2];
  if (!isNumber(val)) {
    return callback(new Error("必须是数字!"));
  }
  let length = val.length;
  //长度校验
  if (inventoryType === "CARD" && length !== 20) {
    return callback(new Error("卡编号位数是20!"));
  } else if (inventoryType === "OBU" && length !== 16) {
    return callback(new Error("OBU编号位数是16!"));
  }
  //进行排序
  startIdSort();
  // 开始编号不能大于结束编号校验
  if (
      val &&
      addForm.value.detailList[index].endId &&
      BigInt(val) > BigInt(addForm.value.detailList[index].endId)
  ) {
    return callback(new Error("开始编号不能大于结束编号"));
  }
  if (
      val && index>0 &&
      addForm.value.detailList[index-1].endId &&
      BigInt(val) <= BigInt(addForm.value.detailList[index-1].endId)
  ) {
    return callback(new Error("开始编号要大于上一段的结束编号"));
  }
  callback();
}

// 校验结束编号
//编号规则。设备类型是卡的话，位数是20位 设备类型是OBU的话，位数的16位
function validateEndId(rule: any, value: string, callback: (e?: Error) => any) {
  let inventoryType = addForm.value.inventoryType;
  let indexArr = rule.field.split("-");
  let index = indexArr[1];
  let val = indexArr[2];
  if (!isNumber(val)) {
    return callback(new Error("必须是数字!"));
  }
  let length = val.length;
  if (inventoryType === "CARD" && length !== 20) {
    return callback(new Error("卡编号位数是20!"));
  } else if (inventoryType === "OBU" && length !== 16) {
    return callback(new Error("OBU编号位数是16!"));
  }

  if (
      val &&
      addForm.value.detailList[index].startId &&
      BigInt(val) < (addForm.value.detailList[index].startId)
  ) {
    return callback(new Error("结束编号不能小于开始编号"));
  }
  callback();
}

// 导出
function exportHandle(list: IObject[]) {
  let header: string[] = [
    "序号",
    "申请单编号",
    "起始编号",
    "结束编号",
    "入库结果",
    "失败原因",
    "重复编号列表",
  ];
  const resultString = {
    ALL_SUCCESS: "全部成功",
    PART_SUCESS: "部分成功",
    ALL_FAIL: "全部失败"
  }
  let data: any = [];
  let countMony = 0;
  let num = 0;

  list.map((item, index) => {
    let value: any = [];
    value.push(index + 1);
    value.push(item.applyId);
    value.push(item.startId);
    value.push(item.endId);
    value.push(item.result ? resultString[item.result] : '');
    value.push(item.failReason);
    value.push(item.duplicatedIds);
    data.push(value);
  });
  import("@/utils/Export2Excel").then((excel) => {
    //保存excel
    excel.export_json_to_excel({
      header: header,
      data,
      //导出的文件名
      filename: "入库结果",
    });
  });
  btnLoding.value = false;
}

// 备货保存
function saveHandle() {
  btnLoding.value = true;
  if (typeOption.value === "add") {
    if (addForm.value.storeCode !== undefined && addForm.value.storeCode !== null && addForm.value.storeCode.length !== 0) {
      addForm.value.storeCode = addForm.value.storeCode[addForm.value.storeCode.length - 1]
    }
  }
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      btnLoding.value = false;
      return false;
    }
    let params: any = {
      ...addForm.value
    }
    let list: any = [];
    // 过滤掉仅前端展示的参数和计算的参数。再提交
    const keys = ["isShowBtn", "failTotal", "total", "successTotal", "count"]
    params.detailList.map((item) => {
      let tem = {};
      for (let key in item) {
        if (keys.indexOf(key) < 0) {
          tem[key] = item[key]
        }
      }
      list.push(tem);
    })

    let params2 = {}
    params2.enterApplyDetailModels = list;
    params2.brand = params.brand;
    params2.inventoryType = params.inventoryType;
    params2.ownType = params.ownType;
    params2.storeCode = params.storeCode;
    params2.agencyId = interfaceLowerListArr.value.find(item => item.code === params.storeCode).agencyId;
    params2.version = params.version;
    params2.cardType = params.cardType;
    params2.obuType = params.obuType;
    // let api = '/invw/inventory/addinventoryapply';
    let api = '/invw/api/enterApply/apply';
    if (typeOption.value === 'add') {
      delete params2.id
    }
    if (typeOption.value === 'edit') {
      params2.id = params.id
      api = '/invw/api/enterApply/update';
    }
    BaseService.postN(api, params2).then((res: any) => {
      if (res && res.code === 0) {
        btnLoding.value = false;
        clearData();
        emit("refreshDataList");
        emit("closeHandle");
        ElMessage.success("备货保存成功");
      } else {
        btnLoding.value = false;
        ElMessage.error(res.message);
      }
    })
  })

}

// 确认入库
function sureHandle() {
  btnLoding.value = true;
  if (addForm.value.id) {
    let params = {
      id: addForm.value.id
    }
    ///invw/inventory/inventoryinstorage
    BaseService.postN('/invw/api/enterApply/confirm', params).then((res: any) => {
      if (res && res.code === 0) {
        // let bizContent = res.data
        // let url = bizContent.url || "";
        // let fileName = bizContent.fileName ? `${bizContent.fileName}` : '初始设备入库明细'
        // if (url) {
        //     //window.open(url)
        //     //处理下载有文件名
        //     BaseService.getDownloadFileName(import.meta.env.VITE_APP_UPLOAD_URL + url, fileName)
        //     btnLoding.value = false;
        //     clearData();
        //     emit("refreshDataList");
        //     emit("closeHandle");
        //     ElMessage.success("确认入库成功");
        // } else {
        //     ElMessage.error("入库成功文件未返回");
        // }
        btnLoding.value = false;
        clearData();
        emit("refreshDataList");
        emit("closeHandle");
        ElMessage.success(res.message);
      } else {
        btnLoding.value = false;
        ElMessage.error(res.message);
      }
    })
  }
}

// 计算conut
function handleApplyCount(row: IObject, index) {
  let startId = row.startId;
  let endId = row.endId;
  let inventoryType = addForm.value.inventoryType;
  let num = 0;
  if (inventoryType === 'CARD' && startId && endId) {
    // let start = startId.toString().slice(3);
    // let end = endId.toString().slice(3);
    // num = parseInt(end) - parseInt(start) + 1;
    let start: any = startId.toString().slice(3);
    let end: any = endId.toString().slice(3);
    let tem = bigNumSub(end, start);
    num = bigNumAdd(tem, '1');
  } else if (inventoryType === 'OBU' && startId && endId) {
    //num = parseInt(endId) - parseInt(startId) + 1;
    let tem = bigNumSub(endId, startId);
    num = bigNumAdd(tem, '1');
  }
  //解决合计刷新
  let receiveVoValue = cloneDeep(addForm.value.detailList);
  receiveVoValue[index].count = num;
  addForm.value.detailList = receiveVoValue;

}

// 合并合计行
function arraySpanMethod({row, column, rowIndex, columnIndex}) {
  //table合计行合并单元格
  nextTick(() => {
    if (tableListRef.value.$el) {
      let current = tableListRef.value.$el
          .querySelector('.el-table__footer-wrapper')
          .querySelector('.el-table__footer')
      let cell = current.rows[0].cells
      cell[1].colSpan = '4'
    }
  })
}

// 合计行计算
function getSummaries(param) {
  //table自定义合计行方法summary-method
  const {columns, data} = param;
  const sums: any = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return
    }
    if (index === 2) {
      const values = data.map((item) => Number(item.count));
      sums[1] = values.reduce((prev, curr) => {
        return prev + curr
      }, 0)
      sums[1] = sums[1]
    }
  })
  // let str = "";
  // if (sums[1]) {
  //     str = `共${data.length}号段,${sums[1]}个设备`;
  //     if (summary.value) {
  //         console.log(data, '-----');
  //         const successTotal = data.map((item) => Number(item.successTotal));
  //         console.log(successTotal.value);
  //         console.log(4535);
  //         let totalNum = sums[1] = successTotal.reduce((prev, curr) => {
  //             return prev + curr
  //         }, 0)
  //         str = str + '已校验可入库数量' + totalNum
  //     }
  // }
  sums[1] = `共${data.length}号段,${sums[1]}个设备`;
  return sums
}

// 获取仓库状态
function getLowerList() {
  let params = {
    allType: 0
  }
  BaseService.postN('/invw/api/warehouse/getWarehouseIdNames', params).then((res: any) => {
    // console.log(res)
    if (res && res.code === 0) {
      let bizContent = res.data
      // console.log(bizContent)
      let data = bizContent.idNames || [];
      interfaceLowerListArr.value = data
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 获取仓库状态
function getAgency() {
  BaseService.postN('/invw/agency/list').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      // console.log(bizContent)
      let data = bizContent.idNames || [];
      let agencyList: any = [];
      data.map((item) => {
        // console.log(item)
        agencyList.push({
          label: item.agencyName,
          value: item.ownType
        })
      })
      interfaceAgencyArr.value = agencyList
    } else {
      ElMessage.error(res.message)
    }
  })
}

defineExpose({
  init,
  addForm,
  typeOption,
  clearData
})
</script>
<style lang='scss' scoped>
.btn-wrap {
  display: flex;
  justify-content: center;
}

.box-card {
  margin-bottom: 16px;
}

.op-btn {
  padding: 8px;
}

.input-wrap {
  display: flex;

  .el-form-item {
    margin-bottom: 0;
  }
}

.btn-read {
  margin-left: 10px;
}
</style>
