<template>
	<view class="container">
		<div style="display: flex;flex-direction: column;height: 100%">
			<div style="display: flex;">
				<button type="primary" style="width:100%;margin-bottom: 10px;margin-left:0px" @click="helpRef.open()">
					使用说明
				</button>
				<button type="primary" style="width:100%;margin-bottom: 10px;" @click="viewExplam">
					{{ isMockData ? '清除' : '查看' }}示例
				</button>
				
				<button type="primary" style="width:100%;margin-bottom: 10px;" @click="switchRoles">
					交换势力
				</button>
				
				<button type="primary" style="width:100%;margin-bottom: 10px;margin-right: 0px;" @click="calculateBestMatch">
					匹配方案
				</button>
			</div>

			<view class="u-table" style="max-height: calc(100vh - 550px)">
				<view class="u-table-tr">
					<view class="u-table-th" style="width: 40px; border-bottom: 0;position: relative;">
						<div style="position: absolute;top:30px">顺序</div>
					</view>

					<view class="u-table-th" style="flex: 1">
						<div style="display: flex;justify-content: space-between;width: 100%">
							目标
							<button style="margin-top: -6px" class="edit-btn" @click="editRow('公', '目标')">
								<uni-icons style="color: #409eff" size="14" type="compose" />
							</button>
						</div>
					</view>

					<view class="u-table-th" style="flex: 1">
						<div style="display: flex;justify-content: space-between;width: 100%">
							备选
							<button style="margin-top: -6px" class="edit-btn" @click="editRow('公', '备选')">
								<uni-icons style="color: #409eff" size="14" type="compose" />
							</button>
						</div>
					</view>
				</view>

				<view class="u-table-tr">
					<view class="u-table-th" style="width: 40px;border-top:0px" />
					<view style="display: flex;flex: 1">
						<view class="u-table-th" style="flex: 1">
							<div style="display: flex;justify-content: space-between;width: 100%">
								<span>公</span>
								<span>{{ numStat.targetMale }}</span>
							</div>
						</view>
						<view class="u-table-th" style="flex: 1">
							<div style="display: flex;justify-content: space-between;width: 100%">
								<span>母</span>
								<span>{{ numStat.targetFemale }}</span>
							</div>
						</view>
					</view>

					<view style="display: flex;flex: 1">
						<view class="u-table-th" style="flex: 1">
							<div style="display: flex;justify-content: space-between;width: 100%">
								<span>公</span>
								<span>{{ numStat.backupMale }}</span>
							</div>
						</view>
						<view class="u-table-th" style="flex: 1">
							<div style="display: flex;justify-content: space-between;width: 100%">
								<span>母</span>
								<span>{{ numStat.backupFemale }}</span>
							</div>
						</view>
					</view>
				</view>

				<view class="u-table-body">
					<view class="u-table-tr" v-for="(item, index) in inputData" :key="index">
						<view class="u-table-td" style="width: 40px">{{ index + 1 }}</view>
						<view style="display: flex;flex: 1">
							<view class="u-table-td" style="flex: 1">
								{{ item.targetMale }}
							</view>
							<view class="u-table-td" style="flex: 1">
								{{ item.targetFemale }}
							</view>
						</view>

						<view style="display: flex;flex: 1">
							<view class="u-table-td" style="flex: 1">
								{{ item.backupMale }}
							</view>
							<view class="u-table-td" style="flex: 1">
								{{ item.backupFemale }}
							</view>
						</view>
					</view>
				</view>


				<view class="u-table-body" v-if="inputData.length === 0"
					style="color:#909399; padding: 15px;display: flex;justify-content: center;border:1px solid #ebeef5;margin-top:-1px">
					暂无数据，请添加猫咪势力
				</view>
			</view>
		</div>



		<!-- 输出表格 -->
		<view class="section" v-if="outputData.length > 0" style="flex: 1;margin-bottom: 0px">
			<div style="display: flex;justify-content: space-between;margin-top:10px">
				<text class="section-title">最佳方案</text>
				<span>差额: {{ powerDifference }}</span>
			</div>


			<view class="u-table" :style="`max-height: calc(550px - 220px)`">
				<view class="u-table-tr">
					<view class="u-table-th" style="width: 40px; border-bottom: 0;position: relative;">
						<div style="position: absolute;top:30px">顺序</div>
					</view>

					<view class="u-table-th" style="flex: 1">
						<div style="display: flex;justify-content: space-between;width: 100%">
							目标

						</div>
					</view>

					<view class="u-table-th" style="flex: 1">
						<div style="display: flex;justify-content: space-between;width: 100%">
							备选
						</div>
					</view>
				</view>

				<view class="u-table-tr">
					<view class="u-table-th" style="width: 40px;border-top:0px" />
					<view style="display: flex;flex: 1">
						<view class="u-table-th" style="flex: 1">
							<span>公</span>
						</view>
						<view class="u-table-th" style="flex: 1">
							<span>母</span>
						</view>
					</view>

					<view style="display: flex;flex: 1">
						<view class="u-table-th" style="flex: 1">
							<span>公</span>

						</view>
						<view class="u-table-th" style="flex: 1">
							<span>公</span>
						</view>
					</view>
				</view>


				<view class="u-table-body">
					<view class="u-table-tr" v-for="(item, index) in outputData" :key="index">
						<view class="u-table-td" style="width: 40px">{{ index + 1 }}</view>
						<view style="display: flex; flex: 1">
							<view class="u-table-td" style="flex: 1">
								{{ item.targetMale }}
							</view>
							<view class="u-table-td" style="flex: 1">
								{{ item.targetFemale }}
							</view>
						</view>
					
						<view style="display: flex;flex: 1">
							<view class="u-table-td" style="flex: 1">
								{{ item.backupMale }}
							</view>
							<view class="u-table-td" style="flex: 1">
								{{ item.backupFemale }}
							</view>
						</view>
					</view>
					
					<view class="u-table-tr">
						<view class="u-table-th" style="width: 40px">合计</view>
						<view class="u-table-th" style="display: flex;flex: 1;justify-content: center;">
							{{ totalTarget }}
						</view>
					
						<view class="u-table-th" style="display: flex;flex: 1;justify-content: center;">
							{{ totalBackup }}
						</view>
					</view>
				</view>
			</view>
			<!-- <uni-table border stripe emptyText="暂无更多数据">
				<uni-tr>
					<uni-th width="60px" rowspan="2">顺序</uni-th>
					<uni-th align="left" colspan="2" width="120px">目标</uni-th>
					<uni-th align="left" colspan="2" width="120px">备选</uni-th>
				</uni-tr>

				<uni-tr>
					<uni-th align="left" width="60px">目标</uni-th>
					<uni-th align="left" width="60px">备选</uni-th>
					<uni-th align="left" width="60px">目标</uni-th>
					<uni-th align="left" width="60px">备选</uni-th>
				</uni-tr>

				<uni-tr v-for="(item, index) in outputData" :key="index">
					<uni-td>{{ index + 1 }}</uni-td>
					<uni-td>{{ item.targetMale }}</uni-td>
					<uni-td>{{ item.targetFemale }}</uni-td>
					<uni-td>{{ item.backupMale }}</uni-td>
					<uni-td>{{ item.backupFemale }}</uni-td>
				</uni-tr>

				<uni-tr>
					<uni-td>合计</uni-td>
					<uni-td colspan="2">{{ totalTarget }}</uni-td>
					<uni-td colspan="2">{{ totalBackup }}</uni-td>
				</uni-tr>
			</uni-table> -->
		</view>


		<uni-popup ref="batchRef" :is-mask-click="false">
			<div
				style="display: flex;flex-direction: column;justify-content: center;padding: 10px; width: 95%;background: #fff;border-radius: 10px;padding: 10px;">
				<div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
					<span></span>
					<h4 style="margin-bottom: 10px"> 编辑{{ role }}</h4>
					<uni-icons type="closeempty" size="18" @click="batchRef.close()"></uni-icons>
				</div>


				<div style="display: flex;justify-content: space-between; align-items: center;">
					<span class="dialog-title">猫咪势力(公)</span>
					<uni-icons type="close" size="18" @click="malePowers = ''"></uni-icons>
				</div>

				<textarea v-model="malePowers" placeholder="用逗号或顿号隔开，如:200,150,100"
					style="height: 70px;border: 1px solid #dfe2e5" />

				<div style="display: flex;justify-content: space-between; align-items: center;">
					<span class="dialog-title">猫咪势力(母)</span>
					<uni-icons type="close" size="18" @click="feMalePowers = ''"></uni-icons>
				</div>

				<textarea v-model="feMalePowers" placeholder="用逗号或顿号隔开，如:200,150,100"
					style="height: 70px;border: 1px solid #dfe2e5" />

				<button size='mini' type="primary" @click="handleConfirm">保存</button>
			</div>
		</uni-popup>


		<uni-popup ref="messageRef" type="message">
			<uni-popup-message type="error" :message="messageText" :duration="5000"></uni-popup-message>
		</uni-popup>
		
		
		<uni-popup  ref="helpRef" :is-mask-click="false">
			<div class="help-modal" style="display: flex; justify-content: center;flex-direction: column;padding: 10px; width: 90vw;background: #fff;border-radius: 10px;padding: 30px;box-sizing: border-box;">
				<div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
					<span></span>
					<h4 style="margin-bottom: 10px">使用说明</h4>
					<uni-icons type="closeempty" size="18" @click="helpRef.close()"></uni-icons>
				</div>
				
				<div style="margin-bottom: 10px;">
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;“喵缘礼堂”是一款专注于为猫咪结婚提供解决方案的应用。它以所有目标角色猫咪的势力总和作为基准，通过筛选备选角色猫咪，为用户匹配出其势力总和最接近目标角色猫咪势力总和的方案。
				</div>
				
				<div>
					<p style="font-weight: bold;margin-bottom: 10px">使用方法：</p>
					<p style="margin-bottom: 10px">1.录入目标猫咪势力数据，总数≤20 只，依次准确填写。</p>
					<p style="margin-bottom: 10px">2.输入备选猫咪势力数据，不同性别数均≤20 只，详细填写。</p>
					<p>3.点击 “计算最佳匹配方案”，系统将据此算出最适配方案。</p>
				</div>
			</div>
		</uni-popup>




		<div class="loading" v-if="loading">
			<div class="loading-wrapper">
				<image src="./cat-load.gif" style="width:260px;height:260px" />
			</div>
		</div>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';


