<script setup lang="ts">
import {
	stockInEditSort,
	Storehouse_Product_Add,
	Storehouse_Product_Del,
	Storehouse_Product_Edit,
	Storehouse_Product_List,
	Storehouse_ProductClass_List
} from '@/api/storehouse'
import {nextTick, onMounted, reactive, ref} from 'vue'
import Upload from '@/components/Upload/index.vue'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit} from '@element-plus/icons-vue'
import type {ColumnProps} from '@/components/TableBase/interface'
import ImageCom from '@/components/Image/index.vue'
import {useTablePublic} from '@/hooks/useTablePublic'

const isNew = ref(true)
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const {resetForm, globalStore, searchOnTableList, updateOnTableList} = useTablePublic()

const columns: ColumnProps[] = [
	{type: 'index', label: '序号', width: 80},
	{prop: 'T_class_name', label: '产品分类'},
	{prop: 'T_name', label: '产品名称'},
	{prop: 'T_price', label: '单价'},
	{prop: 'T_remark', label: '备注', name: 'T_remark'},
	{prop: 'operation', label: '操作', width: 150, fixed: 'right'}
]

const rules = reactive<FormRules>({
	T_name: [{required: true, message: '请输入产品名称', trigger: 'blur'}],
	T_class: [{required: true, message: '请选择产品分类', trigger: 'blur'}],
	T_price: [{required: true, message: '请输入单价', trigger: 'blur'}],
})
const form = ref({
	Id: '',
	T_name: '',
	T_class: '',
	T_remark: '',
	T_price: ''
})

const openDrawer = (type: string, row?: any) => {
	isNew.value = type === 'new' ? true : false
	// !specList.value.length && getSpecList()
	nextTick(() => {
		if (!isNew.value) {
			form.value = {...row}
		}
	})
	drawerRef.value?.openDrawer()
}

const AddProduction = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async valid => {
		if (valid) {
			let res: any = {}
			if (isNew.value) {
				res = await Storehouse_Product_Add({User_tokey: globalStore.GET_User_tokey, ...form.value})
			} else {
				res = await Storehouse_Product_Edit({
					User_tokey: globalStore.GET_User_tokey,
					...form.value,
					T_id: form.value.Id
				})
			}
			if (res.Code === 200) {
				ElMessage.success(`验证产品${isNew.value ? '添加' : '修改'}成功！！`)
				nextTick(() => {
					drawerRef.value?.closeDrawer()
					updateOnTableList(TableRef.value)
					resetForm(ruleFormRef.value)
					isNew.value = true
				})
			}
		}
	})
}

const ProductDelete = (row: any) => {
	ElMessageBox.confirm('您确定要删除该验证产品吗?', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			const res: any = await Storehouse_Product_Del({
				User_tokey: globalStore.GET_User_tokey,
				T_id: row.Id
			})
			if (res.Code === 200) {
				ElMessage.success('删除成功！')
				nextTick(() => updateOnTableList(TableRef.value))
			}
		})
		.catch(() => {
			ElMessage.warning('取消成功！')
		})
}

const callbackDrawer = (done: () => void) => {
	resetForm(ruleFormRef.value)
	uploadRef.value?.clearfileList()
	done()
}
// 搜索
const initParam = reactive({
	User_tokey: globalStore.GET_User_tokey,
	T_name: '',
	T_class: '',
	T_VerifyContract: 1
})
// 获取产品分类
const options = ref<any[]>([])
const getProductClassList = async () => {
	const res: any = await Storehouse_ProductClass_List({T_Verify: 1, page: 1, page_z: 999})
	options.value = res.Data.Data
}

const onclickSort = async (row: any) => {
	ElMessageBox.prompt('请输入排序号', '', {
		confirmButtonText: 'OK',
		cancelButtonText: 'Cancel',
		inputValue: `${row.T_sort}`
	}).then(async ({value}) => {
		const result: any = await stockInEditSort({T_id: row.Id, T_sort: value})
		if (result.Code == 200) {
			ElMessage.success('编辑成功')
			TableRef.value?.getTableList()
		}
	}).catch(() => {
	})
}

