<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="4">
            <el-form-item label="到货单" prop="params.RECEIVEREQUESTNAME">
              <el-Input v-model="queryParams.params.RECEIVEREQUESTNAME" placeholder="到货单" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库单" prop="params.actNo">
              <el-select v-model="queryParams.params.RECEIVEACTNO" placeholder="请选择入库单" style="width: 240px"
                :disabled="state.RECEIVEACTNODisplay" default-first-option>
                <el-option v-for="item in GetActInformationList" :key="item.value" :label="item.RECEIVEACTNO"
                  :value="item.RECEIVEACTNO" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="移动原因" prop="params.DELIVERYTYPE">
              <el-select v-model="queryParams.params.DELIVERYTYPE" placeholder="Select" style="width: 240px"
                default-first-option>
                <el-option v-for="item in GetDELIVERYTYPE" :key="item.value" :label="item.CODEDESCRIPTION"
                  :value="item.CODEDESCRIPTION" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label="供应商" prop="params.SUPPLIERNAME">
              <el-Input v-model="queryParams.params.SUPPLIERNAME" placeholder="供应商" clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button type="primary" @click="Reset">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>到货单编号信息</span>
          </div>
        </div>
      </div>
      <el-table border v-loading="state.loading" :data="state.DocumentList" highlight-current-row row-key="id"
        style="width: 100%" @row-click="handle">
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide && (col.dispaly == true)" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column v-if="col.text && (col.time == false)" :label="col.header">
            <template #default="scope">
              <el-input v-model="scope.row[col.field]" style="width: 120px" placeholder="请输入组织编号" v-if="col.flag" />
              <span v-if="!col.flag">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="col.text && (col.time == true)" :label="col.header">
            <template #default="scope">
              <el-input v-model="scope.row[col.field]" style="width: 120px" placeholder="请输入仓库编号" v-if="col.flag" />
              <span v-if="!col.flag">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column> -->
        </template>
      </el-table>
    </div>
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>入库单</span>
          </div>
        </div>
        <div class="page-table-operateBtns">
          <el-button type="primary" v-loading="state.loading3" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            创建入库单
          </el-button>
        </div>
      </div>
      <el-table border v-loading="state.loading" :data="state.ACTInfoList" highlight-current-row row-key="id"
        style="width: 100%" @row-click="handle2">
        <template v-for="(col, index) in column1" :key="index">
          <el-table-column v-if="!col.hide && (col.dispaly == true)" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="col.text && (col.time == false)" :label="col.header">
            <template #default="scope">
              <el-input v-model="scope.row[col.field]" style="width: 120px" placeholder="请输入接收数量"
                v-if="scope.row['flag']" />
              <span v-if="!scope.row['flag']">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="col.time && col.dispaly == false && col.text && col.ERPLocation == false"
            :label="col.header">
            <template #default="scope">
              <el-select v-model="state.ChangeParams.body.ERPLOCATION" placeholder="选择仓库" style="width: 240px"
                default-first-option @change="getStorageSpec" filterable v-if="scope.row['flag']">
                <el-option v-for="item in state.ERPLocationList" :key="item.VALUE" :label="item.LABEL"
                  :value="item.VALUE" />
              </el-select>
              <span v-if="!scope.row['flag']">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="col.time && col.dispaly == false && col.text && col.ERPLocation" :label="col.header">
            <template #default="scope">
              <el-select v-model="state.ChangeParams.body.LOCATIONNAME" placeholder="选择库位" style="width: 240px"
                default-first-option filterable v-if="scope.row['flag']">
                <el-option v-for="item in state.POCreateLocationList" :key="item.VALUE" :label="item.LABEL"
                  :value="item.VALUE" />
              </el-select>
              <span v-if="!scope.row['flag']">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="col.time && (col.text == false) && state.IF_Time_Manager" :label="col.header">
            <template #default="scope">
              <el-date-picker v-model="scope.row['MAKEDATE']" type="date" style="width: 120px" placeholder="请选择时间"
                :size="'small'" v-if="scope.row['flag']" />
              <span v-if="!scope.row['flag']">{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

      </el-table>
    </div>

    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="state.ChangeParams" :inline="true" label-position="left">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="实际规格" prop="state.ChangeParams.body">
              <el-Input v-model="state.ChangeParams.body.TrueGG" placeholder="实际规格" clearable @input="InputNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="单个标签物料数量" prop="state.ChangeParams.body">
              <el-Input v-model="state.ChangeParams.body.MATERIALCREATEQUANTITY" placeholder="单个标签物料数量"
                @input="InputNumber2" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="标签数量" prop="state.ChangeParams.body">
              <el-Input v-model="state.ChangeParams.body.MATERIALQUANTITY" placeholder="标签数量" clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="备注" prop="state.ChangeParams.body">
              <el-Input v-model="state.ChangeParams.body.Remark" placeholder="备注信息..." clearable
                @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="handleCreate" :disabled="state.ClickButton">预创建标签</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5" class="col_height">
            <el-form-item label="辅单位" prop="DESCRIPTION">
              <el-select v-model="queryParams.params.FUNIT" placeholder="辅单位" style="width: 240px" 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-col>
          <el-col :span="5" class="col_height">
            <el-form-item label="" prop="DESCRIPTION">
              <el-form-item label="辅数量" prop="state.ChangeParams.body">
                <el-Input v-model="state.ChangeParams.body.FQTY" placeholder="辅数量" clearable
                  @keyUpEvent="handleQuery" />
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleStockIn">入库</el-button>

      </div>
    </el-row>

    <el-dialog v-model="state.dialogVisible" title="创建标签" width="700" :before-close="handleClose">
      <span>标签页</span>
      <template #footer>
        <el-table border v-loading="state.loading" :data="state.BOXList" highlight-current-row row-key="id"
          style="width: 100%">
          <!-- <el-table-column type="selection" width="40" :reserve-selection="true" /> -->
          <template v-for="(col, index) in column2" :key="index">
            <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row[col.field] }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="col.text && (col.time == false) && state.ModifyBox" :label="col.header">
              <template #default="scope">
                <el-input v-model="scope.row[col.field]" style="width: 120px" placeholder="请输入矫正数量"
                  v-if="scope.row['flag']" />
                <span v-if="!scope.row['flag']">{{ scope.row[col.field] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="" prop="queryParams.params">
              <el-checkbox label="打印标签" name="type" v-model="IFPrint" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="" prop="queryParams.params">
              <el-Input v-model="state.LabelNumber" placeholder="标签数量" clearable @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="" prop="queryParams.params">
              <el-Input v-model="state.ALLNumber" placeholder="总数量" clearable @keyUpEvent="handleQuery" />
            </el-form-item>
          </el-col>
          <el-button type="primary" @click="handBoxModify">修改</el-button>
          <el-button type="primary" @click="handBoxConfirm">确认</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>

</template>
<script lang="ts">
export default {
  name: "createBoxByPO",
};
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElMessageBox, ElTable } from "element-plus";
import { getUserRoleList } from "@/api/user";
import { BpelEvent, getQueryList, getQueryPageList } from "@/api/common";
import { getRSAPublic } from "@/api/auth";
import { JSEncrypt } from "jsencrypt";
import router from "@/router";
import { useRouter } from 'vue-router'
import { IFTRUE, msToDate, areAllNotEmpty } from '@/utils/CommonUtil'
import { ModifyPackingEvent, ModifyACTEvent } from '@/api/StockIn'
import { printLabel } from "@/api/label";

const routerPath = useRouter()//router被定义了，routerPath就是定义的路由的意思
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const roleTableRef = ref();

const IFPrint = ref(false);
const state = reactive({
  rsa: "",
  LabelNumber: '',//总标签数量
  ALLNumber: 0,//弹框中标签的总数量
  SUPPLIERNO: '',
  RealERPLocation: '',
  RealLocation: '',
  POCreateUnit: '',//单位
  POCreateGG: '',//SDK规格
  UnitList: '',//单位列表
  POCreateLocationList: [] as any,
  ERPLocationList: [] as any,
  location2: '',
  ModifyBox: false,
  ReceiveActNumber: 0,
  ClickButton: true,
  loading3: false,
  RECEIVEACTNODisplay: false,
  AleradyReceiveQuantity: '',//已经接收的数量
  DetailREQUESTQUANTITY: '',//订单明细里需要接收的数量
  tabClickIndex: '',
  tabClickLabel: '',
  dialogVisible: false,
  BOXList: [] as any,
  queryParams: {
    queryId: "GetCreateBoxList",
    version: "00001",
    params: {
      SITENAME: "SDK",
      RECEIVEREQUESTNAME: "",//PO
      RECEIVEACTNO: "",//入库单
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",//供应商
      SHIPREQUESTNAME: "",//预留单 
      LASTEVENTTIMEKEY: '',
    } as any,
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      Flag: 'LK',//立库标志
      EventUser: localStorage.getItem('userId'),
      EventTime: msToDate(new Date()).withoutTime

    },
    body: {
      SITENAME: 'SDK',
      FQTY: '',
      FUNIT: '',
      RECEIVEREQUESTNAME: '',
      RECEIVEREQUESTDETAILNAME: '',
      RECEIVEQUANTITY: '',
      MATERIALSPECNAME: '',
      DESCRIPTION: '',
      ERPFACTORY: '',
      SUPPLIERNAME: '',
      RECEIVEACTNO: '',
      ACTTYPE: '',
      MAKEDATE: '',
      LOCATIONNAME: '',
      PHASE: '',
      MATERIALUNIT: '',
      SPECNAME: '',
      TrueGG: '',
      Remark: '',
      SUPPLIERNO: '',
      //退货入库情况
      SHIPREQUESTNAME: '',
      SHIPREQUESTDETAILNAME: '',
      ERPLOCATION: '',
      ERPRECEIVELOCATION: '',
      CHARGE: '',
      IS_BATCH: '',
      IQCFLAG: '',
      AREANAME: '',
      MATERIALCREATEQUANTITY: 0,
      MATERIALQUANTITY: 0,
      RECEIVEQTY: '',
      BOXQTYFLAG: '',
      REASONCODE: '',
      REASONCODETYPE: '',
      EXPIRINGDATE: '',
      NPFLAG: 'N',
      SDK_ID: '',
      REMARK: ''
    }
  },
  flag: false,
  dialog: {
    title: "新增用户",
    visible: false,
  },
  formData: {
    siteName: "",
    userId: "",
    userName: "",
    password: "",
    email: "",
  } as any,
  rules: {
    siteName: [{ required: true, message: "请输入工厂名", trigger: "blur" }],
    userId: [{ required: true, message: "请输入账号", trigger: "blur" }],
    userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  },
  column1: [] as any,
  column: [] as any,
  column2: [] as any,
  GetActInformationList: [] as any,
  selectItem: undefined as any,
  DocumentList: [] as any,
  ACTInfoList: [] as any,
  GetDELIVERYTYPE: [] as any,
  currentTime: "",
  total: 0,
  loading: false,
  InvoiceName: "",
  roleDialog: {
    title: "分配角色",
    visible: false,
  },
  allRole: [] as any,
  column_col: 0,
  IF_Time_Manager: false
});
const { column_col, loading, total, GetDELIVERYTYPE, InvoiceName, ACTInfoList, DocumentList, GetActInformationList, queryParams, dialog, formData, rules, column2, column1, column, currentTime, roleDialog, allRole } = toRefs(state);

