<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="入库单" prop="queryParams.params">
              <el-Input v-model="state.queryParams.params.RECEIVEREQUESTNAME" placeholder="到货单"
                @keydown.enter.prevent="handleQuery" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <span>入库单详细信息</span>
        </div>
      </div>
      <el-table border v-loading="loading" :data="state.MATERIALRECEIVEACT" highlight-current-row row-key="id"
      style="width: 100%;min-height:100px;height:260px" @row-click="handle">
        <!--        <el-table-column prop="MATERIALPACKINGNAME" label="标签" fixed="left" width="180" ></el-table-column>-->
        <!--        <el-table-column prop="CHARGE" label="批次" fixed="left" width="180"></el-table-column>-->
        <el-table-column prop="MATERIALSPECNAME" fixed="left" label="料号" width="100"></el-table-column>
        <el-table-column prop="DESC_CN" label="品名" width="280"></el-table-column>
        <el-table-column prop="DESCRIPTION" label="物料规格" width="100"></el-table-column>
        <el-table-column prop="SDK_ID" label="斯迪克规格ID" v-if=false width="80"></el-table-column>
        <el-table-column prop="SPECNAME" label="斯迪克规格" width="100"></el-table-column>
        <el-table-column prop="PHASE" label="阶段" width="80"></el-table-column>
        <el-table-column prop="ERPFACTORY" label="组织" width="100"></el-table-column>
        <!-- <el-table-column prop="ERPFACTROYDESC" label="组织(CN)" width="180"></el-table-column>-->
        <el-table-column prop="ERPLOCATION" label="库位" width="180">
          <template #default="scope">
            <el-select  v-model="scope.row.ERPLOCATION" placeholder="选择仓库" style="width: 170px" default-first-option
              @focus="getStorageSpec(scope.row.ERPLOCATION)" filterable>
              <el-option v-for="item in state.ERPLocationList" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="ERPLOCATIONDESC" label="库位(CN)" width="180"></el-table-column>-->
<!--        <el-table-column prop="LOCATIONNAME" label="货位" width="180">-->
<!--          <template #default="scope">-->
<!--            <el-select v-model="scope.row.LOCATIONNAME" placeholder="选择库位" style="width: 170px"-->
<!--                       @focus="getStorageSpec(scope.row.ERPLOCATION)" default-first-option filterable-->
<!--                       :filter-method="locatioNFilter">-->
<!--              <el-option v-for="item in state.LocationList" :key="item.VALUE" :label="item.LABEL"-->
<!--                :value="item.VALUE" />-->
<!--            </el-select>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <!-- <el-table-column prop="LOCATIONNAMEDESC" label="货位(CN)" width="180"></el-table-column>-->
        <el-table-column prop="REQUESTQUANTITY" label="订单数量" width="100"></el-table-column>
        <el-table-column prop="RECEIVEDQUANTITY" label="已接收数量" width="100"></el-table-column>
        <el-table-column prop="STOCKINQTY" label="已入库数量" width="100"></el-table-column>
        <el-table-column prop="CREATEQTY" label="本次创建数量" width="100"></el-table-column>
        <el-table-column prop="MINUSQTY" label="剩余数量" width="100"></el-table-column>
        <el-table-column prop="MAKEDATE" label="生产日期" width="120">
          <template #default="scope">
            <el-date-picker v-model="scope.row['MAKEDATE']" type="date" style="width: 110px" placeholder="请选择时间"
              :size="'small'" v-if="scope.row['REPLACED_VALUE'] != '未定义'" />
          </template>
        </el-table-column>