onMounted(() => {
	getProductClassList()
})
</script>

<template>
	<div class="production-list">
		<TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_Product_List" :initParam="initParam">
			<template #table-header>
				<div class="input-suffix">
					<el-row :gutter="20" style="margin-bottom: 0">
						<el-col :xl="6" :lg="8" :md="10">
							<span class="inline-flex items-center">产品分类：</span>
							<el-select v-model="initParam.T_class" class="w-50 m-2" clearable placeholder="请选择分类~">
								<el-option v-for="item in options" :key="item.Id" :label="item.T_name"
										   :value="item.Id"/>
							</el-select>
						</el-col>
						<el-col :xl="10" :md="12">
							<span class="inline-flex items-center">产品名称：</span>
							<el-input
								v-model="initParam.T_name"
								type="text"
								class="w-50 m-2"
								placeholder="按产品名称、产品型号搜索"
								@change="searchOnTableList(TableRef)"
							/>
							<el-button type="primary" @click="searchOnTableList(TableRef)">搜索</el-button>
						</el-col>
						<el-col :xl="6" :md="2" class="btn"
						>
							<el-button type="primary" @click="openDrawer('new')">添加</el-button>
						</el-col
						>
					</el-row>
				</div>
			</template>

			<template #T_img="{ row }">
				<ImageCom :src="row.T_img"/>
			</template>
			<template #T_sort="{ row }">
				<div @dblclick="onclickSort(row)" style="cursor: pointer;">
					{{ row.T_sort }}
				</div>
			</template>
			<template #T_remark="{ row }">
				<el-tooltip effect="customized" placement="left">
					<template #content>
						<div class="tooltip-content">{{ row.T_remark }}</div>
					</template>
					{{ row.T_remark }}
				</el-tooltip>
			</template>
			<template #T_relation_sn="{ row }">
				<el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
				<el-tag v-else type="success" effect="dark">否</el-tag>
			</template>
			<template #right="{ row }">
				<el-button link type="primary" size="small" :icon="Edit" @click="openDrawer('edit', row)">编辑
				</el-button>
				<el-button link type="danger" size="small" :icon="Delete" @click="ProductDelete(row)">删除</el-button>
			</template>
		</TableBase>
		<Drawer ref="drawerRef" :handleClose="callbackDrawer">
			<template #header="{ params }">
				<h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 验证产品</h4>
			</template>
			<el-form ref="ruleFormRef" :model="form" :rules="rules">
				<el-form-item label="产品名称：" class="m-b-6" :label-width="formLabelWidth" prop="T_name">
					<el-input v-model="form.T_name" type="text" autocomplete="off" placeholder="请输入验证产品名称"/>
				</el-form-item>
				<el-form-item label="产品分类：" class="m-b-6" :label-width="formLabelWidth" prop="T_class">
					<el-select v-model="form.T_class" placeholder="请选择产品分类~">
						<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="单价：" class="m-b-6" :label-width="formLabelWidth" prop="T_price">
					<el-input v-model="form.T_price" type="number" autocomplete="off" placeholder="请收入单价"/>
				</el-form-item>
				<el-form-item label="备注：" class="m-b-6" :label-width="formLabelWidth" prop="T_remark">
					<el-input
						v-model="form.T_remark"
						:autosize="{ minRows: 4, maxRows: 6 }"
						type="textarea"
						placeholder="请输入备注信息"
					/>
				</el-form-item>
				<el-form-item :label-width="formLabelWidth">
					<el-button v-if="isNew" color="#626aef" @click="AddProduction(ruleFormRef)">提交</el-button>
					<el-button v-else color="#626aef" @click="AddProduction(ruleFormRef)">修改</el-button>
				</el-form-item>
			</el-form>
		</Drawer>
	</div>
</template>

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

.tooltip-content {
	max-width: 500px;
	overflow-y: auto;
}

.production-list {
	@include f-direction;

	.input-suffix {
		width: 100%;

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

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

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