<script setup lang="ts">
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from 'element-plus'
import {nextTick, reactive, ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {GlobalStore} from '@/stores/index'
import {Delete} from '@element-plus/icons-vue'
import {Storehouse_StockOut_Apply} from '@/api/storehouse/index'
import InStorageSn from '@/views/storehouse/inventory/InStorageSn.vue'
import OutStockProduct from './OutStockProduct.vue'
import ReceiveUser from '../receiveUser.vue'
import {depotHooks, ReceiveApplyFormType} from '@/hooks/useDepot'
import ImageCom from '@/components/Image/index.vue'
import {paymentMethodOptions} from '@/hooks/useTablePublic'


const router = useRouter()
const tableData = ref<any[]>([])
const globalStore = GlobalStore()
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const drawerSnRef = ref<InstanceType<typeof InStorageSn> | null>(null)
const drawerProductRef = ref<InstanceType<typeof OutStockProduct> | null>(null)
const receiveUserdialog = ref<InstanceType<typeof ReceiveUser> | null>(null)
const showReceiveField = ref(false)

const form = reactive<ReceiveApplyFormType>({
	T_project: '',
	T_number: '',
	T_date: '',
	T_depot_id: undefined,
	T_product: '',
	T_remark: '',
	T_contract_number: '',
	T_company_name: '',
	T_payment_method: '',
	T_receive: '',
	T_receive_name: ''
})

const validate_T_product = (rule: any, value: any, callback: any) => {
	if (value.includes(undefined) || value === '') {
		callback(new Error('请填写产品数量,出库数量不能大于库存数量!'))
	} else if (value.includes(null)) {
		callback(new Error('请添加产品SN'))
	} else {
		callback()
	}
}

const validate_T_receive = (rule: any, value: any, callback: any) => {
	// 只有从仓库页面进入时才验证领取人
	if (showReceiveField.value && !form.T_receive) {
		callback(new Error('请选择领取人'))
	} else {
		callback()
	}
}

const rules = reactive<FormRules>({
	T_product: [{required: true, validator: validate_T_product, trigger: 'blur'}],
	T_depot_id: [{required: true, message: '请选择仓库', trigger: 'blur'}],
	T_company_name: [{required: true, message: '请输入公司名称', trigger: 'blur'}],
	T_payment_method: [{required: true, message: '请选择付款方式', trigger: 'blur'}],
	T_receive: [{validator: validate_T_receive, trigger: 'change'}],
})

const columns = [
	{type: 'index', label: '序号', width: 80, align: 'center '},
	{label: '产品图片', prop: 'T_product_img', align: 'center ', name: 'T_product_img'},
	{label: '产品名称', prop: 'T_product_name', align: 'center '},
	{label: '产品型号', prop: 'T_product_model', align: 'center '},
	{label: '产品分类', prop: 'T_product_class_name', align: 'center '},
	{label: '产品型号', prop: 'T_product_model', align: 'center ', ellipsis: true},
	{label: '产品规格', prop: 'T_product_spec', align: 'center '},
	{label: '是否关联SN', prop: 'T_product_relation_sn', align: 'center ', width: 120, name: 'T_product_relation_sn'},
	{label: '库存数量', prop: 'T_total', align: 'center '},
	{label: '*出库数量', prop: 'count', align: 'center ', name: 'count'},
	{prop: 'operation', label: '操作', width: 80, fixed: 'right'}
]


const countBlurHandle = () => {
	form.T_product = tableData.value.map(item => {
		if (!item.count ) return undefined
		if (item.count > item.T_total) return undefined
		return `${item.T_product_id},${item.count}|`
	})
}
const getDeviceSnToProduct = () => {
	const isEmpty = determineSNorCount()
	if (isEmpty && isEmpty === 'count') return [undefined]

	return tableData.value.map((item: any) => {
		let product: any = ''
		product = `${item.T_product_id}-${item.count}-`
		return product + '|'
	})
}
/**
 * 判断sn or 数量是否为空
 */
const determineSNorCount = () => {
	for (const item of tableData.value) {
		if ((!item.count) || item.count > item.T_total) return 'count'
	}
	return false
}

const OutStorageApply = (formEl: FormInstance | undefined) => {

	if (!formEl) return
	form.T_product = getDeviceSnToProduct()
	formEl.validate(async valid => {
		if (valid) {
			const res: any = await Storehouse_StockOut_Apply({
				User_tokey: globalStore.GET_User_tokey,
				...form,
				T_product: form.T_product.join(''),
			})
			if (res.Code === 200) {
				ElMessage.success('出库申请提交成功！')
				nextTick(() => {
					resetForm(ruleFormRef.value)
					router.back()
				})
			}
		}
	})
}

const deleteProduct = (row: any) => {
	tableData.value = tableData.value.filter(item => item.Id !== row.Id)

	// 设置产品的选中
	drawerProductRef.value?.selectTableChange(row)
	// 删除设备得sn
	drawerSnRef.value?.deleteDeviceSn(row.Id)
}

const closeReceive = () => {
	resetForm(ruleFormRef.value)
	router.back()
}
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	tableData.value = []
	drawerSnRef.value?.clearDeviceSn()
	drawerProductRef.value?.clearSelection()
	formEl.resetFields()
}
/**
 * 添加产品
 */