<!--        <el-table-column prop="RECEIVETIME" label="接收日期" width="100"></el-table-column>-->
        <el-table-column prop="RECEIVETIME" label="接收日期" width="120">
          <template #default="scope">
            <el-date-picker v-model="scope.row['RECEIVETIME']" type="date" style="width: 110px" placeholder="请选择时间"
                            :size="'small'" v-if="scope.row['REPLACED_VALUE'] != '未定义'" />
          </template>
        </el-table-column>

        <el-table-column prop="MATERIALUNITDESC" label="单位" width="50"></el-table-column>
        <el-table-column prop="FUNIT" label="辅助单位"  v-if=false width="50"></el-table-column>
        <el-table-column prop="FUNITDESC" label="辅助单位" width="50"></el-table-column>
        <el-table-column prop="UNIT_RATES" label="换算率" width="50"></el-table-column>
        <el-table-column prop="IS_BATCH" label="启用批次" width="80"></el-table-column>
        <el-table-column prop="IQCFLAG" label="启用质检" width="80"></el-table-column>
        <el-table-column prop="REPLACED_VALUE" label="有效期管理方式" width="150"></el-table-column>
        <el-table-column prop="SUPPLIERNO" label="供应商"  width="180"></el-table-column>
        <el-table-column prop="REMARK" label="备注"  width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button @click="createBox(scope.row)" type="text" size="small">创建批次</el-button>
            <el-button @click="deleteBox(scope.row)" type="text" size="small">删除批次</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <span>批次信息</span>
        </div>
      </div>
      <el-table :height="tableHeight" style="width: 100%;min-height:100px;" :data="state.MATERIALPACKINGLIST" border show-summary>
        <el-table-column prop="SEQ" label="序号" fixed="left" width="100"></el-table-column>
        <el-table-column prop="RECEIVEREQUESTNAME" label="单号" width="120"></el-table-column>
        <el-table-column prop="MATERIALPACKINGNAME" label="标签" fixed="left" v-if=false width="180"></el-table-column>
        <el-table-column prop="CHARGE" label="批次" fixed="left" width="180"></el-table-column>
        <el-table-column prop="MATERIALSPECNAME" fixed="left" label="料号" width="180"></el-table-column>
        <el-table-column prop="DESC_CN" label="品名" width="280"></el-table-column>
        <el-table-column prop="DESCRIPTION" label="物料规格" width="180"></el-table-column>
        <el-table-column prop="TRUEGG" label="实际规格" width="150"></el-table-column>
        <el-table-column prop="SDK_ID" label="斯迪克规格ID" v-if=false width="80"></el-table-column>
        <el-table-column prop="SPECNAME" label="斯迪克规格" width="180"></el-table-column>
        <el-table-column prop="PHASE" label="阶段" width="80"></el-table-column>
        <el-table-column prop="ERPFACTROY" label="组织" v-if=false width="180"></el-table-column>
        <el-table-column prop="ERPFACTROYDESC" label="组织(CN)" width="220"></el-table-column>
        <el-table-column prop="ERPLOCATION" label="库位" v-if=false width="180"></el-table-column>
        <el-table-column prop="ERPLOCATIONDESC" label="库位(CN)" width="180"></el-table-column>
        <el-table-column prop="LOCATIONNAME" label="货位" v-if=false width="180"></el-table-column>
        <el-table-column prop="LOCATIONNAMEDESC" label="货位(CN)" width="180"></el-table-column>
        <el-table-column prop="MATERIALQUANTITY" label="数量" width="50"></el-table-column>
        <el-table-column prop="UNIT" label="单位" width="50"></el-table-column>
        <el-table-column prop="SUPPLIERNO" label="供应商"  width="180"></el-table-column>
        <el-table-column prop="REMARK" label="备注"  width="180"></el-table-column>
        <el-table-column fixed="right" label="操作"  width="180">
          <template #default="scope">
            <el-button @click="deleteThisBox(scope.row)" type="text" size="small">删除本批次</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="vue-element-page-table">
      <el-row class="page-search" justify="space-between" align="middle">
        <el-form ref="operateFormRef" :model="operateParams" :inline="true">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="选择打印机" v-model="state.PRINTNAME">
                <!--                <el-select clearable filterable v-model="state.PRINTLIST" placeholder="请选择打印机"-->
                <!--                           class="product-input">-->
                <!--                  <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL"-->
                <!--                             :value="item.VALUE" />-->
                <!--                </el-select>-->
                <el-select v-model="state.PRINTNAME" placeholder="请选择打印机" style="width: 240px">
                  <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-button type="primary" @click="print" :disabled="state.button_print" v-loading="state.loadings">打印</el-button>
            </el-col>
            <el-col :span = "4">
              <el-form-item label="过账日期" prop="state.commitDate">
                <el-date-picker :clearable="true" :editable="true" v-model="state.commitDate" type="date" placeholder="选择过账时间" value-format="YYYY-MM-DD"/>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-Input v-model="state.OpCode"  :disabled = false readonly />
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="sendToERP" :disabled="state.button_state" v-loading="state.button_loading">入库</el-button>
            </el-col>
          </el-row>
        </el-form>