const isMockData = ref(false)
const loading = ref(false)
const helpRef = ref(null)
const messageRef = ref(null)
const messageText = ref('')
const time = ref("")
const role = ref("")
const type = ref('')
const gender = ref("")
const powers = ref("")
const malePowers = ref('')
const feMalePowers = ref('')

const windowHeight = ref(0)

const totalTarget = ref(0)
const totalBackup =  ref(0)

uni.getSystemInfo({
	success(info){ windowHeight.value = info.windowHeight  / 2}
})
	
	
const numStat = computed(() => {
	const stat = {
		targetMale: 0,
		targetFemale: 0,
		backupMale: 0,
		backupFemale: 0
	}
	
	inputData.value.forEach(item => {
		stat.targetMale += item.targetMale ? 1 : 0
		stat.targetFemale += item.targetFemale ? 1 : 0
		stat.backupMale += item.backupMale ? 1 : 0
		stat.backupFemale += item.backupFemale ? 1 : 0
	})
	
	return stat
})



const mockData = [
    {
        "targetMale": "153",
        "targetFemale": "121",
        "backupMale": "174",
        "backupFemale": "180"
    },
    {
        "targetMale": "138",
        "targetFemale": "118",
        "backupMale": "152",
        "backupFemale": "165"
    },
    {
        "targetMale": "91",
        "targetFemale": "115",
        "backupMale": "147",
        "backupFemale": "158"
    },
    {
        "targetMale": "90",
        "targetFemale": "86",
        "backupMale": "102",
        "backupFemale": "154"
    },
    {
        "targetMale": "80",
        "targetFemale": "84",
        "backupMale": "101",
        "backupFemale": "152"
    },
    {
        "targetMale": "77",
        "targetFemale": "84",
        "backupMale": "98",
        "backupFemale": "151"
    },
    {
        "targetMale": "60",
        "targetFemale": "59",
        "backupMale": "98",
        "backupFemale": "150"
    },
    {
        "targetMale": "54",
        "targetFemale": "53",
        "backupMale": "97",
        "backupFemale": "150"
    },
    {
        "targetMale": "52",
        "targetFemale": "51",
        "backupMale": "62",
        "backupFemale": "102"
    },
    {
        "targetMale": "52",
        "backupMale": "60",
        "backupFemale": "101"
    },
    {
        "targetMale": "52",
        "backupMale": "58",
        "backupFemale": "101"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": "19",
        "backupFemale": "93"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "61"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "30"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "30"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "29"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "29"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "29"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "27"
    },
    {
        "targetMale": null,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": "10"
    }
]

