<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="10">
            <el-form-item label="入库单" prop="queryParams.params">
              <el-select v-model="state.queryParams.params.RECEIVEACTNO" placeholder="入库单" style="width: 160px"
                filterable>
                <el-option v-for="item in state.ReceiveACTList" :key="item.RECEIVEACTNO" :label="item.RECEIVEACTNO"
                  :value="item.RECEIVEACTNO" />
              </el-select>
            </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 class="page-table-operateBtns">
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table border v-loading="loading" :data="state.MATERIALRECEIVEACT" highlight-current-row row-key="id"
        style="width: 100%" height="450px">
        <template v-for="(col, index) in column" :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>
        </template>
      </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="6">
              <el-form-item label="过账时间" prop="state.ChangeParams.body">
                <el-date-picker v-model="state.ChangeParams.body.RECEIVETIME" type="date" placeholder="选择个时间"
                  clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="page-search-btns">
          <el-button type="primary" @click="resetQuery" :disabled="state.button_state">提交</el-button>
        </div>
      </el-row>
    </div>
  </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElMessageBox, ElTable } from "element-plus";
import { BpelEvent, getQueryList } from "@/api/common";
import { useRoute } from 'vue-router'
import { localStorage } from "@/utils/storage";
import { IFTRUE } from "@/utils/CommonUtil"

const route = useRoute()
const queryFormRef = ref(ElForm);
const operateFormRef = ref(ElForm);

const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const state = reactive({
  rsa: "",
  button_state: false,
  MATERIALRECEIVEACT: [] as any,
  ReceiveACTList: [] as any,
  queryParams: {
    queryId: "",
    version: "",
    params: {
      //SITENAME: localStorage.get("siteName"),
      SITENAME: 'SDK',
      RECEIVEREQUESTNAME: "",
      RECEIVEACTNO: '',
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      QualityFlag: false,
      ACTTYPE: '',
    },
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      EventUser: localStorage.get('userId')
    },
    body: {
      RECEIVETIME: '',//过账时间
      SITENAME: localStorage.get("siteName") == null ? "SDK" : localStorage.get("siteName"),
      RECEIVEACTNO: '',
      RECEIVEREQUESTNAME: '',
    }
  },
  operateParams: {
    date: new Date()
  },

  loading: false,
  userList: [] as any,
  column: [] as any,
});
const { MATERIALRECEIVEACT, rsa, queryParams, loading, userList, column, operateParams } = toRefs(state);

onMounted(() => {
  state.column = [
    { header: "工厂", field: "SITENAME", hide: false },
    { header: "入库单", field: "RECEIVEACTNO", hide: false },
    { header: "库存组织", field: "ERPFACTORY", hide: false },
    { header: "仓库", field: "ERPLOCATION", hide: false },
    { header: "货位", field: "LOCATIONNAME", hide: false },
    { header: "到货单", field: "RECEIVEREQUESTNAME", hide: false },
    { header: "到货单明细", field: "RECEIVEREQUESTDETAILNAME", hide: false },
    { header: "订单日期", field: "ORDERDATE", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "物料品名", field: "DESC_CN", hide: false },
    { header: "SDK规格", field: "SPECNAME", hide: false },
    { header: "阶段", field: "PHASE", hide: false },
    { header: "单据ID", field: "ERPID", hide: false },
    { header: "库存组织", field: "ERPFACTORY", hide: false },
    // { header: "是否采购退货", field: "RETURNFLAG", hide: false },
    { header: "批次数量", field: "MATERIALQUANTITY", hide: false },
    { header: "主单位", field: "UNIT", hide: false },
    { header: "批次", field: "CHARGE", hide: false },
  ];
  state.queryParams.params.RECEIVEACTNO = route.query.ReceiveActNo as string,
    SelectReceiveAct()
  state.queryParams.params.RECEIVEACTNO = route.query.ReceiveActNo as string
  SelectReceiveAct()

});

//查询所有的入库单
function SelectReceiveAct() {
  state.queryParams.queryId = 'GetNormalReceiveActNoList'
  state.queryParams.version = 'H0002'
  getQueryList(state.queryParams).then((res: any) => {
    state.ReceiveACTList = res.data
  })
}

// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  console.log(route.query.ReceiveActNo)
  console.log(route)
  if ((state.queryParams.params.RECEIVEACTNO != '') && (state.queryParams.params.RECEIVEACTNO != null) && (state.queryParams.params.RECEIVEACTNO != undefined)) {
    state.queryParams.queryId = 'GetPoToReceiveAct'
    state.queryParams.version = '00001'
    state.MATERIALRECEIVEACT = []
    getQueryList(state.queryParams).then((res: any) => {
      for (let item of res.data) {
        state.MATERIALRECEIVEACT.push({ ...item })
      }

    }).catch((error: any) => {
      ElMessageBox.alert(error.message, '提醒框', {
        confirmButtonText: 'OK',
      })
    })
  } else {
    ElMessageBox.alert('到货单为空！', '提醒框', {
      confirmButtonText: 'OK',
    })
  }

}

function getViewData() {
  // 查出该单据下所有的抬头文本
  let queryParams = {
    queryId: "GetActInformationRow",
    version: "00001",
    params: {
      SITENAME: localStorage.get("siteName"),
      RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,
    },
  };

  if (state.queryParams.params.RECEIVEREQUESTNAME.trim() === "" && state.queryParams.params.RECEIVEACTNO != "") {
    proxy.$ElMessage.error("请输入或选择查询条件！");
    return;
  }
  if (state.queryParams.params.RECEIVEREQUESTNAME.trim() != "") {
    let queryPar = {
      queryId: "GetInvoiceInformation",
      version: "00001",
      params: {
        SITENAME: localStorage.get("siteName"),
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,
      },
    };
    getQueryList(queryPar).then((res: any) => {
      let systemType = res.data.SYSTEMTYPE;
      if (systemType != "" && systemType != "ERP") {
        proxy.$ElMessage.warning("该单据是虚拟单据，请确认！！！");
        return;
      }
    });
    // 查询PO Detail
    let queryPar1 = {
      queryId: "GetInvoiceInformation",
      version: "00001",
      params: {
        SITENAME: localStorage.get("siteName"),
        RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,
      },
    };
    getQueryList(queryPar1).then((res: any) => { });
  }
}
async function resetQuery() {
  if (state.column.length > 0) {
    state.button_state = true
    state.ChangeParams.header.MESSAGENAME = 'NormalStockInForSDK'
    state.ChangeParams.header.EventUser = localStorage.get('userId')
    var dateObj = new Date(state.ChangeParams.body.RECEIVETIME);
    state.ChangeParams.body.RECEIVETIME = formatDate(dateObj);
    state.ChangeParams.body.SITENAME = "SDK";
    for (let item of state.column) {
      state.ChangeParams.body.RECEIVEACTNO = item.RECEIVEACTNO;
      state.ChangeParams.body.RECEIVEREQUESTNAME = item.RECEIVEREQUESTNAME;
    }
    if (state.MATERIALRECEIVEACT.length > 0) {
      state.ChangeParams.header.MESSAGENAME = 'NormalStockInForSDK'
      state.ChangeParams.header.EventUser = localStorage.get('userId')
      var dateObj2 = new Date(state.ChangeParams.body.RECEIVETIME);
      state.ChangeParams.body.RECEIVETIME = formatDate(dateObj2);
      state.ChangeParams.body.SITENAME = "SDK";
      state.ChangeParams.body.RECEIVEACTNO = state.queryParams.params.RECEIVEACTNO
      state.ChangeParams.body.RECEIVEREQUESTNAME = state.MATERIALRECEIVEACT[0].RECEIVEREQUESTNAME
      await BpelEvent(state.ChangeParams).then((res: any) => {
        if (IFTRUE(res)) {
          state.MATERIALRECEIVEACT = []
          SelectReceiveAct();
          ElMessageBox.alert("入库成功", '', {
            confirmButtonText: 'OK',
          })
        } else {
          ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
            confirmButtonText: 'OK',
          })
        }
      }).catch((error: any) => {
        console.log(error + "*************************");
        if (error.code == 'UndefinedCode') {
          ElMessageBox.alert(error.msg, '', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: 'OK',
          })
        }
        ElMessageBox.alert(error, '', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
        })
      }).catch((exception: any) => {
        console.error(exception.toString());
        ElMessageBox.alert(exception, '提示框', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
        })
      });
      state.button_state = false
    } else {
      ElMessageBox.alert('请勾选入库任务！', '提醒框', {})

    }
    state.button_state = false
  }
  state.button_state = false
}


/**************************************************公共方法************************************************/
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;
}
</script>

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

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