<template>
	<el-dialog v-model="visible" title="常规借用申请单" width="75%" :close-on-click-modal="false" @close="onCancel">
		<div style="margin-bottom: 16px">
			<ol style="padding: 10px 30px; margin-bottom: 20px; border: 1px solid #409eff; border-radius: 5px; background: #e6f7ff">
				<h2>借用须知：</h2>
				<li>1、申请借用设备时必须本人来办理，借用期间设备由借用人负责保管。禁止转借他人</li>
				<li>2、如因人为操作不当造成的设备损坏或设备损失，应由借用人按规定赔偿。</li>
				<li>3、设备需按时归还，如逾期归还，将限制借用资格。</li>
				<li>4、设备借用一周以内由实验室管理办公室审批，设备借用一周以上或非我院师生借用时还需实验中心领导审批。</li>
			</ol>
		</div>
		<el-form :model="form" label-width="110px" label-position="top" :rules="rules" ref="formRef">
			<el-row :gutter="16">
				<el-col :span="8">
					<el-form-item label="借用单编号" prop="application_no">
						<el-input v-model="form.application_no" placeholder="自动生成" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用人" prop="admin_borrower" v-if="form.borrower_type == 0">
						<el-select v-model="form.admin_borrower" placeholder="请选择借用人" >
							<el-option  :label="adminList.name" :value="adminList.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="借用人" prop="app_user_borrower" v-if="form.borrower_type == 1">
						<el-select v-model="form.app_user_borrower" placeholder="请选择借用人" >
							<el-option v-for="item in allUserList"  :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="借用人" prop="external_borrower_name" v-if="form.borrower_type == 2">
						<el-input v-model="form.external_borrower_name" placeholder="请输入借用人"  />
					</el-form-item>
				</el-col>
				<el-col :span="8" v-if="form.borrower_type !== 2">
					<el-form-item label="学号/工号" prop="user_code">
						<el-input v-model="form.user_code" placeholder="请输入学号/工号"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联系电话" prop="mobile" v-if="form.borrower_type !== 2">
						<el-input v-model="form.mobile" placeholder="请输入联系电话"  />
					</el-form-item>
					<el-form-item label="联系电话" prop="mobile" v-if="form.borrower_type == 2">
						<el-input v-model="form.external_borrower_phone" placeholder="请输入联系电话"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用部门" prop="borrower_dept">
						<el-input v-model="form.borrower_dept" placeholder="请输入借用部门"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="预计归还时间" prop="expected_end_time">
						<el-date-picker v-model="form.expected_end_time" type="datetime" placeholder="请选择预计归还时间" style="width: 100%" />
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="个人/团队" prop="team_type">
						<el-select v-model="form.team_type" placeholder="请选择">
							<el-option label="个人" :value="0" />
							<el-option label="团队" :value="1" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4" v-show="form.team_type===1">
					<el-form-item label="团队人数" prop="team_members_count">
						<el-input v-model="form.team_members_count" placeholder="请输入" />
					</el-form-item>
				</el-col>
				<el-col :span="16" v-show="form.team_type===1">
					<el-form-item label="团队其他人员名单" prop="team_members">
						<el-input v-model="form.team_members" placeholder="请输入团队其他人员名单" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="借用原因" prop="purpose">
						<el-input v-model="form.purpose" type="textarea" placeholder="请输入借用原因" />
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="审批人" prop="applicant_remark">
						<el-select v-model="form.applicant_remark_type" placeholder="请选择">
							<el-option label="管理员" value="1"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="20">
					<el-form-item label="备注" prop="applicant_remark">
						<el-input v-model="form.applicant_remark" placeholder="请输入备注" />
					</el-form-item>
				</el-col>
			</el-row>
			<div style="margin: 16px 0 8px 0; font-weight: bold">借用列表</div>
			<!-- {{ isEdit }} -->
			<el-table :data="!isEdit ? form.items : form.items.filter(item => item.device === null)" border style="width: 50%; margin-bottom: 12px">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="device_category" label="设备分类">
					<template #default="{ row }">
						{{ getCategoryName(row.device_category) }}
					</template>
				</el-table-column>
				<!-- <el-table-column prop="quantity" label="借用数量" /> -->
				<el-table-column label="借用数量">
				<template #default="{ row }">
				<el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" :disabled="isView" />
				</template>
				</el-table-column>
				<el-table-column prop="location" label="存放仓库" />
				<el-table-column label="操作" width="80">
					<template #default="{ row, $index }">
						<el-button type="text" style="color: red" @click="removeItem($index)" :disabled="isView">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="primary" @click="addItem">选择设备分类</el-button>
			<div style="margin: 16px 0 8px 0; font-weight: bold">配件信息</div>
			<el-input v-model="form.accessories" placeholder="请输入配件信息" />
			<div style="margin: 16px 0 8px 0; font-weight: bold">附件</div>
			<div>
				<el-upload
				list-type="picture-card"
				:show-file-list="true"
				:http-request="handleCustomUpload"
				:file-list="fileList"
				style="margin-top: 10px;"
				>
				<el-icon><Plus /></el-icon>
				</el-upload>
		    </div>
		</el-form>
		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button type="primary" @click="onSubmit">提交</el-button>
		</template>
	</el-dialog>
	<SelectDeviceDialog v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" />
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted,computed } from 'vue';
import SelectDeviceDialog from './SelectDeviceDialog/index.vue';
import * as apis from '../../../timetablemanage/api';
import * as api from '../../api';
import { provide } from 'vue';
import dayjs from 'dayjs';
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';
import { getUserInfo } from '../../../login/api';
import * as deviceApi from '../../../deviceclass/api';
import { request } from '/@/utils/service';
const now = dayjs().format('YYYY-MM-DD HH:mm:ss');




