<script setup lang="ts">
import type {FormInstance} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRouter} from 'vue-router'
import {GlobalStore} from '@/stores'
import {Delete, Edit, Van, View} from '@element-plus/icons-vue'
import {nextTick, reactive, ref} from 'vue'
import TableBase from '@/components/TableBase/index.vue'
import type {ColumnProps} from '@/components/TableBase/interface'
import {stockOutExcelBatch, Storehouse_StockOut_Apply_Del, Storehouse_StockOut_Apply_List,} from '@/api/storehouse'
import {depotHooks} from '@/hooks/useDepot'
import OutStorageEdit from './modules/OutStorageEdit.vue'
import {paymentMethodOptions} from '@/hooks/useTablePublic'

const router = useRouter()
const formLabelWidth = ref('120px')
const globalStore = GlobalStore()
const ruleFormRef = ref<FormInstance>()
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const multipleSelection = ref<any[]>([])

const columns: ColumnProps[] = [
	{type: 'selection', width: '44px', fixed: 'left'},
	{type: 'index', label: '序号', width: 80},
	{prop: 'T_number', label: '出库单号'},
	{prop: 'T_application_date', label: '申请日期'},
	{prop: 'T_state_str', label: '状态', name: 'T_state_str'},
	{prop: 'T_company_name', label: '公司名称'},
	{prop: 'T_payment_method', label: '付款方式', name: 'T_payment_method', width: 150},
	{prop: 'T_receive_name', label: '领取人'},
	{prop: 'T_depot_name', label: '出库仓库'},
	{prop: 'T_date', label: '出库日期'},
	{prop: 'T_project', label: '关联项目'},
	{prop: 'operation', label: '操作', width: 250, fixed: 'right', align: 'left '}
]

const form = reactive({
	T_number: '',
	T_remark: '',
	T_delivery_type: '',
	T_signer_unit: '',
	T_signer: '',
	T_signer_phone: '',
	T_signer_date: '',
	T_courier_number: ''
})

// 搜索
const stateOptions = reactive([
	{name: '待审批', id: 1},
	{name: '财务通过', id: 2},
	{name: '财务驳回', id: 3},
	{name: '总经理通过', id: 4},
	{name: '总经理驳回', id: 5},
	{name: '已出库', id: 6},
])

/**
 * 查看详情
 */
const preview = (number: string) => {
	router.push({name: 'OutStockDetail', params: {number}})
}
const OutStorageRef = ref()
/**
 * 编辑
 */
const previewEdit = (row: any) => {
	OutStorageRef.value?.openDrawer()
	OutStorageRef.value?.getStorehouseContractGet(row.T_number)
	for (let key in OutStorageRef.value?.form) {
		if (row.hasOwnProperty(key)) OutStorageRef.value.form[key] = row[key];
	}

}
// 搜索
const T_date = ref<string[]>([])
const initParam = reactive({
	User_tokey: globalStore.GET_User_tokey,
	T_end_date: '',
	T_start_date: '',
	T_depot_id: '',
	T_name: '',
	T_state:''
})
const searchHandle = () => {
	initParam.T_end_date = T_date.value ? T_date.value[1] : ''
	initParam.T_start_date = T_date.value ? T_date.value[0] : ''
	TableRef.value?.searchTable()
}

/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}

/**
 * 删除
 */
const deleteFun = (row: any) => {
	ElMessageBox.confirm(
		'删除操作，是否立即删除?',
		'删除',
		{
			confirmButtonText: '立即删除',
			cancelButtonText: '取消',
			type: 'warning',
			center: true,
		}
	).then(async () => {
		const result: any = await Storehouse_StockOut_Apply_Del({T_number: row})
		if (result.Code == 200) {
			ElMessage.success('删除成功')
			TableRef.value?.searchTable()
		}
	}).catch(() => {
	})
}

