<script setup lang="ts">
import { ref } from 'vue';

// @ts-ignore
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

// @ts-ignore
import { ElMessage } from 'element-plus';

// @ts-ignore
import { handleOperationalWeeklyReport } from '#/api/task/index';

// @ts-ignore
import { drawerFormSchema } from './config-data';

// 定义emit
const emit = defineEmits<{ reload: [] }>();

// 运营周报参数
const weeklyReportParams = ref({
  taskId: '',
  taskName: '',
});

// 初始化表单数据
const initialFormData = ref({
  competitorStrategy: '',
  competitorStrategyChange: '',
  coordinationHelp: '',
  id: undefined,
  images: '',
  nextWeekPlan: '',
  securityInternalComplianceOther: '',
  sitePriceStrategy: '',
  siteStrategyChange: '',
  weekCompletedWork: '',
  weekSummary: '',
});

// 创建表单实例
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 创建抽屉实例
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { taskId, taskName } = drawerApi.getData();
      weeklyReportParams.value.taskId = taskId;
      weeklyReportParams.value.taskName = taskName;

      // 重置表单
      formApi.resetForm(initialFormData.value);
    } catch (error) {
      console.error(error);
      ElMessage.error('加载运营周报数据失败');
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm(initialFormData.value);
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;

      // 表单验证
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }

      // 获取表单值
      const values = await formApi.getValues();

      // 处理图片字段
      delete values.imagePaths;

      // 构造请求参数
      const params = {
        id: weeklyReportParams.value.taskId,
        ...values,
      };

      // 调用API保存运营周报数据
      await handleOperationalWeeklyReport(params);

      ElMessage.success('运营周报处理成功');
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
      ElMessage.error('运营周报处理失败');
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="weeklyReportParams.taskName">
    <Form />
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