const props = defineProps<{ visible: boolean; modelValue?: any }>();
const emit = defineEmits(['update:visible', 'update:modelValue', 'submit']);
const visible = ref(props.visible);

const isEdit = computed(() => props.modelValue?.mode === 'edit');
const isView = computed(() => props.modelValue?.mode === 'view');
const isAdd = computed(() => props.modelValue?.mode === 'add');

const formRef = ref();

const form = ref({
	application_no: '',
	emergency_contact: '',
	emergency_phone: '',
	app_user_borrower: 1,
	team_type: 0,
	team_members_count: 1,
	team_members: '',
	expected_start_time:'',
	expected_end_time: '',
	borrower_dept: '',
	purpose: '',
	applicant_remark_type:'1',
	applicant_remark: '',
	items: [],
	accessories: '',
	borrow_type: 0,
	return_location:'',
	borrower_type:0,
	attachments:'',
});

const showSelectDeviceDialog = ref(false);

const rules = {
   external_borrower_name: [
    { required: true, message: '请输入借用人', trigger: 'change' },
  ],
  app_user_borrower: [
    { required: true, message: '请输入学号或工号', trigger: 'change' },
  ],
  external_borrower_phone: [
    { required: true, message: '请输入联系电话', trigger: 'change' },
  ],
  borrower_dept: [
    { required: true, message: '请输入借用部门', trigger: 'change' },
  ],
  expected_end_time: [
    { required: true, message: '请输选择归还时间', trigger: 'change' },
  ],
  team_type: [
    { required: true, message: '请选择个人或者团队', trigger: 'change' },
  ],
  purpose: [
    { required: true, message: '请输入借用原因', trigger: 'change' },
  ],
  applicant_remark_type: [
    { required: true, message: '请选择审批人', trigger: 'change' },
  ],
  applicant_remark: [
    { required: true, message: '请输入备注', trigger: 'change' },
  ],
};

const fileList = ref([]);

// const fileList = ref([]);
const handleCustomUpload = async ({ file, onProgress, onSuccess, onError }: any) => {
  const token = Cookies.get('token'); 
  const formData = new FormData();
  formData.append('file', file);
  console.log("token::::",token);

  try {
    const res = await request({
		url: `/api/system/upload/`,
		method: 'post',
		headers: {
			'Content-Type': 'multipart/form-data',
			Authorization: 'JWT '+ token,
		},
		data: formData,
		timeout: 60000,
		onUploadProgress: (p: any) => {
                            onProgress({percent: Math.round((p.loaded / p.total) * 100)});
		}
    });

	// 构造 Element Plus 需要的 file 对象
	const fileObj = {
      name: res.data.name,
      url: res.data.url,
      status: 'success',
      response: res.data
    };

    // 添加到附件列表
	form.value.attachments = fileObj.url; 

    ElMessage.success('上传成功');
    onSuccess(fileObj); 
  } catch (error) {
    ElMessage.error('上传失败');
    onError(error);
  }
};