onMounted(() => {
  (state.column = [
    { header: "工厂", field: "SITENAME", hide: false, dispaly: true },
    { header: "库存组织", field: "ERPFACTORY2", hide: false, dispaly: true },
    { header: "库存组织", field: "ERPFACTORY", hide: true, dispaly: true },
    { header: "到货单", field: "RECEIVEREQUESTNAME", hide: false, dispaly: true },
    { header: "订单行项", field: "RECEIVEREQUESTDETAILNAME", hide: false, dispaly: true },
    { header: "物料", field: "MATERIALSPECNAME", hide: false, dispaly: true },
    { header: "品名", field: "DESC_CN", hide: false, dispaly: true },
    { header: "仓库", field: "ERPLOCATION2", hide: false, dispaly: true },
    { header: "仓库", field: "ERPLOCATION", hide: true, dispaly: true },
    { header: "货位", field: "LOCATIONNAME2", hide: false, dispaly: true },
    { header: "货位", field: "LOCATIONNAME", hide: true, dispaly: true },
    { header: "订单数量", field: "REQUESTQUANTITY", hide: false, dispaly: true },
    { header: "实收数量", field: "RECEIVEDQUANTITY", hide: false, dispaly: true },
    { header: "剩余接收数量", field: "RECEIVEDQUANTITY2", hide: false, dispaly: true },
    { header: "单位", field: "MATERIALUNIT", hide: true, dispaly: true },
    { header: "单位", field: "MATERIALUNITDESC", hide: false, dispaly: true },
    { header: "SDK规格ID", field: "SDK_ID", hide: true, dispaly: true },
    { header: "SDK规格", field: "SPECNAME", hide: true, dispaly: true },
    { header: "规格", field: "DESCRIPTION", hide: false, dispaly: true },
    { header: "阶段", field: "PHASE", hide: false, dispaly: true },
    { header: "启用批次", field: "IS_BATCH", hide: false, dispaly: true },
    { header: "启用质检", field: "IQCFLAG", hide: false, dispaly: true },
    { header: "有效期管理方式", field: "REPLACED_VALUE", hide: false, dispaly: true },
    { header: "备注", field: "REMARK", hide: false, dispaly: true },
  ]),
    (state.column2 = [
      { header: "标签编号", field: "MATERIALPACKINGNAME", hide: false },
      { header: "标签数量", field: "MATERIALQUANTITY", hide: false },
      { header: "教正数量", field: "MATERIALQUANTITY2", hide: true, text: true, time: false },
      { header: "备注", field: "REMARK", hide: false },
      { header: "用户", field: "User", hide: true },
    ]),
    (state.column1 = [
      { header: "工厂", field: "SITENAME", hide: false, dispaly: false },
      { header: "库存组织", field: "ERPFACTORY", hide: false, dispaly: true },
      { header: "到货单", field: "RECEIVEREQUESTNAME", hide: false, dispaly: true },
      { header: "订单行项", field: "RECEIVEREQUESTDETAILNAME", hide: false, dispaly: true },
      { header: "入库单", field: "RECEIVEACTNO", hide: false, dispaly: true },
      { header: "物料", field: "MATERIALSPECNAME", hide: false, dispaly: true },
      { header: "品名", field: "DESCRIPTION", hide: false, dispaly: true },
      { header: "仓库", field: "ERPLOCATION", hide: false, text: true, time: true, dispaly: false, ERPLocation: false, flag: false },
      { header: "货位", field: "LOCATIONNAME", hide: false, text: true, time: true, dispaly: false, ERPLocation: true, flag: false },
      { header: "接收数量", field: "RECEIVEQUANTITY", hide: false, text: true, time: false, dispaly: false },
      { header: "生产日期", field: "MAKEDATE", hide: false, time: true, text: false, dispaly: false },
      { header: "供应商名称", field: "SUPPLIERNAME", hide: true, dispaly: true },
      // { header: "生产日期", field: "MAKEDATE", hide: false, dispaly: true },
      { header: "接收日期", field: "RECEIVETIME", hide: false, dispaly: true },
      { header: "入库类型", field: "ACTTYPE", hide: false, dispaly: true },
      // { header: "SDK规格", field: "SDK_ID", hide: false, dispaly: true },
      { header: "SDK规格", field: "SPECNAME", hide: false },
      { header: "阶段", field: "PHASE", hide: false },
      { header: "有效期管理方式", field: "REPLACED_VALUE", hide: false },
      { header: "备注", field: "REMARK", hide: false, dispaly: true },
    ]);
  getMaterialUnit()
  // handleQuery();

  //getRSA();
});
// 更新列
function updateList(col: any) {
  state.column1 = col;
}
function getRSA() {
  getRSAPublic()
    .then((res: any) => {
      state.rsa = res.data;
    })
    .catch(() => { });
}