<!--        <div class="demo-date-picker">-->
<!--          <div class="block">-->
<!--            <el-form-item label="过账日期" prop="state.commitDate">-->
<!--              <el-date-picker :clearable="true" :editable="true" v-model="state.commitDate" type="date" placeholder="选择过账时间" value-format="YYYY-MM-DD"/>-->
<!--            </el-form-item>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div class="page-search-btns">-->
<!--          <el-Input v-model="state.OpCode" placeholder="过账流水"/>-->
<!--          <el-button type="primary" @click="sendToERP" :disabled="state.button_state" v-loading="state.button_loading">入库</el-button>-->
<!--        </div>-->
      </el-row>
    </div>
    <div style="width: 300px">
      <el-drawer v-model="boxDrawer" title="创建标签" size="300px">
        <el-form :model="state.createBoxForm" :rules="rules" ref="state.createBoxForm">

          <el-form-item label="订单数量" prop="state.createBoxForm.REQUESTQUANTITY">
            <!--        <input v-model="state.createBoxForm.RECEIVEDQUANTITY"   />-->
            <span>{{ state.createBoxForm.REQUESTQUANTITY }}</span>
          </el-form-item>
          <el-form-item label="已收数量" prop="state.createBoxForm.RECEIVEDQUANTITY">
            <!--        <input v-model="state.createBoxForm.RECEIVEDQUANTITY"   />-->
            <span>{{ state.createBoxForm.RECEIVEDQUANTITY }}</span>
          </el-form-item>
          <el-form-item label="实收数量" prop="state.createBoxForm.RECEIVEDQUANTITY2">
            <!--        <input v-model="state.createBoxForm.RECEIVEDQUANTITY"   />-->
            <span  >{{ state.createBoxForm.RECEIVEDQUANTITY2 }}</span>
          </el-form-item>
          <el-form-item label="剩余数量" prop="state.createBoxForm.MINUSQTY">
            <!--        <input v-model="state.createBoxForm.RECEIVEDQUANTITY"   />-->
            <span>{{ state.createBoxForm.MINUSQTY }}</span>
          </el-form-item>
          <el-form-item label="实际规格" prop="state.createBoxForm.TrueGG">
            <el-Input v-model="state.createBoxForm.TrueGG" placeholder="实际规格" clearable @input="InputNumber" />
          </el-form-item>
          <el-form-item label="标签个数" prop="state.createBoxForm.MATERIALQUANTITY">
            <el-Input v-model="state.createBoxForm.MATERIALQUANTITY" placeholder="标签个数" type=number min=0 clearable
              @input="InputNumber3" />
          </el-form-item>
          <el-form-item label="单个标签物料数量" prop="state.createBoxForm.MATERIALCREATEQUANTITY">
            <el-Input v-model="state.createBoxForm.MATERIALCREATEQUANTITY" placeholder="单个标签物料数量" type=number min=0
              @input="InputNumber2" clearable />
          </el-form-item>

          <el-form-item label="辅单位" prop="funit">
            <el-select v-model="state.createBoxForm.FUNIT" placeholder="辅单位" style="width: 240px" :disabled="state.unitAble" filterable default-first-option>
              <el-option v-for="item in state.UnitList" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="转换系数" prop="state.createBoxForm.UNIT_RATES">
            <el-Input v-model="state.createBoxForm.UNIT_RATES" placeholder="转换系数" :disabled="true"
                      @keyUpEvent="handleQuery" />
          </el-form-item>
          <el-form-item label="辅数量" prop="state.createBoxForm.FQTY">
            <el-Input v-model="state.createBoxForm.FQTY" placeholder="辅数量" clearable type=number min=0
              @keyUpEvent="handleQuery" />
          </el-form-item>
          <el-form-item label="备注" prop="state.createBoxForm.Remark">
            <el-Input v-model="state.createBoxForm.Remark" placeholder="备注信息..." clearable @keyUpEvent="handleQuery" />
          </el-form-item>
          <div class="page-search-btns">
            <el-button type="primary" @click="commitBox" :disabled="state.button_state2" v-loading="state.button_loading2">提交</el-button>
          </div>

        </el-form>
      </el-drawer>
    </div>

  </div>

</template>

<script lang="ts">
export default {
  name: "StockInByCharge",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance} from "vue";
import { ElForm, ElMessageBox, ElTable, ElMessage } from "element-plus";
import { BpelEvent, getQueryList } from "@/api/common";
import { useRoute } from 'vue-router'
import { localStorage } from "@/utils/storage";
import { IFTRUE, areAllNotEmpty, msToDate } from "@/utils/CommonUtil"
import { CreateBox, DeleteTrackOutBox, PurInSendERPByCharge, DeleteTrackOutThisBox } from '@/api/StockIn'
import { getOpCode } from '@/api/opcode'
import { printLabel } from "@/api/label";
import { bTableHeight } from "../../../composables/calcTableHeight";
import { cals } from '@/utils/cal'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(530);
const drawer = ref(false)
const route = useRoute()
const queryFormRef = ref(ElForm);
const operateFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