const mockOutData = [
    {
        "targetMale": 153,
        "targetFemale": 121,
        "backupMale": 102,
        "backupFemale": 180
    },
    {
        "targetMale": 138,
        "targetFemale": 118,
        "backupMale": 101,
        "backupFemale": 165
    },
    {
        "targetMale": 91,
        "targetFemale": 115,
        "backupMale": 98,
        "backupFemale": 158
    },
    {
        "targetMale": 90,
        "targetFemale": 86,
        "backupMale": 98,
        "backupFemale": 154
    },
    {
        "targetMale": 80,
        "targetFemale": 84,
        "backupMale": 97,
        "backupFemale": 101
    },
    {
        "targetMale": 77,
        "targetFemale": 84,
        "backupMale": 62,
        "backupFemale": 93
    },
    {
        "targetMale": 60,
        "targetFemale": 59,
        "backupMale": 60,
        "backupFemale": 29
    },
    {
        "targetMale": 54,
        "targetFemale": 53,
        "backupMale": 58,
        "backupFemale": 29
    },
    {
        "targetMale": 52,
        "targetFemale": 51,
        "backupMale": 19,
        "backupFemale": 29
    },
    {
        "targetMale": 52,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": 27
    },
    {
        "targetMale": 52,
        "targetFemale": null,
        "backupMale": null,
        "backupFemale": 10
    }
]