function handleQuery() {
  if ((state.queryParams.params.RECEIVEREQUESTNAME != '') && (state.queryParams.params.RECEIVEREQUESTNAME) != null && (state.queryParams.params.RECEIVEREQUESTNAME != undefined)) {
    let flag = true;
    state.DocumentList = []
    if (state.queryParams.params.RECEIVEACTNO == "") {
      getQueryList(state.queryParams)
        .then((res: any) => {
          let mpp = res.data;
          if (mpp.LASTEVENTUSER != null && mpp.LASTEVENTUSER != "") {
            if (mpp.LASTEVENTUSER != localStorage.getItem("userName")) {
              ElMessageBox.confirm("工号:" + mpp.LASTEVENTUSER + " 姓名:" + mpp.RECEIVER + " 也在收货" + "\r\n" + "最近作业时间:" + mpp.LASTEVENTTIME + "\r\n" + "请与其确认后再收货", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                flag = false;
              });
            }
          }
          if (flag) {
            getViewData();
          }
        })
        .catch(() => { });
    }
  } else {
    ElMessageBox.alert('到货单是必填选项', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }

}


function handleEdit(row: any) {
  row.editable = true
}
async function getViewData(this: any) {
  state.ACTInfoList = []
  /*判断到货单不为空 */
  if (state.queryParams.params.RECEIVEREQUESTNAME != "") {
    let queryPoOrShip = {
      queryId: "GetInvoiceDetailInformationRow",
      version: "10005",
      params: {
        SITENAME: "SDK",
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,//PO
        RECEIVEACTNO: state.queryParams.params.RECEIVEACTNO,//入库单
        DELIVERYTYPE: state.queryParams.params.DELIVERYTYPE, //移动类型
        SUPPLIERNO: state.queryParams.params.SUPPLIERNAME,//供应商
        SHIPREQUESTNAME: "",//预留单 
      } as any
    };
    let POList = await getQueryList(queryPoOrShip).then(res => res.data)
    queryPoOrShip.params.SHIPREQUESTNAME = state.queryParams.params.RECEIVEREQUESTNAME;
    let ShipList = await getQueryList({ ...queryPoOrShip, version: "10002" }).then(res => res.data)
    if (POList.length > 0) {
      state.DocumentList = POList;
      setMoveInfo('101');
    } else if (ShipList.length > 0) {
      state.DocumentList = ShipList;
      if (state.queryParams.params.RECEIVEACTNO != "") {
        let queryShipAct = {
          queryId: "GetReasonCode",
          version: "00002",
          params: {
            SITENAME: "SDK",
            RECEIVEACTNO: state.queryParams.params.RECEIVEACTNO,//入库单
          } as any
        }
        let ShipActList = await getQueryList(queryShipAct).then(res => res.data)
        if (ShipActList > 0) {
          setMoveInfo(ShipActList[0]['REASONCODE'], ShipActList[0]['REASONCODETYPE']);
        } else {
          let queryShipActTwo = {
            queryId: "GetInvoiceDetailInformationRow",
            version: "00003",
            params: {
              SITENAME: "SDK",
              RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,//入库单
            } as any
          }
          let ShipActTwo = await getQueryList(queryShipAct).then(res => res.data)
          if (ShipActTwo.length > 0) {
            setMoveInfo('262');
          } else {
            setMoveInfo('312');
          }
        }
      }

    }
  }
  /*判断入库单为空 */
  /*if (state.queryParams.params.RECEIVEACTNO == "") {
    let queryActNo = {
      queryId: "GetActInformationRow",
      version: "00001",
      params: {
        SITENAME: "SDK",
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,//PO
        RECEIVEACTNO: state.queryParams.params.RECEIVEACTNO,//入库单
        DELIVERYTYPE: state.queryParams.params.DELIVERYTYPE, //移动类型
        SUPPLIERNO: state.queryParams.params.SUPPLIERNAME,//供应商
        SHIPREQUESTNAME: "",//预留单 
      } as any
    }
    let ActNoList = await getQueryList(queryActNo).then(res => res.data)
    state.GetActInformationList = ActNoList;
    state.queryParams.params.RECEIVEACTNO = ActNoList[0]['RECEIVEACTNO'];
    state.GetActInformationList.push("");
  }*/
  /*判断入库单不为空 */
  if (state.queryParams.params.RECEIVEACTNO != "") {
    if (state.queryParams.params.RECEIVEREQUESTNAME == "") {
      alert("请输入或选择查询条件！");
      return;
    }
    let queryActNoIFFinish = {
      queryId: "getActInfo",
      version: "00001",
      params: {
        SITENAME: "SDK",
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,//PO
        RECEIVEACTNO: state.queryParams.params.RECEIVEACTNO,//入库单
        DELIVERYTYPE: state.queryParams.params.DELIVERYTYPE, //移动类型
        SUPPLIERNO: state.queryParams.params.SUPPLIERNAME,//供应商
        SHIPREQUESTNAME: "",//预留单 
      } as any
    }
    let ActNoIFFinish = await getQueryList(queryActNoIFFinish).then(res => res.data)
    // if (ActNoIFFinish.length <= 0) {
    //   state.queryParams.params.RECEIVEACTNO = "";
    //   getViewData()
    //   return
    // }
    let queryPoOrShipActNO = {
      queryId: "GetActDetailInformationRow",
      version: "R10003",
      params: {
        SITENAME: "SDK",
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,//PO
        RECEIVEACTNO: state.queryParams.params.RECEIVEACTNO,//入库单
        DELIVERYTYPE: state.queryParams.params.DELIVERYTYPE, //移动类型
        SUPPLIERNO: state.queryParams.params.SUPPLIERNAME,//供应商
        SHIPREQUESTNAME: "",//预留单 
      } as any
    };
    let POActNOList = await getQueryList(queryPoOrShipActNO).then(res => res.data)
    queryPoOrShipActNO.params.SHIPREQUESTNAME = state.queryParams.params.RECEIVEREQUESTNAME;
    let ShipActNOList = await getQueryList({ ...queryPoOrShipActNO, version: "S10003" }).then(res => res.data)
    if (POActNOList.length > 0)
      state.ACTInfoList = POActNOList;
    if (ShipActNOList > 0)
      state.ACTInfoList = ShipActNOList;
  }

}
/* 移动类型*/
async function setMoveInfo(...args: any) {
  if (arguments.length == 1) {
    let queryMoveInfo = {
      queryId: "GetMoveReason",
      version: "00001",
      params: {
        SHIPREQUESTDETAILTYPE: arguments[0]
      }
    }
    let MoveInfoList = await getQueryList(queryMoveInfo).then(res => res.data)
    state.GetDELIVERYTYPE = MoveInfoList;
    state.queryParams.params.DELIVERYTYPE = MoveInfoList[0]['CODEDESCRIPTION'];
    state.GetDELIVERYTYPE.push("");
  }

  if (arguments.length == 2) {
    let queryMoveInfo = {
      queryId: "GetMoveReason",
      version: "00002",
      params: {
        SHIPREQUESTDETAILTYPE: arguments[0],
        REASONCODE: arguments[1]
      }
    }
    let MoveInfoList = await getQueryList(queryMoveInfo).then(res => res.data)
    state.GetDELIVERYTYPE = MoveInfoList;
    state.queryParams.params.DELIVERYTYPE = MoveInfoList[0]['CODEDESCRIPTION'];
    state.GetDELIVERYTYPE.push("");
  }

}

