<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-row>
            <el-col :span="12" v-if="typeOption !== 'add'">
              <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-col>

            <el-col :span="12">
              <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-col>

            <el-col :span="12">
              <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-col>

            <el-col :span="12">
              <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-col>

            <el-col :span="12">
              <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-col>

            <el-col :span="12">
              <el-form-item label="申请数量" prop="applyCount">
                <el-input clearable v-model="addForm.applyCount" placeholder="请输入申请数量"
                          :disabled="typeOption === 'view' || typeOption === 'sure'"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="发货仓库" prop="sendStoreCode">
                <el-select v-model="addForm.sendStoreCode" placeholder="请选择" :disabled="typeOption === 'view' || typeOption === 'sure'"
                           @change="changeStore(1)">
                  <el-option v-for="item in props.storeList" :key="item.value" :label="item.name" :value="item.code"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="收货仓库" prop="receiveStoreCode">
                <el-select v-model="addForm.receiveStoreCode" placeholder="请选择" :disabled="typeOption === 'view' || typeOption === 'sure'">
                  <el-option v-for="item in receiveStoreList" :key="item.value" :label="item.name" :value="item.code"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="addForm.inventoryType === 'OBU'">
              <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" :disabled="typeOption === 'view' || typeOption === 'sure'"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="addForm.inventoryType === 'CARD'">
              <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" :disabled="typeOption === 'view' || typeOption === 'sure'"/>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
          <!-- filePath multiple-->
          <el-form-item label="附件">