const AddProductionDetailed = () => drawerProductRef.value?.openDrawer()
/**
 * 产品选择 是否
 */
const ProductselectionChange = (row: any) => {
	// 检查产品ID是否已存在（根据T_product_id去重）
	const existingIndex = tableData.value.findIndex((item: any) => item.T_product_id === row.T_product_id)
	
	if (existingIndex === -1) {
		// 产品ID不存在，可以添加
		row.count = ''
		tableData.value.push(row)
	} else {
		// 产品ID已存在，移除该产品
		tableData.value.splice(existingIndex, 1)
	}
}
/**
 * 全选
 */
const ProductSelectionAllChange = (selection: any[]) => {
	// 清空现有数据
	tableData.value = []
	
	// 使用Map根据T_product_id去重
	const productMap = new Map()
	
	selection.forEach(row => {
		if (!productMap.has(row.T_product_id)) {
			row.count = ''
			productMap.set(row.T_product_id, row)
		}
	})
	
	// 将去重后的产品添加到表格数据中
	tableData.value = Array.from(productMap.values())

}

// 拿到仓库列表
const {options} = depotHooks()
const changeDepot = () => drawerProductRef.value?.clearProdctData()

/**
 * 选择领取人
 */
const selectReceiver = () => receiveUserdialog.value?.openDrawer()
const getReceiveInfo = ({T_uuid, T_name}: {T_uuid: string; T_name: string}) => {
	form.T_receive_name = T_name
	form.T_receive = T_uuid
}

// 组件挂载时设置默认出库仓库为4（产成品库）
onMounted(() => {
	form.T_depot_id = 4
	
	// 检查是否从仓库页面进入
	const route = router.currentRoute.value
	if (route.query.fromWarehouse === '1') {
		showReceiveField.value = true
	}
})
</script>