function Reset() {
  state.queryParams.params.RECEIVEREQUESTNAME = '';
  state.queryParams.params.RECEIVEACTNO = '';
  state.queryParams.params.SUPPLIERNAME = '';
  //queryFormRef.value.resetFields();
  //handleQuery();
}
/**
 * 新增入库单 
 */
async function handleAdd() {
  state.ChangeParams.body.ERPLOCATION = ""
  if ((state.ChangeParams.body.RECEIVEREQUESTNAME != '') && (state.ChangeParams.body.RECEIVEREQUESTNAME != null) && (state.ChangeParams.body.RECEIVEREQUESTNAME != undefined)) {
    state.ACTInfoList = [];
    state.loading3 = true
    state.ChangeParams.header.MESSAGENAME = 'GenerateActNo'
    await BpelEvent(state.ChangeParams).then((res: any) => {
      if (IFTRUE(res)) {
        if (state.ReceiveActNumber == 0) {
          state.ClickButton = false
          let obj = res.data
          obj.flag = true
          obj.RECEIVETIME = msToDate(new Date()).hasTime
          obj.RECEIVEQUANTITY = 0
          state.ACTInfoList.push(obj)
          state.ChangeParams.body.LOCATIONNAME = state.location2
          state.ChangeParams.body.RECEIVEACTNO = res.data.RECEIVEACTNO
          state.GetActInformationList = [{ "RECEIVEACTNO": res.data.RECEIVEACTNO }]
          state.queryParams.params.RECEIVEACTNO = state.GetActInformationList[0]["RECEIVEACTNO"]
          state.RECEIVEACTNODisplay = true
        } else {
          state.ClickButton = false
          let obj = res.data
          obj.flag = true
          obj.RECEIVETIME = msToDate(new Date()).hasTime
          obj.ReceiveActNo = state.GetActInformationList[0]["RECEIVEACTNO"]
          obj.RECEIVEQUANTITY = 0
          state.ACTInfoList.push(obj)
          state.ChangeParams.body.LOCATIONNAME = state.location2
          state.ChangeParams.body.RECEIVEACTNO = obj.ReceiveActNo
          state.GetActInformationList = [{ "RECEIVEACTNO": obj.ReceiveActNo }]
          state.queryParams.params.RECEIVEACTNO = state.GetActInformationList[0]["RECEIVEACTNO"]
          state.RECEIVEACTNODisplay = true
        }
      } else {
        ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
          confirmButtonText: 'OK',
        })
      }

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

          confirmButtonText: 'OK',
        })
      });
  } else {
    ElMessageBox.alert('请选择到货单明细创建入库单', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }
  state.loading3 = false
}