<!--            <el-upload v-if="!(typeOption === 'view' || typeOption === 'sure')" ref="uploadRef"-->
<!--                       :data="{ busCode: 'invw' }" v-model:file-list="fileList" list-type="picture-card"-->
<!--                       :action="uploadUrl" :limit="1" :on-exceed="handleExceed" :on-success="handleSuccess"-->
<!--                       :before-upload="beforeUpload" accept="image/*,.pdf,.doc,.docx,.xls,.xlsx">-->
<!--              <el-icon><Plus/></el-icon>-->
<!--              <template #file="{ file }">-->
<!--                <div>-->
<!--                  <img v-if="file.type && file.type.includes('image')" class="el-upload-list__item-thumbnail" :src="file.url || file.raw?.url" alt=""/>-->
<!--                  <div v-else class="file-icon">-->
<!--                    <el-icon :size="30"><Document/></el-icon>-->
<!--                    <span class="file-name">{{ file.name }}</span>-->
<!--                  </div>-->
<!--                  <span class="el-upload-list__item-actions">-->
<!--                    <span class="el-upload-list__item-preview" @click="handlePreview(file)">-->
<!--                        <el-icon><zoom-in/></el-icon>-->
<!--                    </span>-->
<!--                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">-->
<!--                        <el-icon><Delete/></el-icon>-->
<!--                    </span>-->
<!--                </span>-->
<!--                </div>-->
<!--              </template>-->
<!--              <template #tip>-->
<!--                <div class="el-upload__tip">-->
<!--                  (不限于图片、文件,不超过1个)-->
<!--                </div>-->
<!--              </template>-->
<!--            </el-upload>-->

              <el-upload
                  v-if="!(typeOption === 'view' || typeOption === 'sure')" ref="uploadRef"
                  v-model:file-list="fileList"
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :limit="1"
                  :on-success="handleSuccess"
                  :on-exceed="handleExceed"
                  :before-upload="beforeUpload"
                  accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
              >
                <el-button type="primary">选择文件</el-button>
              </el-upload>

            <view v-else>
              <el-link underline :href="addForm.filePath">{{ addForm.filePath }}</el-link>
            </view>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image"/>
            </el-dialog>
          </el-form-item>
            </el-col>
          </el-row>
        </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" :disabled="typeOption === 'view' || typeOption === 'sure'">
              <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>

            <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="primary" @click="validDetailHandle(scope.row)" v-if="scope.row.isShowBtn">校验失败明细</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">调拨保存</el-button>
      <el-button type="primary" v-if="typeOption === 'sure'" @click="sureHandle">确认入库</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 {Plus, ZoomIn, Delete, Document} from '@element-plus/icons-vue'
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 URLS = import.meta.env.VITE_APP_BASE_URL;
const props = defineProps({
  storeList: {
    type: Object,
    default: {},
  },
})
// 声明事件
const emit = defineEmits([
  "closeHandle",
  "refreshDataList"
])
const handleChange = (value) => {
  // console.log(value)
}
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    fileListData.value.splice(index, 1);
    // console.log(fileListData.value, 'fileListData.valuefileListData.value')
  }
};
const beforeUpload = (file) => {
  const isImage = file.type.includes('image');
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isImage && !isLt5M) {
    ElMessage.error('文件大小不能超过5MB');
    return false;
  }
  // 可以在这里添加更多的文件类型验证   filePath
  return true;
};
const handleSuccess = (response: any) => {
  fileListData.value.push(response.data.ossFilePath)
};
const handlePreview = (file) => {
  const isImage = file.type && file.type.includes('image');
  if (isImage) {
    dialogImageUrl.value = file.url || file.raw?.url;
    dialogVisible.value = true;
  } else {
    window.open(file.url || file.raw?.url);
  }
};
const fileList = ref([])
const receiveStoreList = ref([])
const fileListData = ref([])
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) => {
  // dataFormRef.value.validate((valid) => {
  //   if (valid) {
  //     return true;
  //   }else {
  //     return false;
  //   }
  // })
}
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['OBU_BRAND'] || [];
})
const cardManufacturerList = computed(() => {
  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({
  storeCodeList: [{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"}],
  // brand: [{ required: true, message: "请选择申请单类型", trigger: "blur" }],
  receiveStoreCode: [{required: true, message: "请选择收货仓库", trigger: "blur"}],
  sendStoreCode: [{required: true, message: "请选择发货仓库", trigger: "blur"}],
  cardType: [{ required: true, message: "请选择卡类型", trigger: "blur" }],
  obuType: [{ required: true, message: "请选择签类型", trigger: "blur" }],
})
const props2 = {
  value: "code",
  label: "name",
  children: "subordinateModel",
  // multiple: true,
  checkStrictly: true,
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  if (!upload.value || files.length === 0) return;

  const file = files[0] as UploadRawFile;
  file.uid = genFileId(); // 生成唯一 ID

  upload.value.clearFiles();
  upload.value.handleStart(file);
  upload.value.submit();
}

function changeStore(flag){
  let code = addForm.value.sendStoreCode;
  if(code !== '' && code !== undefined && code !== null) {
    let params = {
      id: null,
      code: code,
      type: "5"
    }
    BaseService.postN('/invw/api/warehouse/getWarehouseIdNames', params).then((res: any) => {
      if (res && res.code === 0) {
        let bizContent = res.data
        receiveStoreList.value = bizContent.idNames
        if(flag === 1){
          addForm.value.receiveStoreCode=null;
        }
      }
    })
  }
}

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

// 初始化
function init(row: any) {
  if (row !== null) {
    idex = row.id
  }
  getLowerList();
  // getAgency();
  clearData();
  fileList.value = []
  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;
  BaseService.postN('/invw/api/transfer/detail', {id: id}).then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.transferApply || {};
      let detailList = bizContent.transferDetails || [];
      let files = [];
      files.push({url:data.filePath,name:data.filePath});
      fileList.value = files;
      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
      }
      changeStore();
      // console.log(addForm.value, '=============------------==========');

      //addForm.value.detailList = list;
      formLoding.value = false;
    } else {
      formLoding.value = false;
      ElMessage.error(res.message)
    }
  })
}

let idex = ''

function onSuccess(response: any) {
  // console.log(response)
  BaseService.postN('/invw/api/transfer/import', {fileUrl: response.data.ossFilePath}).then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data;
      let data = bizContent.transferDetails
      let newarr: any = []
      data.forEach((column, index) => {
        newarr.push(
            {
              startId: column.startId,
              endId: column.endId,
              count: column.endId - column.startId,
              isShowBtn: false
            }
        );
        nextTick(()=>{
          handleApplyCount(column,index)
        })
        return newarr
      })
      addForm.value.detailList = newarr;
      ElMessage.success("导入成功")
    } else {
      ElMessage.error(res.message)
    }
  })
}

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

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

