<script lang="ts" setup>
/**
 * @Name: EditComputerInfo.vue
 * @Description: 编辑电脑信息
 * @Author: xinyan
 */
import { ref } from 'vue';
import { ElMessage, FormInstance, FormRules, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import { genFileId } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { EditPen, Picture as IconPicture, Plus, Search } from '@element-plus/icons-vue';

const visible = defineModel({ default: false });
const { computerOverview, computerNumber , userOptions, shopOptions } = defineProps<{
  computerOverview: any;
  computerNumber: any;
  userOptions: any;
  shopOptions: any;
}>();

const emit = defineEmits(['refresh']);

// 图片处理
const upload = ref<UploadInstance>();
// 表单数据
const ruleFormRef = ref<FormInstance>();
const formData = reactive<RuleForm>({
	computerNumber: '',
	computerType: '',
	station: '',
	shop: '',
	user: '',
	macaddress: '',
	ipaddress: '',
	images: [],
});
const rules = reactive<FormRules<RuleForm>>({
  computerNumber: [{ required: true, message: '请输入电脑编号', trigger: 'blur' }],
  computerType: [{ required: true, message: '请输入电脑类型', trigger: 'blur' }],
  station: [{ required: true, message: '请输入所在站点', trigger: 'blur' }],
  shop: [{ required: true, message: '请输入所属商铺', trigger: 'blur' }],
  user: [{ required: true, message: '请输入使用者', trigger: 'blur' }],
  macaddress: [{ required: true, message: '请输入MAC地址', trigger: 'blur' }],
  ipaddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
});

const previewVisible = ref(false); // 控制预览对话框的显示
const previewImage = ref('');

onBeforeMount(() => {
  replaceCol();
});

// 超过图片限制时触发的回调
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles();
	const file = files[0] as UploadRawFile;
	file.uid = genFileId();
	upload.value!.handleStart(file);
};

const handlePreview = (file) => {
  previewImage.value = file.url || URL.createObjectURL(file.raw); // 获取图片 URL
  previewVisible.value = true; // 显示对话框
};

// 保存操作
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const dataToUpload = new FormData();

      // for (const key in formData) {
      //   if (key !== 'images' && formData.hasOwnProperty(key)) {
      //     dataToUpload.append(key, formData[key]);
      //   }
      // }

      const fieldsToAppend = ['computerNumber', 'computerType', 'station', 'user', 'macaddress', 'ipaddress'];

      fieldsToAppend.forEach((field) => {
        dataToUpload.append(field, formData[field as keyof RuleForm]);
      });

      const shopValue = Array.isArray(formData.shop) ? formData.shop.join(',') : formData.shop;
      dataToUpload.append('shops', shopValue);

      if (Array.isArray(formData.images)) {
        formData.images.forEach((image: any) => {
          if (image.raw) {
            dataToUpload.append('images', image.raw);
          }
        });
      }
      try {
        const resp = await useResponse({ id: computerOverview.id, partial: 1, dataToUpload, }, api.updateComputerDetail);
        // 检查上传结果并提示用户
        if (resp.code === 2000) {
          ElMessage.success('修改成功');
          visible.value = false;
          emit('refresh');
        }
      } catch (error) {
        console.error('上传失败:', error);
        ElMessage.error('上传失败，请重试');
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  visible.value = false;
};

function replaceCol() {
  const result = Object.keys(formData).reduce((acc, key) => {
    if (key in computerOverview) {
      if (key === 'images' && Array.isArray(computerOverview[key])) {
        acc[key] = computerOverview[key].map((img: { image: string }) => ({
          name: '已上传图片',
          url: img.image_url,
        }));
      } else {
        acc[key] = computerOverview[key];
      }
    }
    return acc;
  }, {} as { [key: string]: any });
  Object.assign(formData, result);
}

function handleImageError(file) {
  // 当图片加载失败时，设置 file 对象的 error 状态为 true
  file.error = true;
}
</script>

<template>
	<el-drawer :title="`电脑编辑 - ${computerNumber}`" v-model="visible" size="30%">
			<el-form  ref="ruleFormRef" :model="formData" :rules="rules" class="computer-info-form" label-width="auto">
        <el-form-item label="电脑编号：" prop="computerNumber">
          <el-input v-model="formData.computerNumber" placeholder="请输入电脑编号" />
        </el-form-item>
        <el-form-item label="电脑类型：" prop="computerType">
          <el-input v-model="formData.computerType" placeholder="请输入电脑类型" />
        </el-form-item>
        <el-form-item label="工位号：" prop="station">
          <el-input v-model="formData.station" placeholder="请输入工位号" />
        </el-form-item>
        <el-form-item label="所属店铺：" prop="shop">
          <el-select v-model="formData.shop" clearable filterable multiple collapse-tags placeholder="请选择店铺">
            <el-option v-for="shop in shopOptions" :key="shop.value" :label="shop.label" :value="shop.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="电脑使用人：" prop="user">
          <el-select v-model="formData.user" placeholder="请选择电脑使用人">
            <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="MAC地址：" prop="macaddress">
          <el-input v-model="formData.macaddress" placeholder="请输入MAC地址" />
        </el-form-item>
        <el-form-item label="使用IP地址：" prop="ipaddress">
          <el-input v-model="formData.ipaddress" placeholder="请输入IP地址" />
        </el-form-item>

				<!-- 电脑图片上传 -->
				<el-form-item :key="images" label="电脑图片：">
					<el-upload
						ref="upload"
						v-model:file-list="formData.images"
						:auto-upload="false"
						:limit="1"
						:on-exceed="handleExceed"
						action="#"
						list-type="picture-card"
            accept="image/*"
            :on-preview="handlePreview"
					>
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>

				<!-- 按钮组 -->
				<el-form-item class="button-group">
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
				</el-form-item>
			</el-form>
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" width="30%" height="30%">
      <img :src="previewImage" alt="预览图" style="width: 100%; height: auto;" />
    </el-dialog>
	</el-drawer>
</template>

<style scoped>
.computer-info-form {
	padding: 20px;
}

.button-group {
	margin-top: 20px;
	text-align: center;
}

.computer-info-form :deep(.el-form-item__label) {
	font-size: 14px;
	font-weight: 500;
}
</style>