/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}
// 点击入库跳转
function handleStockIn() {
  if (state.queryParams.params.RECEIVEREQUESTNAME != '' && state.queryParams.params.LASTEVENTTIMEKEY != '') {
    routerPath.push({ path: '/stockIn/normalStockIn', query: { ReceiveActNo: state.queryParams.params.RECEIVEACTNO } })
  } else {
    ElMessageBox.alert('请先创建标签', '提醒框', {
      confirmButtonText: 'OK',
    })
  }

}

function handle(row: any, event: any, column: any) {

  if (row.REPLACED_VALUE == '遵守有效期管理') {
    state.IF_Time_Manager = true
  } else {
    state.IF_Time_Manager = false
  }
  console.log(state.DocumentList[column])
  state.ChangeParams.body.RECEIVEREQUESTNAME = row.RECEIVEREQUESTNAME
  state.ChangeParams.body.RECEIVEREQUESTDETAILNAME = row.RECEIVEREQUESTDETAILNAME
  state.ChangeParams.body.MATERIALSPECNAME = row.MATERIALSPECNAME
  state.ChangeParams.body.DESCRIPTION = row.DESC_CN
  state.ChangeParams.body.SUPPLIERNAME = row.SUPPLIERNAME
  state.ChangeParams.body.ERPFACTORY = row.ERPFACTORY
  state.ChangeParams.body.ERPLOCATION = row.ERPLOCATION
  state.ChangeParams.body.LOCATIONNAME = row.LOCATIONNAME
  state.ChangeParams.body.ERPRECEIVELOCATION = row.ERPRECEIVELOCATION
  state.AleradyReceiveQuantity = row.RECEIVEDQUANTITY
  state.DetailREQUESTQUANTITY = row.REQUESTQUANTITY
  state.ChangeParams.body.ACTTYPE = 'Normal'
  state.ChangeParams.body.SDK_ID = row.SDK_ID
  state.ChangeParams.body.SPECNAME = row.SPECNAME
  state.ChangeParams.body.MATERIALUNIT = row.MATERIALUNIT
  state.ChangeParams.body.PHASE = row.PHASE
  state.ChangeParams.body.IQCFLAG = row.IQCFLAG
  state.ChangeParams.body.IS_BATCH = row.IS_BATCH
  state.ChangeParams.body.REMARK = row.REMARK
  state.location2 = row.LOCATIONNAME2
  state.SUPPLIERNO = row.SUPPLIERNO
  state.ChangeParams.body.Remark = row.REMARK
  //规格+单位
  state.POCreateUnit = row.MATERIALUNITDESC
  state.ChangeParams.body.TrueGG = row.DESCRIPTION
  var getTime = new Date().getTime(); //获取到当前时间戳
  var time = new Date(getTime); //创建一个日期对象
  state.ChangeParams.body.MAKEDATE = nowDate(time)
  if (areAllNotEmpty(row.ERPFACTORY)) {
    getERPLocation(row.ERPFACTORY)
  } else {
    ElMessageBox.alert("该明细下组织为空！", '警示框', {
      confirmButtonText: 'OK',
    })
  }
  state.RealERPLocation = row.ERPLOCATION
  state.RealLocation = row.LOCATIONNAME
}