function validHandle(row: IObject, index) {
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    BaseService.postN('/invw/api/transfer/check', {
      transferApply: {
        ...addForm.value
      },
      transferDetails: {
        startId: row.startId,
        endId: row.endId
      }
    }).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: row.count,
        //     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: "",
    count: 0,
    isShowBtn: false,
    failTotal: 0,
    successTotal: 0,
    total: 0
  });
}

// 校验结束编号
//编号规则。设备类型是卡的话，位数是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 &&
      val < addForm.value.detailList[index].startId
  ) {
    return callback(new Error("结束编号不能小于开始编号"));
  }
  // 列表中不能重复校验
  let endIds = addForm.value.detailList.filter((item) => item.endId === val);
  if (endIds.length > 1) {
    callback(new Error("请检查，结束编号有重复"));
  }
  callback();
}

// 校验开始编号
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!"));
  }
  // 开始编号不能大于结束编号校验
  if (
      val &&
      addForm.value.detailList[index].endId &&
      val > addForm.value.detailList[index].endId
  ) {
    return callback(new Error("开始编号不能大于结束编号"));
  }
  // 列表中不能重复校验
  let startIds = addForm.value.detailList.filter((item) => item.startId === val);
  if (startIds.length > 1) {
    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.storeCodeList !== undefined && addForm.value.storeCodeList !== null && addForm.value.storeCodeList.length !== 0) {
      addForm.value.storeCode = addForm.value.storeCodeList[addForm.value.storeCodeList.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);
    })
    // console.log(params);

    let params2 = {}
    params2.brand = params.brand;
    params2.inventoryType = params.inventoryType;
    params2.ownType = params.ownType;
    params2.receiveStoreCode = Array.isArray(params.receiveStoreCode) ? params.receiveStoreCode[0] : params.receiveStoreCode;
    params2.sendStoreCode = Array.isArray(params.sendStoreCode) ? params.sendStoreCode[0] : params.sendStoreCode;
    params2.version = params.version;
    params2.cardType = params.cardType;
    params2.obuType = params.obuType;
    params2.filePath = fileListData.value[0];
    let api = '/invw/api/transfer/add';
    // console.log("typeOption.value", typeOption.value)
    if (typeOption.value === 'add') {
      delete params2.id
    }
    if (typeOption.value === 'edit') {
      params2.id = idex
      api = '/invw/api/transfer/edit';
    }
    BaseService.postN(api, {
      transferApply: params2,
      transferDetails: list
    }).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() {
  // console.log(addForm.value, idex);
  if (idex) {
    let params = {
      id: idex
    }
    btnLoding.value = true;
    BaseService.postN('/invw/api/transfer/confirmIn', params).then((res: any) => {
      if (res && res.code === 0) {
        btnLoding.value = false;
        emit("refreshDataList");
        emit("closeHandle");
        ElMessage.success("确认入库成功");
        clearData();
      } else {
        btnLoding.value = false;
        ElMessage.error(res.message);
      }
    })
  }
}

// 计算conut
function handleApplyCount(row: IObject, index) {
  if(row.startId.length == row.endId.length && (row.startId.length == 20 || row.startId.length == 16)) {
    let startId = row.startId;
    let endId = row.endId;
    let num = 0;
    if (startId && endId) {
      let start: any = startId.toString();
      let end: any = endId.toString();
      let tem = bigNumSub(end, start);
      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
  // console.log("====>",param)
  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, '-----');
      // 计算 successTotal 总和（自动过滤无效值）
      const totalNum = data.reduce((sum, item) => {
        const num = Number(item.successTotal);
        return sum + (isNaN(num) ? 0 : num);
      }, 0);

      // 更新 sums 和字符串（避免直接修改外部变量）
      sums[1] = totalNum;
      str = str + ',已校验可入库数量' + totalNum
    }
  }
  sums[1] = str;
  return sums
}

// 获取仓库状态
function getLowerList() {
  // console.log("获取仓库列表")
  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
    }
  })
}

// 获取仓库状态
function getAgency() {
  // console.log("获取产权列表")
  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>