const state = reactive({
  button_loading : false,
  button_loading2 : false,
  MATERIALPACKINGLISTS:{},
  boxDrawer: false,
  direction: 'ltr',
  rsa: "",
  loadings: false,
  button_print:false,
  disabledss: false,
  InputState: true,
  // UnitList: '',//单位列表
  RealERPLocation: [] as any,//用于存储实际查询到仓库
  RealLocation: [] as any,//用于存储实际查询到库位
  MATERIALPACKINGLIST: [] as any,
  POCreateLocationList: [] as any,
  LocationList: [] as any, //货位集合
  AllLocationList: [] as any,//所有货位集合
  UnitList: [] as any,
  ERPLocationList: [] as any,
  button_state: false,
  button_state2: false,
  MATERIALRECEIVEACT: [] as any,
  ReceiveACTList: [] as any,
  createBoxForm: {},
  unitAble : false,
  commitDate : '',
  defaultDate : '',
  PRINTLIST: [] as any,//打印机
  PRINTNAME: '',
  queryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',
      RECEIVEREQUESTNAME: "",
      MATERIALSPECNAME : ""
    },
  },
  operateParams: {
    date: new Date()
  },
  stockInloadings: true,
  loading: false,
  userList: [] as any,
  column: [] as any,
  rules: {
    MATERIALQUANTITY: [
      { required: true, message: '请输入数字', trigger: 'blur' },
      { type: 'number', message: '输入内容不是有效的数字', trigger: 'blur' }
    ],
    MATERIALCREATEQUANTITY: [
      { required: true, message: '请输入数字', trigger: 'blur' },
      { type: 'number', message: '输入内容不是有效的数字', trigger: 'blur' }
    ]
  },
  OpCode : "", //过账流水

});
onMounted(() => {
  getPRINTLIST();
});
const { MATERIALRECEIVEACT, rsa, queryParams, button_print, loading, userList, column, operateParams, boxDrawer, createBoxForm,unitAble } = toRefs(state);