const inputData = ref([]);
const outputData = ref([]);

const batchRef =  ref(null)


const arraySpanMethod = ({
	row,
	column,
	rowIndex,
	columnIndex,
}) => {
	if (rowIndex % 2 === 0) {
		if (columnIndex === 0) {
			return [1, 2]
		} else if (columnIndex === 1) {
			return [0, 0]
		}
	}
}

function viewExplam(){
	
	if(!isMockData.value){
		inputData.value = JSON.parse(JSON.stringify(mockData))
		outputData.value  = JSON.parse(JSON.stringify(mockOutData))
		totalTarget.value = 1670
		totalBackup.value = 1670
	} else {
		inputData.value  = []
		outputData.value = []
		totalTarget.value = 0
		totalBackup.value = 0
	}
	
	isMockData.value = !isMockData.value
}


function editRow(_gender, _role) {
	console.log(1,2,3,4);
	
	type.value = 'edit'
	gender.value = _gender
	role.value = _role
	
	const roleProp = role.value === '目标' ? 'target' : 'backup'
	malePowers.value = inputData.value.map(item => item[`${roleProp}Male`]).filter(item => !!item).join(',')
	feMalePowers.value = inputData.value.map(item => item[`${roleProp}Female`]).filter(item => !!item).join(',')
	batchRef.value.open()
}


function switchRoles(){
	outputData.value = []
	const backups = inputData.value.map(item => ({ male: item.backupMale, female: item.backupFemale }))
	const targets = inputData.value.map(item => ({ male: item.targetMale, female: item.targetFemale }))
	
	inputData.value = inputData.value.map((_, index) => ({
		backupFemale: targets[index]?.female || null,
		backupMale: targets[index]?.male || null,
		targetFemale: backups[index]?.female || null,
		targetMale: backups[index]?.male || null,
	}))
}

const powerDifference = ref(0)

function isPositiveInteger(str) {
    return /^[1-9]\d*$/.test(str);
}

