<template>
	<div class="filterDiv">
		<div>
				产品：
				<el-select v-model="productIdList" multiple collapse-tags collapse-tags-tooltip placeholder="可多选" style="width: 240px" >
					<el-option v-for="item in productList" :key="item.Id" :label="item.Name" :value="item.Id" />
				</el-select>
		</div>
		<div>
			批次：
			<el-input v-model="batchId" clearable wid placeholder="批次号" style="width: 150px;" />
		</div>
		<div>
			日期：
			<el-date-picker
				v-model="queryDate"
				type="daterange"
				align="right"
				unlink-panels
				range-separator="至"
				start-placeholder="开始日期"
				end-placeholder="结束日期"
				:picker-options="pickerOptions">
			</el-date-picker>
		</div>
		<div>
			<el-button type="primary" @click="onClickQuery">查询</el-button>
			<el-button type="success" @click="loadData(true)">导出</el-button>
		</div>
	</div>
	<el-table :data="dataList" @selection-change="handleSelectionChange" stripe style="width: 100%" >
		<el-table-column fixed type="index" width="50" />
		<el-table-column fixed prop="Name" label="产品名称" />
		<el-table-column fixed prop="Code" label="料号" />
		<el-table-column fixed prop="BatchId" label="批次号"/>
		<el-table-column align="right" prop="Total" label="检测数量" width="100" />
		<el-table-column align="right" prop="Qualified" label="合格数量" width="80" />
		<el-table-column align="right" prop="Qualified" label="合格率" width="80">
				 <template v-slot="scope">{{ formatQualifiedRatio(scope.row) }}%</template>
		</el-table-column>
	</el-table>
	<div class="paging">
    <el-pagination
      v-model:current-page="paging.currentPage"
      v-model:page-size="paging.pageSize"
      :page-sizes="[10, 15, 20, 30, 50, 100]"
      :small="true"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paging.totalCount"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
const { isDark, toggleDark } = useDarks()
const { formatTableDateTime,formatTableDate,formatDateTime,formatDate,formatNum,show_loading,close_loading }= utils()
import { exportJsonToExcel } from "../utils/exportExcel.js";
import XLSX from "xlsx"
import {query_table,getReport_Qualified} from '../api/api.ts'

const queryDate=ref([])
const productIdList=ref([])
const qualifiedValue = ref('')

const dataList = ref([])
const productList=ref([])

const batchId=ref('')
const paging=reactive({
	currentPage:1,//当前页
	pageSize:10,//每页条目数
	totalCount:0,//总条目数
})
const pickerOptions={
	shortcuts: [{
		text: '最近一周',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近一个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近三个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			picker.$emit('pick', [start, end]);
		}
	}]
}
//
onMounted(async () => {
		console.log("onMounted - DOM挂载完毕");
		queryDate.value[0]=queryDate.value[1]=new Date()
		await getFiltersData()
		loadData()
})

const handleSizeChange=(val) => {
	console.log(`每页 ${val} 条`);
	loadData()
}
const handleCurrentChange=(val) => {
	console.log(`当前页: ${val}`);
	loadData()
}

const getFiltersData =async () => {
	await query_table({ model:'product', fields:'*',order:'Name'}).then(res=>{
		console.log('getProductList',res)
		if(res.code===200) productList.value.push(...res.data)
	})
	// await query_table({ model:'step', fields:'*',order:'Name'}).then(res=>{
	// 	console.log('getStepList',res)
	// 	if(res.code===200) stepList.value.push(...res.data)
	// })
}
const loadData = (isExport=false) => {
	show_loading()
	const req={
		// model:'order',
		// fields:'Name,Code,BatchId,BatchId,Qualified,Total',
		domain:[],
		order:'',//a.BatchId desc
		pageNum:isExport?0:paging.currentPage,
		pageSize:isExport?0:paging.pageSize,
	}
	if(queryDate.value && queryDate.value.length>0){//0-等于 3-大于等于  5-小于等于 6-IN "CSharpTypeName":"int"
		console.log(queryDate.value)
		req.domain.push({"FieldName": "a.CreateTime","FieldValue": formatDate(queryDate.value[0]),"ConditionalType": 3})
		req.domain.push({"FieldName": "a.CreateTime","FieldValue": formatDate(queryDate.value[1])+' 23:59:59',"ConditionalType": 5})
	}
	if(productIdList.value.length>0){
		var values=''
		for (let key in productIdList.value)
		  values+=productIdList.value[key]+','
		req.domain.push({"FieldName": "a.ProductId","FieldValue": values,"ConditionalType": 6})
	}
	if(batchId.value){
		req.domain.push({"FieldName": "a.BatchId","FieldValue": batchId.value,"ConditionalType": 0})
	}
	console.log(req)

	//
	getReport_Qualified(req).then(res=>{
		console.log('getOrderList',res)
		if(res.code!==200){
			close_loading()
			ElMessage({
				message: res.data,
				type: 'error',
				showClose:true,
				duration: 1000,//自动关闭时间
			})
			return
		}

		//
		const resDataList=JSON.parse( res.data)
		//替换外键名称
		// var rowIndex
		// for(rowIndex=0;rowIndex<resDataList.length;rowIndex++){
		// 	var info=productList.value.find(m=>m.Id===resDataList[rowIndex].ProductId)
		// 	if(info) {
		// 		resDataList[rowIndex].ProductName = info.Name
		// 		resDataList[rowIndex].ProductCode = info.Code
		// 	}

		// 	info=stepList.value.find(m=>m.Id===resDataList[rowIndex].StepId)
		// 	if(info) resDataList[rowIndex].StepName = info.Name
		// }

		console.log('isExport=',isExport)
		if(!isExport){
			dataList.value=resDataList
			paging.totalCount=res.totalCount
			close_loading()
		}
		else
			exExcel(resDataList)
	})
}
const onClickQuery=()=>{
	paging.currentPage=1
	loadData()
}
const exExcel = (datas) => {
	if(datas.length<1){
		close_loading()
		return
	}
	datas.forEach(data=>{
		data.CreateTime=formatDateTime(data.CreateTime)
		data.QualifiedRatio=formatQualifiedRatio(data)+'%'
	})
	const tableField = [
		"Name","Code","BatchId","Qualified","Total","QualifiedRatio"
	]
	const tableHeader = {
		Name: "产品名称",
		Code: "料号",
		BatchId: "批次号",
		Qualified:"合格数量",
		Total:"总数量",
		QualifiedRatio:"合格率",
	}
	//
	exportJsonToExcel({
		header: tableHeader,
		keys: tableField,
		data: datas,
		title: "",
		filename: queryDate.value[0]?formatDate(queryDate.value[0]): "生产报表",
		autoWidth: true,
	});
	ElMessage({ message: "生成中，请稍等...", type: 'success', showClose:true, duration: 2000})
	close_loading()
};

const formatQualifiedRatio=(row)=> {
	return parseInt( row.Qualified/row.Total*100)
}
</script>

<style scoped>
	.filterDiv{
		/* background-color: azure; */
		border-bottom:1px solid #CDD0D6;
		margin: 0px;
		padding-bottom: 10px;
		width: 100%;
		display: flex;
		justify-content:space-around;
	}
	.paging{
		margin: 10px;
		width: 100%;
/* 		display: flex;
		justify-content: flex-end; */
	}
</style>