/* 获取管理员列表 */
const adminList = ref([]);

async function getAdminList() {
	const res = await getUserInfo();
	adminList.value = res.data;
	console.log("adminList.value:::",adminList.value)	
}

/* 获取所有用户 */
const allUserList = ref([]);
const categoryList = ref([]);
async function getAllUserList() {
	const res = await api.GetAllUser();
	allUserList.value = res.data;
	// 设置默认选择第一个用户
	if (allUserList.value.length > 0) {
		form.value.app_user_borrower = allUserList.value[0].id;
	}
	console.log("allUserList.value:::",allUserList.value)	
}

// 自动填充用户信息
// 获取设备分类列表
async function getCategories() {
	try {
		const res = await deviceApi.GetList({ page: 1, limit: 50, tatus:1 })
		if (res.data) {
			categoryList.value = res.data;
		}
	} catch (error) {
		console.error('获取设备分类失败:', error);
	}
}

// 根据分类ID获取分类名称
function getCategoryName(categoryId) {
	const category = categoryList.value.find(item => item.id === categoryId);
	return category ? category.name : categoryId;
}

onMounted(() => {
	try {
		getAllUserList()
		getAdminList();
		getCategories();
		const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		if (userInfo) {
			form.value.emergency_contact = userInfo.username || '';
			form.value.app_user_borrower = Number(userInfo.dept_info?.dept_id )|| 1;
			form.value.emergency_phone = userInfo.mobile || '';
			form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
		}
	} catch (e) {
		/* empty */
	}
});
// 监听借用人选择变化
watch(() => form.value.app_user_borrower, (newValue) => {
  if (newValue && allUserList.value.length > 0) {
    const selectedUser = allUserList.value.find(user => user.id === newValue);
    if (selectedUser) {
      form.value.user_code = selectedUser.user_code || '';
	  form.value.mobile = selectedUser.mobile || '';
    }
  }
});

watch(
	() => props.visible,
	(v) => (visible.value = v)
);
watch(() => props.modelValue, async (val) => {
  if (val && val.id && isView.value) {
			try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
			}
			} catch (e) {
			ElMessage.error('获取详细信息失败');
			}
	}else if(val&& isEdit.value){
		try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				if(data.borrower_type == 0){
					/* data.app_user_borrower= data.admin_borrower */
				}else if(data.borrower_type == 1){
					data.app_user_borrower= data.app_user_borrower?.id
				}
				Object.assign(form.value, data);
			}
			} catch (e) {
			ElMessage.error('获取详细信息失败');
			}
	}
}, { immediate: true });
function addItem() {
	showSelectDeviceDialog.value = true;
}
function onDeviceSelected(devices) {
	// 假设 form.value.items 已存在
	console.log("devices:::",devices);
	form.value.items.push(
		...devices.map((d) => ({
			device:null,
			device_category: d.id,
			remark: d.name,
			quantity: 1,
			location: d.warehouse,
		}))
	);
	console.log("form.value.items:::",form.value.items);
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}
function onCancel() {
	emit('update:visible', false);
}
async function onSubmit() {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const firstLocation = form.value.items[0]?.location || '';
            form.value.return_location = firstLocation;
			form.value.expected_start_time = now;
			form.value.expected_end_time = dayjs(form.value.expected_end_time).format('YYYY-MM-DD HH:mm:ss')|| now;
			form.value.team_members_count=Number(form.value.team_members_count)||1;
			form.value.borrow_type = 0;
			
			try {
				await api.UpdateObj({...form.value});
				ElMessage.success('更新成功');
				/* emit('submit', { ...form.value }); */
				emit('update:visible', false);
				// 触发父组件刷新
				emit('refresh');
			} catch (error) {
				ElMessage.error('更新失败：' + error.message);
			}
		}
	});
}

</script>