function generatePowers(_powers, gender){
	const keys = ['targetMale', 'targetFemale', 'backupMale', 'backupFemale']
	_powers = _powers.replace(/，|、|,/g, ',')
	let powerSet = _powers.split(',').map(item => item.trim()).filter(item => item !== '')
	const isOk = powerSet.every(num => isPositiveInteger(num))
	if (!isOk && powerSet.length !== 0) return false
	
	powerSet.sort((a,b) => b - a)
	
	const roleProp = role.value === '目标' ? 'target' : 'backup'
	const genderProp = gender === '公' ? 'Male' : 'Female'
	inputData.value.forEach((_, index) => { inputData.value[index][`${roleProp}${genderProp}`] = null })

	const prop = `${roleProp}${genderProp}`
	const values = inputData.value.map(item => item[prop]).filter(value => value);

	if (inputData.value.length === 0) {
		for (let index = 0; index < powerSet.length; index++) {
			const item = {}
			keys.forEach(key => {
				if (key === prop) {
					item[key] = powerSet[index]
				} else {
					item[key] = null
				}
			})

			inputData.value.push(item)
		}

	} else if (values.length < inputData.value.length) {
		let pIndex = -1
		for (let index = values.length; index < inputData.value.length; index++) {
			pIndex += 1
			inputData.value[index][prop] = powerSet[pIndex]
		}

		const calcNum = powerSet.length - (pIndex + 1)

		for (let index = 0; index < calcNum; index++) {
			pIndex += 1
			const item = {}

			keys.forEach(key => {
				if (key === prop) {
					item[key] = powerSet[pIndex]
				} else {
					item[key] = null
				}
			})

			inputData.value.push(item)
		}
	}

	inputData.value = inputData.value.filter(item => {
		if(!item.backupFemale && !item.backupMale && !item.targetFemale && !item.targetMale){
			return false
		}
		
		return true
	})
}


function handleConfirm(){	
	const _malePowers = malePowers.value.trim()
	const _feMalePowers = feMalePowers.value.trim()

	const isMaleOk = generatePowers(_malePowers, '公')
	const isFemakeOk = generatePowers(_feMalePowers, '母')
	
	if(typeof isMaleOk === 'boolean' && !isMaleOk){
		messageRef.value.open()
		messageText.value = '势力必须为数字'
		return
	}	else if(typeof isFemakeOk === 'boolean' && !isFemakeOk){
		messageRef.value.open()
		messageText.value = '势力必须为数字'
		return
	}
	
	outputData.value = []
	batchRef.value.close()
}

// 生成数组的所有组合（辅助函数，用于生成指定个数元素的组合情况）
function getCombinations(arr, num) {
    const result = [];
	if (num === 0) { return [[]]; }


    for (let i = 0; i < arr.length; i++) {
        const element = arr[i];

        const remainingCombos = getCombinations(arr.slice(i + 1), num - 1);

		for (const combo of remainingCombos) {
            result.push([element].concat(combo));
        }
    }

    return result;
}


async function calculateBestMatch() {
	if(outputData.value.length !== 0){
		messageRef.value.open()
		messageText.value = '请编辑猫咪势力后,再匹配方案'
		return
	}
	

			
	outputData.value = []

	const targetData = []
	const backupData = []

	inputData.value.forEach(item => {
		if (item.targetMale) { targetData.push({ gender: '公', power: item.targetMale }) }
		if (item.targetFemale) { targetData.push({ gender: '母', power: item.targetFemale }) }
		if (item.backupMale) { backupData.push({ gender: '公', power: item.backupMale }) }
		if (item.backupFemale) { backupData.push({ gender: '母', power: item.backupFemale }) }
	})


	const targetMale = targetData.filter(item => item.gender === '公').map(item => Number(item.power));
	const targetFemale = targetData.filter(item => item.gender === '母').map(item => Number(item.power));
	const backupMale = backupData.filter(item => item.gender === '公').map(item => Number(item.power));
	const backupFemale = backupData.filter(item => item.gender === '母').map(item => Number(item.power));
	// const targetMale = [153, 91, 77, 138, 90, 80, 60, 54, 52, 52, 52];
	// const targetFemale = [121, 118, 115, 86, 84, 84, 59, 53, 51];
	// const backupMale = [180, 165, 158, 154, 152, 151, 150, 150, 102, 101, 101, 93, 61, 30, 30, 29, 29, 29, 27, 10, 10];
	// const backupFemale = [174, 152, 147, 102, 101, 98, 98, 97, 62, 60, 58, 19]; 

	// const targetMale = [238, 90, 90];
	// const targetFemale = [86, 84, 84];
	// const backupMale = [153, 91, 77];
	// const backupFemale = [121, 118, 115]; 
	

	if (targetMale.length === 0 && targetFemale.length === 0) {
		messageRef.value.open()
		messageText.value = '目标公数据与母数据不能同时为空'
		return
	}

	if (targetFemale.length + targetFemale.length > 20) {
		messageRef.value.open()
		messageText.value = '目标公数据与母数据的和不能超过20条'
		return
	}

	if (backupMale.length > 20) {
		messageRef.value.open()
		messageText.value = '备选的公数据不能超过20条'
		return
	}

	if (backupFemale.length > 20) {
		messageRef.value.open()
		messageText.value = '备选的母数据不能超过20条'
		return
	}


	if (targetFemale.length > backupMale.length && backupMale.length !== 0) {
		messageRef.value.open()
		messageText.value = '备选的公数据长度必须大于或等于目标的母数据'
		return
	}

	if (targetMale.length > backupFemale.length && backupFemale.length !== 0) {
		messageRef.value.open()
		messageText.value = '备选的母数据长度必须或等于大于目标的公数据'
		return
	}
	
	
	loading.value = true
	await handleData(targetMale, targetFemale, backupMale, backupFemale)
	loading.value = false
	
}


