<!--
  功能：功能描述  盘点查询
  作者：陶庆峰
-->
<template>
    <div class="vue-element-page-wrap" ref="tableContainer">
        <el-row class="page-search" justify="space-between" align="bottom">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" :rules="rules" label-width="100px"
                label-position="left">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="盘点计划名" prop="CHECKPLANNAME">
                            <el-Input v-model="queryParams.CHECKPLANNAME" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="组织" prop="ERPFACTORY">
                        <el-select
                            filterable
                            v-model="queryParams.ERPFACTORY"
                            placeholder="下拉选择组织"
                            size="small"
                        >
                            <el-option
                            v-for="item in ERPFactoryList"
                            :key="item.ERPFACTORY"
                            :label="item.DESCRIPTION"
                            :value="item.ERPFACTORY"
                            />
                        </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="开始时间" prop="FROMDATE">
                            <el-date-picker v-model="queryParams.FROMDATE" value-format="YYYYMMDD" type="date"
                                placeholder="开始时间" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="结束时间" prop="TODATE">
                            <el-date-picker v-model="queryParams.TODATE" value-format="YYYYMMDD" type="date"
                                placeholder="结束时间" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="page-search-btns">
                <el-button type="primary" @click="handleQueryInfo">搜索</el-button>
                <el-button @click="exportExcel">导出</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>
            <div> <el-table border v-loading="loading" :data="state.list2" highlight-current-row row-key="id"
                    style="width: 100%;min-height: 100px;height: 200px;"  @row-click="handle">
                    <template v-for="(col, index) in column1" :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-column fixed="right" label="操作" width="180">
                      <template #default="scope">
                        <el-button @click="CheckAudit(scope.row)" type="primary" size="small">提交</el-button>
                      </template>
                    </el-table-column>
                </el-table>
                <pagination v-if="total2 > 0" :total="total2" v-model:pageNumTo="state.pageNum2"
                    v-model:pageSizeTo="state.pageSize2" @pagination="handleQuery2" />
            </div>
            <div>
                <el-table :height="tableHeight" border v-loading="loading" :data="list" highlight-current-row row-key="id" style="width: 100%;min-height: 50px;"
                    >
<!--                  <el-table-column type="selection" width="55" />-->
                    <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-column fixed="right" label="是否参与盘点" width="70">
                      <template #default="scope">
<!--                        <span>{{scope.row.CHECKPLATATE1}}</span>-->
                        <el-button v-if="scope.row.CHECKPLATATE1 == '是'" @click="createMark(scope.row)" type="success" size="small">{{scope.row.CHECKPLATATE1}}</el-button>
                        <el-button v-else @click="createMark(scope.row)" type="primary" size="small">{{scope.row.CHECKPLATATE1}}</el-button>
<!--                        <el-button @click="deleteMark(scope.row)" type="text" size="small">删除标记</el-button>-->
                      </template>
                    </el-table-column>
                </el-table>
                <pagination v-if="total > 0" :total="total" v-model:pageNumTo="pageNum" v-model:pageSizeTo="pageSize"
                    @pagination="handleQuery" />
            </div>

        </div>
        <template>
            <el-upload ref="upload" class="upload-demo"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :limit="1"
                :on-exceed="handleExceed" :auto-upload="false">
                <template #trigger>
                    <el-button type="primary">select file</el-button>
                </template>
                <el-button class="ml-3" type="success" @click="submitUpload">
                    upload to server
                </el-button>
                <template #tip>
                    <div class="el-upload__tip text-red">
                        limit 1 file, new file will cover the old file
                    </div>
                </template>
            </el-upload>
        </template>
    </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from "vue";
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryList, getQueryPageList } from '@/api/common';
import { Auditcheckmark, checkmarkAudit, createcheckmark, deletecheckmark } from '@/api/check'
import exportDataToExcel from "@/utils/export-excel";
import * as XLSX from 'xlsx';
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { localStorage } from '@/utils/storage'
import { bTableHeight } from "../../../composables/calcTableHeight";
import { getORG } from '@/api/auth'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(420);
const queryFormRef = ref(ElForm);

