<script setup lang="ts">
import {RepairWorkOrder_Add, RepairWorkOrder_Edit, RepairWorkOrder_Return} from '@/api/RepairWorkOrder/index'
import {nextTick, reactive, ref} from 'vue'
import Upload from './Upload/index.vue'
import Drawer from '@/components/Drawer/index.vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from 'element-plus'
import {useTablePublic} from '@/hooks/useTablePublic'
import ContractUser from "@/views/storehouse/outStock/receiveUser.vue";

const typeTip = ref('')
const isNew = ref(true)
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const {resetForm, globalStore} = useTablePublic()
const receiveUser = ref<InstanceType<typeof ContractUser> | null>(null)
const fileListImg: any = ref([])
let showWatch = ref(true)
let disabled = ref(true)

const rules = reactive<FormRules>({
	T_product: [{required: true, message: '请输入产品名称', trigger: 'blur'}],
	T_repair_num: [{required: true, message: '请输入维修数量', trigger: 'blur'}],
	T_repair_reason: [{required: true, message: '维修原因', trigger: 'blur'}],
	T_return_product: [{required: true, message: '请输入产品名称', trigger: 'blur'}],
	T_return_num: [{required: true, message: '请输入返回数量', trigger: 'blur'}],
	T_staging_num: [{required: true, message: '请输入暂存数量', trigger: 'blur'}],
	T_scrap_num: [{required: true, message: '请输入报废数量', trigger: 'blur'}],
	// T_malfunction_reason: [{ required: true, message: '请输入故障原因', trigger: 'blur' }],
})
const form: any = ref({
	T_id: '',
	T_order_date: '',
	T_repair_date: '',
	T_finish_date: '',
	T_state: '',
	T_product: '',
	T_model: '',
	T_repair_num: '',
	T_source: '',
	T_repair_reason: '',
	T_picture: '',
	T_receive_name: '',
	T_delivery_name: '',
	T_return_name: '',
	T_return_date: '',
	T_return_product: '',
	T_return_model: '',
	T_return_num: '',
	T_staging_num: '',
	T_scrap_num: '',
	T_malfunction_reason: '',
	T_remark: '',
	T_sn: '',
})

const repairWorkOrderFormOpen = (type: string, row?: any) => {
	// drawerRef.value?.openDrawer()
	isNew.value = type === 'new' ? true : false
	showWatch.value = type == 'new' || 'edit' ? true : false
	typeTip.value = type
	if (type !== 'new') {

			for (let key in form.value) {
				if (row.hasOwnProperty(key)) {
					form.value[key] = row[key];
				}
			}
			if (form.value.T_return_product === '') {
				form.value.T_return_product = form.value.T_product
			}
			if (form.value.T_return_model === '') {
				form.value.T_return_model = form.value.T_model
			}
			form.value.T_id = row.Id
			fileListImg.value.push({url:form.value.T_picture})
			console.log('form.value', form.value)
			console.log('fileListImg', fileListImg)


	} else {
		delete form.value.T_id
		form.value.T_product = ''
		form.value.T_repair_num = ''
		form.value.T_model = ''
		form.value.T_source = ''
		form.value.T_repair_reason = ''
		form.value.T_receive = ''
		form.value.T_picture = ''
		fileListImg.value = []
	}

	drawerRef.value && drawerRef.value.openDrawer()

}

const AddRepairWorkOrder = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async (valid: boolean) => {
		if (valid) {
			let res: any = {}
			if (isNew.value) {//新增
				res = await RepairWorkOrder_Add({User_tokey: globalStore.GET_User_tokey, ...form.value})
			} else if (typeTip.value === 'return') {
				res = await RepairWorkOrder_Return({
					User_tokey: globalStore.GET_User_tokey,
					...form.value,
				})
			} else {//编辑
				res = await RepairWorkOrder_Edit({
					User_tokey: globalStore.GET_User_tokey,
					...form.value,
				})
			}
			if (res.Code === 200) {
				ElMessage.success(`维修工单${isNew.value ? '下发' : '修改'}成功！！`)
				nextTick(() => {
					emit('onTableList')
					drawerRef.value?.closeDrawer()
					resetForm(ruleFormRef.value)
					uploadRef.value?.clearfileList()
					isNew.value = true
				})
			}
		}
	})
}

const selectReceive = () => receiveUser.value?.openDrawer()
const getReceiveInfo = ({T_uuid, T_name}: { T_uuid: string; T_name: string }) => {
	form.value.T_receive_name = T_name
	form.value.T_receive = T_uuid
}
const callbackDrawer = (done: () => void) => {
	disabled.value = false
	isNew.value = true
	nextTick(() => {
		resetForm(ruleFormRef.value)
		uploadRef.value?.clearfileList()
		done()
	})
}