onMounted(() => {
  getMaterialUnit()
  var getTime = new Date().getTime(); //获取到当前时间戳
  var time = new Date(getTime); //创建一个日期对象
  state.createBoxForm.MAKEDATE = nowDate(time)
  console.log('MAKEDATE',state.createBoxForm.MAKEDATE)
  var newDate = new Date();
  var year = newDate.getFullYear();
  var moth = newDate.getMonth() + 1;
  if(moth < 10) moth = '0' + moth;
  var day = newDate.getDate();
  if(day < 10) day = '0' + day;
  state.commitDate = year + '-' + moth + '-' + day

  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

//分子分母计算
function stringToFraction(strs :any) {
  // 检查字符串格式是否为分数形式
  const match = strs.match(/^(-?\d+(\.\d+)?)\/(-?\d+(\.\d+)?)$/);
  if (!match) {
    console.log("字符串不是有效的分数格式");
    return;
  }
  // 提取分子和分母
  const numerator = Number(match[1], 10);
  const denominator = Number(match[2], 10);

  // 返回分数对象（或你可以根据需要返回其他形式）
  return {
    numerator: numerator,
    denominator: denominator,
    // 可以添加一个方法来计算分数的值（如果需要的话）
    value: function() {
      // numerator / denominator
      return (cals.div(numerator,denominator)).toNumber();
    }
  };
}

// 辅数量更新
function updateFnumber() {
  console.log("我来了" + state.createBoxForm.UNIT_RATES)
  let fz = 0;
  let fm = 0;
  if(state.createBoxForm.UNIT_RATES !=  null && state.createBoxForm.UNIT_RATES != '') {
    const match = state.createBoxForm.UNIT_RATES.match(/^(-?\d+(\.\d+)?)\/(-?\d+(\.\d+)?)$/);
    if (!match) {
      console.log("字符串不是有效的分数格式");
      return
    }

    fz = Number(state.createBoxForm.UNIT_RATES.split("\/")[0]) //分子
    fm =  Number(state.createBoxForm.UNIT_RATES.split("\/")[1]) //分母
    console.log(fz   + "**************" + fm)

  }
  console.log(fz,fm,state.createBoxForm.MATERIALCREATEQUANTITY)

  //state.createBoxForm.FQTY = (Math.round((state.createBoxForm.MATERIALCREATEQUANTITY / (fz/fm)) * 100) / 100).toFixed(2);
  state.createBoxForm.FQTY = (cals.div(state.createBoxForm.MATERIALCREATEQUANTITY,(cals.div(fz,fm)).toNumber())).toNumber()
  
  
  // 注意：这里 .toFixed(2) 会将结果转换为字符串
// 如果你需要数字，可以去掉 .toFixed(2) 并根据需要调整 Math.round 里的乘数
  console.log("我走了" + state.createBoxForm.FQTY)
}

function getPRINTLIST() {
  getQueryList({
    queryId: "getPRINTLIST",
    version: "00001",
    params: {
    },
  }).then((res: any) => {
    state.PRINTLIST = res.data
  })
}
function InputNumber() {
  if (state.createBoxForm != 'KG') {
    let arrs2 = state.createBoxForm.TrueGG.toString().split('*');
    console.log('arrs2',arrs2)
    // arrs2[0] = parseInt(arrs2[0].replace('mm', ''), 10).toString();
    // arrs2[1] = parseInt(arrs2[1].replace('m', ''), 10).toString();
    // arrs2[0] = (parseInt(arrs2[0]) / 1000).toString();
    // state.createBoxForm.MATERIALCREATEQUANTITY = parseFloat((parseFloat(arrs2[1]) * parseFloat(arrs2[0])).toFixed(2));//单个标签数量
    //state.createBoxForm.MATERIALQUANTITY = Math.ceil(parseFloat(state.createBoxForm.RECEIVEDQUANTITY2) / state.createBoxForm.MATERIALCREATEQUANTITY)//标签个数
    arrs2[0] = arrs2[0].replace('mm', '')
    arrs2[1] = arrs2[1].replace('m', '')
    arrs2[0] = (cals.div(arrs2[0],1000)).toNumber()
    console.log('arrs',arrs2[0],arrs2[1])
    arrs2[1] = arrs2[1] ? arrs2[1] : 0;
    state.createBoxForm.MATERIALCREATEQUANTITY =(cals.mul(arrs2[1],arrs2[0])).toNumber();//单个标签数量
    let sums = (cals.div(state.createBoxForm.RECEIVEDQUANTITY2,state.createBoxForm.MATERIALCREATEQUANTITY)).toNumber();
    state.createBoxForm.MATERIALQUANTITY = Math.ceil(sums)//标签个数
    
  }
  if (Number(state.createBoxForm.MATERIALQUANTITY) >= 0) {
    // state.createBoxForm.RECEIVEDQUANTITY2 = state.createBoxForm.MATERIALCREATEQUANTITY * state.createBoxForm.MATERIALQUANTITY
    // state.createBoxForm.MINUSQTY = (state.createBoxForm.REQUESTQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY2*1000)/1000
    
    state.createBoxForm.RECEIVEDQUANTITY2 = (cals.mul(state.createBoxForm.MATERIALCREATEQUANTITY,state.createBoxForm.MATERIALQUANTITY)).toNumber() || 0;
    state.createBoxForm.MINUSQTY = (cals.subMore(state.createBoxForm.REQUESTQUANTITY,state.createBoxForm.RECEIVEDQUANTITY,state.createBoxForm.RECEIVEDQUANTITY2)).toNumber() || 0;
    updateFnumber()
  }

}
function InputNumber2() {
  /* eslint-disable */
  console.log(state.createBoxForm.MATERIALCREATEQUANTITY,state.createBoxForm.MATERIALQUANTITY)
  if (Number(state.createBoxForm.MATERIALCREATEQUANTITY) >= 0) {
    // state.createBoxForm.RECEIVEDQUANTITY2 = (state.createBoxForm.MATERIALCREATEQUANTITY * 1000) * (state.createBoxForm.MATERIALQUANTITY * 1000) / 1000000
    // state.createBoxForm.MINUSQTY = (state.createBoxForm.REQUESTQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY2*1000)/1000
    
    state.createBoxForm.RECEIVEDQUANTITY2 =(cals.mul(state.createBoxForm.MATERIALCREATEQUANTITY,state.createBoxForm.MATERIALQUANTITY)).toNumber();
    state.createBoxForm.MINUSQTY = (cals.subMore(state.createBoxForm.REQUESTQUANTITY,state.createBoxForm.RECEIVEDQUANTITY,state.createBoxForm.RECEIVEDQUANTITY2)).toNumber();
    updateFnumber()
  }
}

function InputNumber3() {
  if (Number(state.createBoxForm.MATERIALQUANTITY) >= 0) {
    console.log(state.createBoxForm.MATERIALCREATEQUANTITY, state.createBoxForm.MATERIALQUANTITY)
    // state.createBoxForm.RECEIVEDQUANTITY2 = (state.createBoxForm.MATERIALCREATEQUANTITY * 1000) * (state.createBoxForm.MATERIALQUANTITY * 1000) / 1000000
    // state.createBoxForm.MINUSQTY = (state.createBoxForm.REQUESTQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY*1000 - state.createBoxForm.RECEIVEDQUANTITY2*1000)/1000
    
    state.createBoxForm.RECEIVEDQUANTITY2 =(cals.mul(state.createBoxForm.MATERIALCREATEQUANTITY,state.createBoxForm.MATERIALQUANTITY)).toNumber();
    state.createBoxForm.MINUSQTY = (cals.subMore(state.createBoxForm.REQUESTQUANTITY,state.createBoxForm.RECEIVEDQUANTITY,state.createBoxForm.RECEIVEDQUANTITY2)).toNumber();
    updateFnumber()
  }
}
function nowDate(time: any) {
  var year = time.getFullYear(); // 年
  var month = (time.getMonth() + 1).toString().padStart(2, '0'); // 月
  var date = time.getDate().toString().padStart(2, '0'); // 日
  var hour = time.getHours().toString().padStart(2, '0'); // 时
  var minute = time.getMinutes().toString().padStart(2, '0'); // 分
  var second = time.getSeconds().toString().padStart(2, '0'); // 秒
  return (
    year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
  )
}
function print() {
  if (state.PRINTNAME == null || state.PRINTNAME == "") {
    ElMessageBox.alert('请选择打印机', {
      confirmButtonText: 'OK',
    })
    return
  }
  if (state.MATERIALPACKINGLIST.length == 0) {
    ElMessageBox.alert('打印清单为空', {
      confirmButtonText: 'OK',
    })
    return
  }
  let PRINT = {
    LIST: state.MATERIALPACKINGLIST,
    PRINTNAME: state.PRINTNAME,
    USER: localStorage.get('userId')
  }
  state.button_print = true;
  state.loadings = true;
  printLabel(PRINT).then((res: any) => {
    console.log('PRINT',res)
    // if (res.success) {
    //   state.button_print = false;
    //   state.loadings = false;
    //   ElMessageBox.alert('标签打印成功', {
    //     confirmButtonText: 'OK',
    //   })
    // }else {
    //   state.button_print = false;
    //   state.loadings = false;
    // }
  })
    .catch(() => { 
      state.button_print = false;
      state.loadings = false;
    });
    state.button_print = false;
    state.loadings = false;
    ElMessageBox.alert('标签打印成功', {
      confirmButtonText: 'OK',
    })
}
function getMaterialUnit() {
  getQueryList({
    queryId: "GetMaterialUnit",
    version: "00001",
    params: {
      SITENAME: "SDK",
    } as any,
  }).then((res: any) => {
    state.UnitList = res.data
  })
}
function createBox(row: any) {
  if (row.MAKEDATE == null || row.MAKEDATE == "") {
    ElMessageBox.alert('制造日期不能为空', {
      confirmButtonText: 'OK',
    })
    return;
  }
  if (row.ERPFACTORY == null || row.ERPFACTORY == "") {
    ElMessageBox.alert('组织不能为空', {
      confirmButtonText: 'OK',
    })
    return;
  }
  if (row.ERPLOCATION == null || row.ERPLOCATION == "") {
    ElMessageBox.alert('仓库不能为空', {
      confirmButtonText: 'OK',
    })
    return;
  }
  state.boxDrawer = true
  state.createBoxForm = row
  if (row.MATERIALSPECNAME.startsWith("3") || row.MATERIALSPECNAME.startsWith("4")) {
    state.createBoxForm.TrueGG = row.SPECNAME
  } else {
    state.createBoxForm.TrueGG = row.DESCRIPTION
  }

  state.createBoxForm.Remark = row.REMARK
  state.createBoxForm.MINUSQTY = row.MINUSQTY
  state.createBoxForm.RECEIVEDQUANTITY2 = 0
  state.createBoxForm.MATERIALQUANTITY = 0
  state.createBoxForm.MATERIALCREATEQUANTITY = 0
  state.createBoxForm.FUNIT = row.FUNIT
  if (row.FUNIT == "" || row.FUNIT == null) {
    state.unitAble =false
  } else {
    state.unitAble =true
  }
  // console.log(parseFloat(row.REQUESTQUANTITY), parseFloat(row.RECEIVEDQUANTITY))
  state.createBoxForm.MINUSQTY = (cals.sub(row.REQUESTQUANTITY,row.RECEIVEDQUANTITY)).toNumber();
  console.log(row);
}
function deleteBox(row) {
  console.log(state.createBoxForm)
  state.loadings = true
  state.button_state = true
  state.createBoxForm.MAKEDATE = msToDate(state.createBoxForm.MAKEDATE).hasTime
  console.log(state.createBoxForm.MAKEDATE)
  state.createBoxForm = row
  DeleteTrackOutBox({
    materialreceiveAct: state.createBoxForm,
    user: localStorage.get('userId')
  }).then((res: any) => {
    if (res.success) {
      ElMessageBox.alert('解绑成功', '提醒框', {
        confirmButtonText: 'OK',
      })
      handleQuery()
      state.InputState = false
      state.loadings = false
      state.button_state = false
    } else {
      ElMessageBox.alert('解绑失败：' + res.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loadings = false
      state.button_state = false
    }
  }).catch((err: any) => {
    ElMessageBox.alert('解绑失败' + err, '提醒框', {
      confirmButtonText: 'OK',
    })
    state.loadings = false
    state.button_state = false
  })
  state.loadings = false
  state.button_state = false
}

// 删除一行的标签
function deleteThisBox(row) {
  console.log(row)
  state.loadings = true
  state.button_state = true
  DeleteTrackOutThisBox({
    materialreceiveAct: row,
    user: localStorage.get('userId')
  }).then((res: any) => {
    if (res.success) {
      ElMessageBox.alert('解绑成功', '提醒框', {
        confirmButtonText: 'OK',
      })
      // ElMessage({
      //   message: '解绑成功',
      //   type: 'success',
      // })
      handleQuery()
      state.InputState = false
      state.loadings = false
      state.button_state = false
    } else {
      ElMessageBox.alert('解绑失败：' + res.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loadings = false
      state.button_state = false
    }
  }).catch((err: any) => {
    ElMessageBox.alert('解绑失败' + err, '提醒框', {
      confirmButtonText: 'OK',
    })
    state.loadings = false
    state.button_state = false
  })
  state.loadings = false
  state.button_state = false
}

// 创建box
function commitBox() {
  // formDataRef.value.validate(valid => {
  //   if (valid) {
  //     ElMessageBox.alert('验证通过');
  //   } else {
  //     ElMessageBox.alert('验证失败');
  //     return false;
  //   }
  // });
  // console.log(state.createBoxForm)
  if (state.createBoxForm.MINUSQTY < 0) {
    ElMessageBox.alert('创建失败,剩余数量不足以创建批次')
    return
  }
  state.button_loading2 = true
  state.button_state2 = true
  var getTime = new Date().getTime(); //获取到当前时间戳
  var time = new Date(getTime); //创建一个日期对象
  state.createBoxForm.MAKEDATE = msToDate(state.createBoxForm.MAKEDATE).hasTime
  // state.createBoxForm.MAKEDATE = nowDate(time)
  console.log('MAKEDATE1',state.createBoxForm.MAKEDATE)
  
  CreateBox({
    materialreceiveAct: state.createBoxForm,
    user: localStorage.get('userId')
  }).then((res: any) => {
    // console.log(res)
    state.MATERIALPACKINGLISTS = "";
    if (res.success) {
      state.MATERIALPACKINGLISTS = res.resultObj.materialreceiveAct
      state.createBoxForm.RECEIVEDQUANTITY = (cals.add(state.createBoxForm.RECEIVEDQUANTITY2,state.createBoxForm.RECEIVEDQUANTITY)).toNumber(); 
      ElMessageBox.alert('创建成功', '提醒框', {
        confirmButtonText: 'OK',
      })
      handleQuery()
      state.InputState = false
      state.button_loading2 = false
      state.button_state2 = false
    } else {
      ElMessageBox.alert('创建失败：' + res.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.button_loading2 = false
      state.button_state2 = false
    }
  }).catch((err: any) => {
    ElMessageBox.alert('创建失败' + err, '提醒框', {
      confirmButtonText: 'OK',
    })
    state.button_loading2 = false
      state.button_state2 = false
  })
  state.loadings = false
  // state.button_state = false
}

function handleClose(done) {
  this.$confirm('确认关闭？')
    .then(_ => {
      done();
    })
    .catch(_ => { });
}

function handleQuery() {
  state.InputState = true
  state.queryParams.queryId = 'GetInvoiceDetailInformationRow'
  state.queryParams.version = 'Z10006_SAP'
  state.MATERIALRECEIVEACT = []
  state.MATERIALPACKINGLIST = []
  console.log(state.queryParams)
  if(state.queryParams.params.RECEIVEREQUESTNAME == ''){
    ElMessageBox.alert('输入查询条件', '提醒框', {
      confirmButtonText: 'OK',
    })
    return;
  }
  getQueryList(state.queryParams).then((res: any) => {
    console.log(res)
    if(res.data.length == 0){
      ElMessageBox.alert('查无结果', '提醒框', {
        confirmButtonText: 'OK',
      })
    } else {
      state.MATERIALRECEIVEACT = res.data
      if(state.MATERIALPACKINGLISTS != ""){
        for (var i=0; i < state.MATERIALRECEIVEACT.length; i++){
          if(state.MATERIALRECEIVEACT[i].MATERIALSPECNAME == state.MATERIALPACKINGLISTS.MATERIALSPECNAME && state.MATERIALRECEIVEACT[i].DESC_CN == state.MATERIALPACKINGLISTS.DESC_CN){
            state.MATERIALRECEIVEACT[i].ERPLOCATION = state.MATERIALPACKINGLISTS.ERPLOCATION
            state.MATERIALRECEIVEACT[i].ERPLOCATION2 = state.MATERIALPACKINGLISTS.ERPLOCATION2
            state.MATERIALRECEIVEACT[i].LOCATIONNAME = state.MATERIALPACKINGLISTS.LOCATIONNAME
            state.MATERIALRECEIVEACT[i].LOCATIONNAME2 = state.MATERIALPACKINGLISTS.LOCATIONNAME2
          }
        }
        state.MATERIALPACKINGLISTS
      }
    }
  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK',
    })
  })

  state.queryParams.queryId = 'GetPackingRow'
  state.queryParams.version = 'xh002'
  state.queryParams.params.SITENAME = "SDK"
  state.queryParams.params.MATERIALSPECNAME = ""
  state.MATERIALPACKINGLIST = []
  getQueryList(state.queryParams).then((res: any) => {
    state.MATERIALPACKINGLIST = res.data

  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK',
    })
  })

}


async function sendToERP() {
  state.button_state = true
  state.button_loading = true
  console.log(state.button_state)
  console.log(state.commitDate)
  if(state.commitDate == null){
    ElMessageBox.alert('过账时间不可清空', {
      confirmButtonText: 'OK',
    })
    state.loadings = false
    state.button_state = false
    state.button_loading = false
    return;
  }
  console.log(state.OpCode == null || state.OpCode == "")
    getOpCode (
            {
              opcode : state.OpCode,
              user: localStorage.get('userId'),
            }
    ).then((res: any) => {
      console.log(res.resultObj)
      state.OpCode = res.resultObj
      if (state.MATERIALPACKINGLIST == null || state.MATERIALPACKINGLIST.length < 1) {
        ElMessageBox.alert('待提交信息不能为空', {
          confirmButtonText: 'OK',
        })
        state.loadings = false
        state.button_state = false
        state.button_loading = false
        return;
      }
      PurInSendERPByCharge({
        materialreceiveAct: state.MATERIALPACKINGLIST[0],
        user: localStorage.get('userId'),
        commitDate : state.commitDate,
        opcode : state.OpCode,
      }).then((res: any) => {
        console.log(res)
        if (res.success) {
          state.OpCode = "",
          ElMessageBox.alert('入库成功', '提醒框', {
            confirmButtonText: 'OK',
          })
          handleQuery()
          state.InputState = false
          state.loadings = false
          state.button_state = false
          state.button_loading = false
        } else {
          ElMessageBox.alert('入库失败：' + res.message, '提醒框', {
            confirmButtonText: 'OK',
          })
          state.loadings = false
          state.button_state = false
          state.button_loading = false
        }
      }).catch((err: any) => {
        ElMessageBox.alert('入库失败' + err, '提醒框', {
          confirmButtonText: 'OK',
        })
        state.loadings = false
        state.button_state = false
        state.button_loading = false
      })
      state.loadings = false
      state.button_loading = false
      })



}
function handle(row: any, event: any, column: any) {
  if (areAllNotEmpty(row.ERPFACTORY)) {
    getERPLocation(row.ERPFACTORY)
  } else {
    ElMessageBox.alert("该明细下组织为空！", '警示框', {
      confirmButtonText: 'OK',
    })
  }


  if (areAllNotEmpty(row.ERPLOCATION)) {
    getStorageSpec(row.ERPLOCATION)
  } else {
    ElMessageBox.alert("该仓库下货位为空！", '警示框', {
      confirmButtonText: 'OK',
    })
  }

  state.queryParams.queryId = 'GetPackingRow'
  state.queryParams.version = 'xh002'
  state.queryParams.params.SITENAME = "SDK"
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME
  state.MATERIALPACKINGLIST = []
  getQueryList(state.queryParams).then((res: any) => {
    state.MATERIALPACKINGLIST = res.data

  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK',
    })
  })

}