function handle2(row: any, event: any, column: any) {
  state.column_col = column
}
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
  )
}

//dialog 弹窗+抬头纹本注入数据库
function handleCreate() {
  state.BOXList = [];
  let pattern = new RegExp("[\u4E00-\u9FA5]+");
  if (pattern.test(state.ChangeParams.body.LOCATIONNAME)) {
    state.ChangeParams.body.ERPLOCATION = state.RealERPLocation
    state.ChangeParams.body.LOCATIONNAME = state.RealLocation
  }
  if (state.ChangeParams.body.MATERIALCREATEQUANTITY > 0 && (state.ACTInfoList.length > 0)
    && (state.ACTInfoList[0]["RECEIVEQUANTITY"] != 0) && (state.ACTInfoList[0]["RECEIVEQUANTITY"] != null)
    && ((state.ACTInfoList[0]["RECEIVEQUANTITY"] != undefined))) {
    if (parseFloat(state.AleradyReceiveQuantity) + parseFloat(state.ACTInfoList[0]["RECEIVEQUANTITY"]) <= parseFloat(state.DetailREQUESTQUANTITY) * 1.05) {
      state.ChangeParams.header.MESSAGENAME = 'CreateActInfo'
      state.ChangeParams.body.RECEIVEQUANTITY = state.ACTInfoList[0]["RECEIVEQUANTITY"]
      state.ChangeParams.body.REMARK = state.ChangeParams.body.Remark
      //state.ChangeParams.body.RECEIVEACTNO=state.queryParams.params.RECEIVEACTNO
      BpelEvent(state.ChangeParams).then((res: any) => {
        if (IFTRUE(res)) {
          state.ReceiveActNumber++
        } else {
          ElMessageBox.alert("入库单创建失败" + res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
            confirmButtonText: 'OK',
          })
          state.ClickButton = false
        }
      }).catch((error: any) => {
        // ElMessageBox.alert("入库单创建失败" + '->' + error, '', {
        //   confirmButtonText: 'OK',
        // })
        state.ClickButton = false
      });
      state.ChangeParams.header.MESSAGENAME = 'TrackOutBox'
      state.ChangeParams.body.RECEIVEQTY = state.ACTInfoList[0]["RECEIVEQUANTITY"]
      state.ChangeParams.body.MAKEDATE = msToDate(state.ACTInfoList[0]["MAKEDATE"]).hasTime
      state.ChangeParams.body.SUPPLIERNO = state.SUPPLIERNO
      BpelEvent(state.ChangeParams).then((res: any) => {
        if (IFTRUE(res)) {
          state.queryParams.queryId = 'GetMaterialPackingList'
          state.queryParams.version = '00005'
          state.queryParams.params.LASTEVENTTIMEKEY = res.data.LASTEVENTTIMEKEY
          state.ClickButton = true
          state.IF_Time_Manager = false
          getQueryList(state.queryParams).then((res: any) => {
            const newBoxList = res.data.map((obj: any) => ({
              ...obj, // 使用展开运算符复制对象的所有属性  
              flag: true,// 设置 flag 属性为 true 
              User: localStorage.getItem('userId')
            }));
            // 将新数组赋值给 state.BOXList  
            state.BOXList = newBoxList;
            state.ALLNumber = 0
            state.LabelNumber = state.BOXList.length
            for (let i = 0; i < state.BOXList.length; i++) {
              state.ALLNumber += parseFloat(state.BOXList[i].MATERIALCREATEQUANTITY)
              if (i == state.BOXList.length - 1) {
                state.ALLNumber = state.ALLNumber + state.BOXList[i].FNAME
              }
            }

          }).catch((error: any) => {

          })
          state.ChangeParams.body.MATERIALCREATEQUANTITY = 0;
          state.ChangeParams.body.MATERIALQUANTITY = 0;

          state.ACTInfoList[0].ENDDATE = msToDate(state.ACTInfoList[0].ENDDATE).withoutTime


          state.ACTInfoList[0].flag = false
          //state.ACTInfoList = [];
        } else {
          ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
            confirmButtonText: 'OK',
          })
          state.ClickButton = false
        }
      })
        .catch((error: any) => {
          ElMessageBox.alert("创建标签失败，失败原因：=>" + error, '', {
            confirmButtonText: 'OK',
          })
          state.ClickButton = false
        });
      state.dialogVisible = true
    } else {
      ElMessageBox.alert('接收数量大于订单数量', '提醒框', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
      })
    }

  } else {
    ElMessageBox.alert('接收数量不为空', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }


}

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
  state.ClickButton = false
}