const { proxy }: any = getCurrentInstance();


const state = reactive({
    ERPFactoryList: [] as any, // 组织
    queryParams: {
        CHECKPLANNAME: "",
        FROMDATE: '',
        TODATE: '',
        ERPFACTORY:''
    },
    pageNum: 1,
    pageSize: 10,
    pageNum2: 1,
    pageSize2: 10,
    total: 0,
    total2: 0,
    loading: false,
    list: [],
    list2: [],
    column: [] as any,
    column1: [] as any,
    rules: {
        CHECKPLANNAME: [],
    },
    checkmark : {
      CHECKPLANNAME : '',
      MATERIALPACKINGNAME : '',
      SITENAME : '',
      CHECKPLATATE : ''
    },
  handleSelectionlist : [] as any
});

const { ERPFactoryList,loading, list, column, column1, queryParams, rules, pageNum, pageSize, total, total2 } = toRefs(state)

onMounted(() => {
    state.column = [
        { header: "条码", field: "MATERIALPACKINGNAME", hide: false },
        { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
        { header: "品名", field: "DESC_CN", hide: false },
        { header: "系统仓库", field: "ERPLOCATION", hide: false },
        { header: "实际仓库", field: "ERPLOCATION1", hide: false },
        { header: "仓库异动", field: "LOCATIONSTATE2", hide: false },
        { header: "系统货位", field: "SYSLOCATION", hide: false },
        { header: "实际货位", field: "ACTLOCATION", hide: false },
        { header: "货位异动", field: "LOCATIONSTATE1", hide: false },
        { header: "系统数量", field: "MATERIALQUANTITY1", hide: false },
        { header: "实际数量", field: "MATERIALQUANTITY", hide: false },
        { header: "数量异动", field: "QTYSTATE", hide: false },
        { header: "盘点结果", field: "CHECKRESULT", hide: false },
        // { header: "是否参与盘点审核", field: "IS_ADUIT", hide: false },CHECKPLATATE
        { header: "是否参与盘点审核", field: "CHECKPLATATE", hide: false },
    ],
        state.column1 = [
            { header: "盘点时间", field: "PLANDATE", hide: false },
            { header: "盘点任务", field: "CHECKPLANNAME", hide: false },
            { header: "盘点方式", field: "PLANTYPE", hide: false },
            // { header: "盘点类型", field: "MOVEFLAG", hide: false },
            { header: "盘点类型", field: "PLANTYPENAME", hide: false },
            { header: "盘点状态", field: "CHECKPLANSTATE1", hide: false },
            { header: "计划盘点数量", field: "ALLBOX", hide: false },
            { header: "实际盘点数量", field: "JHBOX", hide: false },

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

function CheckAudit(value : any) {
  console.log(value)
  checkmarkAudit(value).then((res : any) => {

  });
  state.list = [];
  state.queryParams.CHECKPLANNAME = ''
  handleQuery2()
}
//ERP工厂查询
function ERPFactoryQuery() {
  getORG({ orgNo: null })
    .then((res: any) => {
      state.ERPFactoryList = res.resultObj
      state.ERPFactoryList.unshift({
        ERPFACTORY: ''
      })
    })
    .catch(() => {})
}
// function deleteMark(value : any){
//   state.checkmark.CHECKPLANNAME = value.CHECKPLANNAME
//   state.checkmark.MATERIALPACKINGNAME = value.MATERIALPACKINGNAME
//   state.checkmark.SITENAME = value.SITENAME
//   state.checkmark.CHECKPLATATE = value.CHECKPLATATE1
//   deletecheckmark(state.checkmark).then((res : any) => {
//   });
//   handleQuery()
// }
function createMark(value : any){
  state.checkmark.CHECKPLANNAME = value.CHECKPLANNAME
  state.checkmark.MATERIALPACKINGNAME = value.MATERIALPACKINGNAME
  state.checkmark.SITENAME = value.SITENAME
  state.checkmark.CHECKPLATATE = value.CHECKPLATATE1
  createcheckmark(state.checkmark).then((res : any) => {
  });
  handleQuery()
}
function handleQuery() {
    queryFormRef.value.validate((valid: any) => {
        if (valid) {
            state.loading = true;
            let query = {
                queryId: "GetCheckList",
                version: "00005",
                params: {
                    userId: localStorage.get("userId"),
                    SITENAME: 'SDK',
                    CHECKPLANNAME: state.queryParams.CHECKPLANNAME,
                    FROMDATE: state.queryParams.FROMDATE,
                    TODATE: state.queryParams.TODATE,
                },
                pageNum: state.pageNum,
                pageSize: state.pageSize,
            }
            getQueryPageList(query).then((res: any) => {
                state.loading = false;
                state.list = res.data.list;
                for (var i=0;i<state.list.length;i++){
                  if(state.list[i].CHECKPLATATE == null){
                    state.list[i].CHECKPLATATE = '是'
                  }
                  if(state.list[i].MATERIALQUANTITY == null) {
                    state.list[i].MATERIALQUANTITY = '0'
                  }
                  if(state.list[i].CHECKPLATATE == '是'){
                    state.list[i].CHECKPLATATE1 = '否'
                  } else {
                    state.list[i].CHECKPLATATE1 = '是'
                  }
                }
                state.total = res.data.total;
            });
        }
        state.loading = false;
    });
}

function handleQueryInfo() {
  state.pageNum2 = 1
  handleQuery2()
}
function handleQuery2() {
    queryFormRef.value.validate((valid: any) => {
        if (valid) {
            state.loading = true;
            let query = {
                queryId: "GetCheckPlanCode",
                // version: "00002",
                version: "00003",
                params: {
                    SITENAME: 'SDK',
                    CHECKPLANNAME: state.queryParams.CHECKPLANNAME,
                    FROMDATE: state.queryParams.FROMDATE,
                    TODATE: state.queryParams.TODATE,
                    ERPFACTORY : state.queryParams.ERPFACTORY
                },
                pageNum: state.pageNum2,
                pageSize: state.pageSize2,
            }
            getQueryPageList(query).then((res: any) => {
              if(res.data.list.length == 0){
                state.list2 = []
                state.list = []
                ElMessageBox.alert('查无数据', '提醒框', {
                  confirmButtonText: 'OK',
                })

                state.loading = false;
              } else {
                state.loading = false;
                state.list2 = res.data.list;
                state.total2 = res.data.total;
                if(state.list2.length>0)
                {
                
                     handle(state.list2[0],null,null);
                }
                for (var i=0;i<state.list2.length;i++){
                  if(state.list2[i].CHECKPLANSTATE == 'Created'){
                    state.list2[i].CHECKPLANSTATE1 = '创建'
                  } else if(state.list[i].CHECKPLANSTATE == 'Approved'){
                    state.list2[i].CHECKPLANSTATE1 = '审核通过'
                  } else if(state.list[i].CHECKPLANSTATE == 'Audit'){
                    state.list2[i].CHECKPLANSTATE1 = '审核中'
                  }
                }
              }

            });
        }
        state.loading = false;
    });
}
function exportExcel() {
    let query = {
        queryId: "GetCheckList",
        version: "00003",
        params: {
            SITENAME: 'SDK',
            CHECKPLANNAME: state.queryParams.CHECKPLANNAME,
        },
    }
    getQueryList(query).then((res: any) => {
        if (res.data.length > 0) {
            exportDataToExcel(res.data, state.queryParams.CHECKPLANNAME + '盘点结果')
        } else {
            proxy.$ElMessage.warning('当前没有数据可以导出');
        }
    });
}

function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

function handle(row: any, enent: any, clount: any) {
    state.queryParams.CHECKPLANNAME = row.CHECKPLANNAME
    handleQuery()
}

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}

const submitUpload = () => {
    upload.value!.submit()
}
</script>

<style scoped lang="scss"></style>