function stop(delay){
	return new Promise((resolve) => setTimeout(() => {resolve(true)}, delay) )
}


 function handleData(targetMale, targetFemale, backupMale, backupFemale){
	return new Promise((resolve) => {
		setTimeout(async () => {
			let startTime = new Date().getTime()
			let endTime = null
			const targetMaleLen = targetMale.length;
			const targetFemaleLen = targetFemale.length;
			
			
			let targetWeight = 0
			if (backupMale.length === 0){
				targetWeight =  targetMale.reduce((acc, val) => acc + val, 0);
			
			} else if(backupFemale.length === 0){
				targetWeight = targetFemale.reduce((acc, val) => acc + val, 0)
			
			} else if(backupMale.length !== 0 && backupFemale.length !== 0){
				targetWeight = targetMale.reduce((acc, val) => acc + val, 0) + targetFemale.reduce((acc, val) => acc + val, 0);
			}
			
			let minDifference = Infinity; 
			let bestfemaleCombination = null;
			let bestMaleCombination = null;
			const femaleCombinations = getCombinations(backupFemale, targetMaleLen);
			const maleCombinations = getCombinations(backupMale, targetFemaleLen);
			
			if (femaleCombinations.length !== 0 && maleCombinations.length !== 0){
				for (const femaleComb of femaleCombinations) {
					for (const maleComb of maleCombinations) {
						const totalWeight = femaleComb.reduce((acc, val) => acc + val, 0) + maleComb.reduce((acc, val) => acc + val, 0);
						const difference = Math.abs(totalWeight - targetWeight);
						if (difference < minDifference) {
							minDifference = difference;
							bestfemaleCombination = femaleComb;
							bestMaleCombination = maleComb;
							if (minDifference == 0) {
								break;
							}
						}
					}
				}
			}
			
			
			// 备选数据的母为空
			if (femaleCombinations.length === 0 && maleCombinations.length !== 0) {
				for (const maleComb of maleCombinations) {
					const totalWeight = maleComb.reduce((acc, val) => acc + val , 0);
					const difference = Math.abs(totalWeight - targetWeight);
					if (difference < minDifference) {
						minDifference = difference;
						bestMaleCombination = maleComb;
						if (minDifference == 0) { break; }
					}
				}
			}
			
			// 备选数据的公为空
			if (femaleCombinations.length !== 0 && maleCombinations.length === 0) {
				for (const femaleComb of femaleCombinations) {
						const totalWeight = femaleComb.reduce((acc, val) => acc + val, 0)
						const difference = Math.abs(totalWeight - targetWeight);
						if (difference < minDifference) {
							minDifference = difference;
							bestfemaleCombination = femaleComb;
							if (minDifference == 0) { break; }
						}
				}
			}
			
			powerDifference.value = totalTarget.value - totalBackup.value
			endTime = new Date().getTime()
			time.value = endTime - startTime
			
			const delay = 5000 - time.value
			if(delay > 0){ await stop(delay) }
			
			
			bestMaleCombination && bestMaleCombination.sort((a, b) => b - a)
			bestfemaleCombination && bestfemaleCombination.sort((a, b) => b - a)
			targetMale.sort((a, b) =>  b - a)
			targetFemale.sort((a, b) =>  b - a)
			
			if (!bestMaleCombination && !bestfemaleCombination){ return }
			
			
			bestfemaleCombination && targetMale.forEach((_, index) => {
				outputData.value.push({
					targetMale: targetMale[index],
					targetFemale: null,
					backupMale: null,
					backupFemale: bestfemaleCombination[index]
				})
			})
			
			const fl = targetFemale.length
			
			for(let index = 0; index < fl; index ++){
				if(outputData.value[index]){
					outputData.value[index].targetFemale = targetFemale[index]
					outputData.value[index].backupMale = bestMaleCombination[index]
				} else {
					outputData.value.push({
						targetMale: null,
						targetFemale: targetFemale[index],
						backupMale: bestMaleCombination[index],
						backupFemale: null
					})
					
				}
			}
			
			
			totalTarget.value = outputData.value.reduce((prev, current) => prev + current.targetMale, 0) + outputData.value.reduce((prev, current) => prev + current.targetFemale, 0)
			totalBackup.value = outputData.value.reduce((prev, current) => prev + current.backupMale, 0) + outputData.value.reduce((prev, current) => prev + current.backupFemale, 0)
			resolve(time.value)
		}, 0)
	})
}
</script>