async function handBoxConfirm() {
  let colum = 0
  let colum1 = 0
  console.log(IFPrint.value)
  if (state.ModifyBox) {
    for (let i = 0; i < state.BOXList.length; i++) {
      colum = colum + parseFloat(state.BOXList[i].MATERIALQUANTITY)
      colum1 = colum1 + parseFloat(state.BOXList[i].MATERIALQUANTITY2)
    }
    if (colum == colum1) {
      await ModifyPackingEvent({
        BOXLIST: state.BOXList
      }).then((res: any) => {
        if (res.errorCode == '200') {
          state.dialogVisible = false
          proxy.$ElMessage.success('标签打印成功，点击入库按钮入库');
        }

      }).catch((error: any) => {

      })
    } else {
      ElMessageBox.alert('修改后的数量不等于创建时的数量', '提醒框', {
        confirmButtonText: 'OK',
      })
    }

  }
  // else {
  //   state.dialogVisible = false
  //   // proxy.$ElMessage.success('标签创建成功(未打印)');
  // } 
  if (IFPrint.value) {
    printLabel(state.BOXList).then((res: any) => {
      if (res.errorCode == '200') {
        state.dialogVisible = false
        proxy.$ElMessage.success('标签打印成功，点击入库按钮入库');
      }
    })
      .catch(() => { });
  } else {
    state.dialogVisible = false
    // proxy.$ElMessage.success('标签创建成功(未打印)');
  }



}