// 拿到仓库列表
const {options} = depotHooks()

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
	return row.T_number
}
const stockOutExcelFun = async () => {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择出库单!!!')
		return
	}
	let T_number_list = ''
	for (let item of multipleSelection.value) {
		T_number_list += item.T_number + '|'
	}

	const result: any = await stockOutExcelBatch({T_number_list: T_number_list})
	if (result.Code === 200) {
		window.open(result.Data)
	}
	nextTick(() => {
		multipleSelection.value = []
		TableRef.value?.clearSelection()
	})
}
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val
	console.log(multipleSelection.value)
}
</script>

<template>
	<div class="out-stock">
		<TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_StockOut_Apply_List" :initParam="initParam"
				   :getRowKey="getRowKey"
				   :selection-change="handleSelectionChange"
		>
			<template #table-header>
				<div class="input-suffix">
					<el-row :gutter="20" style="margin-bottom: 0">
						<el-col :xl="5" :lg="5" :md="5" style="display: flex">
							<span class="inline-flex items-center">出库编号：</span>
							<el-input
								v-model="initParam.T_name"
								class="w-50 m-2"
								type="text"
								placeholder="出库编号搜索"
								clearable
								@change="searchHandle"
							/>
						</el-col>
						<el-col :xl="5" :lg="5" :md="5" style="display: flex">
							<span class="inline-flex items-center">状态：</span>
							<el-select v-model="initParam.T_state" class="w-50 m-2" clearable placeholder="请选择状态~">
								<el-option v-for="item in stateOptions" :key="item.id" :label="item.name"
										   :value="item.id"/>
							</el-select>
							<el-button type="primary" @click="searchHandle">搜索</el-button>
						</el-col>
						<el-col :xl="14" :lg="14" :md="14" class="btn"
						>
							<el-button type="primary" @click="router.push('/receiveOutStockApply')">出库申请</el-button>
							<el-button type="success" icon="Download" @click="stockOutExcelFun">导出excel</el-button>

						</el-col>
					</el-row>
				</div>
			</template>
			<template #T_payment_method="{ row }">
				<el-text type="info">{{
						paymentMethodOptions.find((option: any) => option.id === row.T_payment_method)?.name || ''
					}}
				</el-text>

			</template>
			<template #T_state_str="{ row }">
				<el-text v-if="row.T_state_str === '待审批'" type="warning"> 待审批</el-text>
				<el-text v-if="row.T_state_str === '财务通过'" type="primary"> 财务通过</el-text>
				<el-text v-if="row.T_state_str === '财务驳回'" type="danger"> 财务驳回</el-text>
				<el-text v-if="row.T_state_str === '总经理通过'" type="primary"> 总经理通过</el-text>
				<el-text v-if="row.T_state_str === '总经理驳回'" type="danger"> 总经理驳回</el-text>
				<el-text v-if="row.T_state_str === '已出库'" type="success"> 已出库</el-text>
			</template>
			<template #right="{ row }">
				<el-button link type="success" size="small" :icon="View" @click="preview(row.T_number)">详情</el-button>
				<el-button link type="primary" size="small" :icon="Edit" @click="previewEdit(row)"
						   :disabled="[2,4,6].includes(row.T_state)"
				>编辑
				</el-button>
				<el-button link type="danger" size="small" :icon="Delete" @click="deleteFun(row.T_number)"
						   :disabled="[2,4,6].includes(row.T_state)"
				>删除
				</el-button>
			</template>
		</TableBase>
		<OutStorageEdit ref="OutStorageRef" :options="options" @onUpdateList="searchHandle"/>
	</div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.out-stock {
	@include f-direction;

	:deep(.el-drawer__header) {
		margin-bottom: 0;
	}

	.input-suffix {
		width: 100%;

		.inline-flex {
			white-space: nowrap;
		}
	}

	.btn {
		display: flex;
		justify-content: right;

		.el-button {
			padding: 0 20px;
		}
	}
}
</style>