/**************************************************公共方法************************************************/
function formatDate(date: any) {
  var year = date.getFullYear();

  // 注意JavaScript中的月份是从0开始的，所以需要+1
  var month = ("0" + (date.getMonth() + 1)).slice(-2);

  // 同样，日期也是从1开始的，但是我们需要检查它是否小于10，并在前面添加0（如果需要）
  var day = ("0" + date.getDate()).slice(-2);

  // 拼接字符串
  return year + "-" + month + "-" + day;
}
function getStorageSpec(value: any) {
  state.AllLocationList = []
  getQueryList({
    queryId: "GetLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPLOCATION: value,//PO
    } as any,
  }).then((res: any) => {
    state.AllLocationList = res.data
    this.locatioNFilter('')
  })
}
function getERPLocation(erpfactory: any) {
  getQueryList({
    queryId: "GetERPLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPFACTORYNAME: erpfactory,//PO
    } as any,
  }).then((res: any) => {
    state.ERPLocationList = res.data

  })
}

/**
 * 货位卡顿处理
 * @param query
 */
function locatioNFilter(query : any) {
  console.log(query)
  let arr = state.AllLocationList.filter((item : any) => {
    return (item.LABEL.includes(query) || item.VALUE.includes(query))
  })
  if (arr.length > 50) {
    state.LocationList = arr.slice(0, 50)
  } else {
    state.LocationList = arr
  }
}
</script>

<style scoped lang="scss">
.el-overlay.userRoleModel {}

.operate-bottom {
  width: 80px;
  height: 28px;
  float: right;
  margin-top: 20px;
}


/* 自定义滚动条整体样式 */
.el-table__body-wrapper::-webkit-scrollbar {
  width: 12px; /* 滚动条的宽度 */
  height: 12px; /* 垂直滚动条的宽度，如果需要的话 */
}

/* 自定义滚动条滑块样式 */
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: darkgrey; /* 滑块的颜色 */
  border-radius: 10px; /* 滑块的圆角 */
  border: 2px solid transparent; /* 滑块边框，设置为透明 */
  background-clip: content-box; /* 使得边框内缩，只显示内容区域 */
}

/* 自定义滚动条轨道样式 */
.el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #f1f1f1; /* 轨道的颜色 */
  border-radius: 10px; /* 轨道的圆角 */
}

/* 当鼠标悬停在滑块上时改变滑块样式 */
.el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #555; /* 鼠标悬停时的颜色 */
}
</style>