function InputNumber() {
  if (parseInt(state.ACTInfoList[0]["RECEIVEQUANTITY"]) > 0) {
    if (state.POCreateUnit != 'KG') {
      let arrs2 = state.ChangeParams.body.TrueGG.toString().split('*');
      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.ChangeParams.body.MATERIALCREATEQUANTITY = parseFloat((parseFloat(arrs2[1]) * parseFloat(arrs2[0])).toFixed(2));
      state.ChangeParams.body.MATERIALQUANTITY = Math.ceil(parseFloat(state.ACTInfoList[0]["RECEIVEQUANTITY"]) / state.ChangeParams.body.MATERIALCREATEQUANTITY)
      getMaterialUnit()
    }
  }
}

function InputNumber2() {
  if (parseInt(state.ACTInfoList[0]["RECEIVEQUANTITY"]) > 0) {
    state.ChangeParams.body.MATERIALQUANTITY = Math.ceil(parseFloat(state.ACTInfoList[0]["RECEIVEQUANTITY"]) / state.ChangeParams.body.MATERIALCREATEQUANTITY)
  }
}

function handBoxModify() {
  state.ModifyBox = !state.ModifyBox
  for (let i = 0; i < state.BOXList.length; i++) {
    state.BOXList[i].MATERIALQUANTITY2 = state.BOXList[i].MATERIALQUANTITY;
  }
}


function getERPLocation(erpfactory: any) {
  getQueryList({
    queryId: "GetERPLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPFACTORYNAME: erpfactory,//PO

    } as any,
  }).then((res: any) => {
    state.ERPLocationList = res.data
  })
}
function getStorageSpec(value: any) {
  state.POCreateLocationList = []
  getQueryList({
    queryId: "GetLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPLOCATION: value,//PO
    } as any,
  }).then((res: any) => {
    state.POCreateLocationList = res.data

  })
}

function getMaterialUnit() {

  getQueryList({
    queryId: "GetMaterialUnit",
    version: "00001",
    params: {
      SITENAME: "SDK",
    } as any,
  }).then((res: any) => {
    state.UnitList = res.data
  })
}








</script>

<style scoped lang="scss">
.operate-bottom {
  width: 80px;
  height: 28px;
  float: right;
}
</style>