<template>
	<div class="receive-outStock">
		<div>
			<h4 class="title">出库申请</h4>
			<el-divider border-style="dashed"/>
		</div>
		<el-form ref="ruleFormRef" :model="form" :rules="rules">
			<el-form-item label="出库单号：" :label-width="formLabelWidth" prop="T_number">
				<el-input v-model="form.T_number" disabled type="text" placeholder="系统自动生成" class="w-50"/>
			</el-form-item>
			<el-form-item label="出库仓库：" :label-width="formLabelWidth" prop="T_depot_id">
				<el-select v-model="form.T_depot_id" class="w-50" clearable placeholder="请选择出库仓库~"
						   @change="changeDepot">
					<el-option v-for="item in options" :key="item.Id" :label="item.T_name" :value="item.Id"/>
				</el-select>
			</el-form-item>
			<el-form-item label="公司名称：" :label-width="formLabelWidth" prop="T_company_name">
				<el-input v-model="form.T_company_name" placeholder="请输入公司名称" class="w-50"/>
			</el-form-item>
			<el-form-item label="付款方式：" class="m-b-6" :label-width="formLabelWidth" prop="T_payment_method">
				<el-select v-model="form.T_payment_method" class="w-50 m-2" clearable placeholder="请选择付款方式~">
					<el-option v-for="item in paymentMethodOptions" :key="item.id" :label="item.name" :value="item.id"/>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showReceiveField" label="领取人：" :label-width="formLabelWidth" prop="T_receive">
				<el-input v-model="form.T_receive_name" placeholder="请选择领取人" class="w-50" @focus="selectReceiver"/>
			</el-form-item>
			<el-form-item label="关联项目：" :label-width="formLabelWidth">
				<el-input v-model="form.T_project" placeholder="请输入关联项目" class="w-50"/>
			</el-form-item>
			<el-form-item label="出库明细：" :label-width="formLabelWidth" prop="T_product">
				<el-table
					:data="tableData"
					style="width: 100%"
					border
					stripe
					:header-cell-style="{
            background: '#dedfe0',
            height: '50px'
          }"
				>
					<template v-for="item in columns" :key="item.prop">
						<el-table-column show-overflow-tooltip v-bind="item"
										 v-if="item.fixed !== 'right' && !item.ellipsis">
							<template #header v-if="item.prop === 'count'">
								<span style="color: red">{{ item.label }}</span>
							</template>
							<template #default="{ row }" v-if="item.prop === item.name">
								<el-input
									v-if="item.prop === 'count'"
									v-model.number="row.count"
									type="text"
									autocomplete="off"
									@blur="countBlurHandle"
								/>
								<span v-if="item.prop === 'T_product_relation_sn'">
								  <el-tag v-if="row.T_product_relation_sn === 1" effect="dark">是</el-tag>
								  <el-tag v-else type="success" effect="dark">否</el-tag>
              					</span>
								<ImageCom v-if="item.prop === 'T_product_img'" :src="row.T_product_img"/>
							</template>
						</el-table-column>
						<el-table-column show-overflow-tooltip v-if="item.ellipsis && item.prop === 'T_model'"
										 v-bind="item">
							<template #default="{ row }">
								<el-tooltip effect="dark" :content="row.T_model" placement="bottom">
									{{ row.T_model }}
								</el-tooltip>
							</template>
						</el-table-column>
						<el-table-column v-bind="item" v-if="item.fixed === 'right'">
							<template #default="{ row }">
								<el-button link type="danger" size="small" :icon="Delete" @click="deleteProduct(row)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</template>
					<template #append>
						<el-button type="primary" @click="AddProductionDetailed">
							<el-icon>
								<Plus/>
							</el-icon>
							<span style="margin-left: 6px">添加产品</span>
						</el-button>
					</template>
				</el-table>
			</el-form-item>
			<el-form-item label="备注：" :label-width="formLabelWidth" prop="T_remark">
				<el-input
					v-model="form.T_remark"
					:autosize="{ minRows: 4, maxRows: 6 }"
					type="textarea"
					placeholder="请输入备注信息"
				/>
			</el-form-item>
			<div class="btn">
				<el-divider>
					<el-button @click="closeReceive">取消</el-button>
					<el-button color="#626aef" @click="OutStorageApply(ruleFormRef)">提交</el-button>
				</el-divider>
			</div>
		</el-form>
		<OutStockProduct
			ref="drawerProductRef"
			:depotId="form.T_depot_id"
			@ontableData="ProductselectionChange"
			@ontableDataAll="ProductSelectionAllChange"
		/>
		<ReceiveUser ref="receiveUserdialog" :dept_leader="0" @onUserInfo="getReceiveInfo" title="选择领取人"/>
	</div>
</template>
<style scoped lang="scss">
@import '../index.scss';
</style>