<style>
	.help-modal {
		line-height: 24px;
		color: #2c3e50;
	}
	
.u-table{
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 80px;
	justify-content: flex-start;
	font-size: 14px !important;
	height: auto;

	border-top: 1px solid #ebeef5;
	border-left: 1px solid #ebeef5;
	/* background: red */
}

.u-table-tr {
	display: flex;
	color: #909399;
	height: 40px !important;
	margin-top: -1px;
}

.u-table-body {
	height: calc(100% - 80px);
	overflow: auto;
}


.u-table-th {
	display: flex;
	border: 1px solid #ebeef5;
	padding: 8px 10px;
	margin-left: -1px;
	font-weight: bold;
}


.u-table-td {
	display: flex;
	border: 1px solid #ebeef5;
	padding: 8px 10px;
	margin-left: -1px;
}


.u-table-th-custom {
	display: flex;
	border: 1px solid #ebeef5;
	margin-left: -1px;
}

	
.edit-btn {
	padding: 0px !important;
	border: 0px !important;
	display: block;
	background: #fff !important;
}

.edit-btn:after {
	border: 0px !important;
}


@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loader {
  animation: spin 2s linear infinite; /* 应用旋转动画 */
}

textarea {
	font-size: 13px;
	padding: 8px;
}
</style>

<style lang="scss" scoped>


button {
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	padding: 0px !important;
	text-wrap: nowrap !important;
}


.dialog-title {
	line-height: 30px;
	padding-left: 10px;
	font-size: 14px;
}


.table-wrapper {
	font-size: 14px !important;
}


.custom-picker {
    border: 1px solid #e3e3e3;
    padding: 3px 5px;
    text-align: center;
	width: 100%;
	
    
    div {
        display: flex;
        justify-content: space-between;
        
        text {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
}

.container {
    padding: 10px 20px;
	display: flex;
	flex-direction: column;
}

.section {
    margin-bottom: 20px;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
}

.input {
    width: 100%;
    text-align: center;
    border: 1px solid #ddd;
    padding: 5px;
}

button {
    margin: 5px;
}

.add-btn,
.calculate-btn {
    background-color: #007bff;
    color: white;
    padding: 10px;
    font-size: 16px;
    text-align: center;
    border-radius: 5px;
}

.delete-btn {
    background-color: #ff4d4f;
    color: white;
    padding: 5px;
    font-size: 14px;
    border-radius: 5px;
}

.summary {
    margin-top: 20px;
    font-size: 14px;
    text-align: right;
    font-weight: bold;
}

.hj-table {
	:deep(.el-table__body-wrapper){
		display: none !important;
	}
}

.loading {
	position: fixed;
	top: 0px;
	left: 0px;
	
	width: 100vw;
	height: 100vh;
	
	background: rgba(0,0,0,.6);
	
	display: flex;
	justify-content: center;
	align-items: center;
	
	
	.loading-wrapper {
		height: 260px;
		width: 260px;
		border-radius: 100%;
		overflow:hidden;
		display:flex;
		
		justify-content: center;
		align-items: center;
		
		img {
			height: 260px;
			width: 260px;
		}
	}
}
</style>