const getTitle = (type: string) => {
	switch (type) {
		case 'new':
			return '下发'
		case 'edit':
			return '编辑'
		case 'return':
			return '归还'
		default:
			return '详情'
	}
}

const emit = defineEmits<{ (event: 'onTableList'): void }>()

defineExpose({
	repairWorkOrderFormOpen
})
</script>

<template>
	<Drawer ref="drawerRef" :handleClose="callbackDrawer" size="35%">
		<template #header="{ params }">
			<h4 :id="params.titleId" :class="params.titleClass">{{ getTitle(typeTip) }} - 维修工单</h4>
		</template>
		<el-form ref="ruleFormRef" :model="form" :rules="rules">
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="产品名称：" class="m-b-6" :label-width="formLabelWidth" prop="T_product">
				<el-input v-model="form.T_product" type="text" autocomplete="off" placeholder="请填写产品名称"/>
			</el-form-item>
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="型号：" class="m-b-6" :label-width="formLabelWidth" prop="T_model">
				<el-input v-model="form.T_model" type="text" autocomplete="off" placeholder="请填写型号"/>
			</el-form-item>
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="维修数量：" class="m-b-6" :label-width="formLabelWidth" prop="T_repair_num">
				<el-input v-model="form.T_repair_num" type="text" autocomplete="off" placeholder="请填写维修数量"/>
			</el-form-item>
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="设备来源：" class="m-b-6" :label-width="formLabelWidth" prop="T_source">
				<el-input v-model="form.T_source" type="text" autocomplete="off" placeholder="请填写设备来源"/>
			</el-form-item>
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="维修原因：" class="m-b-6" :label-width="formLabelWidth" prop="T_repair_reason">
				<el-input v-model="form.T_repair_reason" type="text" autocomplete="off" placeholder="请填写维修原因"/>
			</el-form-item>
			<el-form-item
				v-if="!(typeTip === 'return')"
				label="接收人：" class="m-b-6" :label-width="formLabelWidth" prop="T_receive_name">
				<el-input v-model="form.T_receive_name" type="text" autocomplete="off" placeholder="请选择接收人"
						  @focus="selectReceive"/>
			</el-form-item>

			<el-divider :style="{borderColor: '#64BA3AFF' }"
						v-if="!(typeTip === 'new' || typeTip === 'return')"
						content-position="left">归还情况
			</el-divider>
			<el-form-item v-if="!isNew" label="产品名称：" class="m-b-6" :label-width="formLabelWidth"
						  prop="T_return_product">
				<el-input v-model="form.T_return_product" type="text" autocomplete="off" placeholder="请填写产品名称"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="型号：" class="m-b-6" :label-width="formLabelWidth" prop="T_return_model">
				<el-input v-model="form.T_return_model" type="text" autocomplete="off" placeholder="请填写型号"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="返回数量：" class="m-b-6" :label-width="formLabelWidth"
						  prop="T_return_num">
				<el-input v-model="form.T_return_num" type="text" autocomplete="off" placeholder="请填写返回数量"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="暂存数量：" class="m-b-6" :label-width="formLabelWidth"
						  prop="T_staging_num">
				<el-input v-model="form.T_staging_num" type="text" autocomplete="off" placeholder="请填写暂存数量"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="报废数量：" class="m-b-6" :label-width="formLabelWidth"
						  prop="T_scrap_num">
				<el-input v-model="form.T_scrap_num" type="text" autocomplete="off" placeholder="请填写报废数量"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="故障原因：" class="m-b-6" :label-width="formLabelWidth"
						  prop="T_malfunction_reason">
				<el-input v-model="form.T_malfunction_reason" type="text" autocomplete="off"
						  placeholder="请填写故障原因"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="备注：" class="m-b-6" :label-width="formLabelWidth" prop="T_remark">
				<el-input v-model="form.T_remark" type="text" autocomplete="off" placeholder="请填写备注"/>
			</el-form-item>
			<el-form-item v-if="!isNew" label="SN：" class="m-b-6" :label-width="formLabelWidth" prop="T_sn">
				<el-input v-model="form.T_sn" type="text" autocomplete="off" placeholder="请填写SN"/>
			</el-form-item>

			<el-form-item :label-width="formLabelWidth">
				<el-button v-if="typeTip==='new'" color="#626aef" @click="AddRepairWorkOrder(ruleFormRef)">提交
				</el-button>
				<el-button v-if="typeTip==='edit'" color="#626aef" @click="AddRepairWorkOrder(ruleFormRef)">修改
				</el-button>
				<el-button v-if="typeTip==='return'" color="#626aef" @click="AddRepairWorkOrder(ruleFormRef)">归还
				</el-button>
			</el-form-item>
		</el-form>
	</Drawer>
	<ContractUser ref="receiveUser" @onUserInfo="getReceiveInfo" title="接收人"/>

</template>

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

.tooltip-content {
	max-width: 500px;
	overflow-y: auto;
}
</style>
