<script setup lang="ts">
import {defineAsyncComponent, nextTick, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Finished, View} from '@element-plus/icons-vue'
import TableBase from '@/components/TableBase/index.vue'
import {useTablePublic} from '@/hooks/useTablePublic'
import {ColumnProps} from '@/components/TableBase/interface/index'
import {
	Purchase_Apply_User_List,
	Purchase_Del,
	Purchase_Excel,
	Purchase_List,
	Purchase_Stat_Excel
} from '@/api/purchase/index'
import { deptOptions } from '@/hooks/useTablePublic'
import {stockInexcel, Storehouse_VerifyContract_Recover_User_List} from "@/api/storehouse";
interface UserInfoIn {
	T_name: string
	T_type_name: string
	T_text: string
	T_uuid: string
	T_dept_name: string
	T_post_name: string
}

const columns: ColumnProps[] = [
	{type: 'index', label: '序号', width: 80},
	{prop: 'T_date', label: '申请时间'},
	{prop: 'T_dept', label: '申请部门'},
	{prop: 'T_uuid_name', label: '申请人'},
	{prop: 'T_State', label: '状态', name: 'T_State'},
	{prop: 'T_submit_name', label: '提交人'},
	{prop: 'T_approver_name', label: '审批人'},
	{prop: 'T_remark', label: '备注', width: 125},
	{prop: 'operation', label: '操作', width: 260, fixed: 'right'}
]
// 搜索
const options = reactive([
	{name: '待采购', id: 1},
	{name: '已采购', id: 2},
])

const TableRef = ref<InstanceType<typeof TableBase> | null>(null)

const {globalStore, updateOnTableList} = useTablePublic()
const openPurchaseDrawer = (type: string, row?: any) => purchaseFormRef.value?.purchaseFromOpen(type, row)
const purchaseFormRef = ref<InstanceType<typeof PurchaseForm> | null>(null)
const PurchaseForm = defineAsyncComponent(() => import(/*webpackChunkName: 'PurchaseForm'*/ './PurchaseForm.vue'))

const T_date = ref<string[]>([])
const initParam = reactive({
	User_tokey: globalStore.GET_User_tokey,
	T_uuid: '',
	T_dept: '',
	T_state: '',
	T_end_date: '',
	T_start_date: ''
})

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 DeletePurchase = (Id: number) => {
	ElMessageBox.confirm('您确定要删除采购申请吗?', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			const res: any = await Purchase_Del({User_tokey: globalStore.GET_User_tokey, T_id: Id})
			if (res.Code === 200) {
				ElMessage.success('删除成功！')
				nextTick(() => updateOnTableList(TableRef.value))
			}
		})
		.catch(() => {
			ElMessage.warning('取消成功！')
		})
}

const exportExcel = async (Id: number) => {

	const result:any = await Purchase_Excel({
		User_tokey: globalStore.GET_User_tokey,
		T_id: Id,
	})
	if (result.Code === 200) {
		window.open(result.Data)
	}

}

const exportStatExcel = async () => {

	const result:any = await Purchase_Stat_Excel({
		User_tokey: globalStore.GET_User_tokey,
		T_uuid: initParam.T_uuid,
		T_dept: initParam.T_dept,
		T_state: initParam.T_state,
		T_end_date: initParam.T_end_date,
		T_start_date: initParam.T_start_date
	})
	if (result.Code === 200) {
		window.open(result.Data)
	}
}

interface ListItem {
	value: string
	label: string
}
const loading = ref(false)
const list = ref<ListItem[]>([])
const optionsData = ref<ListItem[]>([])
const remoteMethod = async (query: string) => {
	if (query) {
		loading.value = true
		setTimeout(() => {
			loading.value = false
			optionsData.value = list.value.filter((item: any) => {
				return item.label.toLowerCase().includes(query.toLowerCase())
			})
		}, 200)
	} else {
		optionsData.value = list.value
	}
}
const click2 = async () => { optionsData.value = list.value }
onMounted(async () => {
	const result: any = await Purchase_Apply_User_List({})
	let arr =  []
	if (result?.Data !== null) {
		arr = result.Data.Data
	}

	list.value = arr.map((item: any) => {
		return { value: item.T_uuid, label: item.T_name }
	})
})
</script>
<template>
	<div class="purchase">
		<TableBase
			ref="TableRef"
			:columns="columns"
			:requestApi="Purchase_List"
			:initParam="initParam"
		>
			<template #table-header>
				<div class="input-suffix">
					<el-row :gutter="20" style="margin-bottom: 0">
						<el-col :xl="6" :lg="6" :md="6" style="display: flex">
							<span class="inline-flex items-center">申请日期：</span>
							<el-date-picker
								v-model="T_date"
								type="daterange"
								range-separator="~"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
							/>
						</el-col>
						<el-col :xl="6" :md="6">
							<span class="inline-flex items-center">部门：</span>
							<el-select v-model="initParam.T_dept" class="w-50 m-2" clearable placeholder="请选择部门~">
								<el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id"/>
							</el-select>
						</el-col>
						<el-col :xl="6" :lg="6"  :md="6" class="d-flex">
							<span class="inline-flex items-center">申请人：</span>
							<el-select v-model="initParam.T_uuid" filterable remote reserve-keyword placeholder="申请人"
									   :remote-method="remoteMethod" :loading="loading" @click="click2" clearable style="width: 150px;">
								<el-option v-for="item in optionsData" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-col>
						<el-col :xl="6" :md="6">
							<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 options" :key="item.id" :label="item.name" :value="item.id"/>
							</el-select>
							<el-button type="primary" @click="searchHandle">搜索</el-button>
							<el-button type="success" @click="exportStatExcel">导出</el-button>
						</el-col>
					</el-row>
				</div>
			</template>
			<template #T_State="{ row }">
				<el-tag v-if="row.T_State === 1" type="primary" effect="dark">待采购</el-tag>
				<el-tag v-else-if="row.T_State === 2" type="success" effect="dark">已采购</el-tag>
				<el-tag v-else-if="row.T_State === 3" type="warning" effect="dark">待审批</el-tag>
				<el-tag v-else type="danger" effect="dark">未通过</el-tag>
			</template>
			<template #right="{ row }">
				<el-button link type="success" size="small" :icon="View" @click="openPurchaseDrawer('view', row)">详情
				</el-button>
				<el-button
					link
					type="success"
					size="small"
					:icon="Finished"
					@click="exportExcel(row.Id)"
				>导出
				</el-button>
				<el-button
					link
					type="primary"
					size="small"
					:icon="Edit"
					@click="openPurchaseDrawer('edit', row)"
				>编辑
				</el-button>

				<el-button
					link
					type="danger"
					size="small"
					:icon="Delete"
					:disabled="[2].includes(row.T_State)"
					@click="DeletePurchase(row.Id)"
				>删除
				</el-button
				>
			</template>
		</TableBase>
		<PurchaseForm ref="purchaseFormRef" purchaseName="purchase" @onTableList="updateOnTableList(TableRef)"/>
	</div>
</template>

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

.purchase {
	height: 100%;
	display: flex;
	overflow: hidden;
	@include f-direction;

	:deep(.table-header),
	:deep(.card) {
		margin: 0;
		border-radius: 8px;
	}

	:deep(.el-table .cell) {
		white-space: normal !important;
	}

	.input-suffix {
		width: 100%;

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

		.btn {
			display: flex;
			justify-content: end;
		}

		.w-50 {
			width: 12.5rem;
		}
	}
}
</style>
