<template>
  <div>
    <el-drawer v-model="visible" title="问题详情" direction="rtl" size="30%" :close-on-click-modal="false"
      @close="handleCancel">
      <el-form ref="formRef" :model="formData">
        <el-form-item label="问题来源：" prop="source">
          <el-select v-model="formData.source" placeholder="请选择问题来源" clearable @change="handleSelectChange">
            <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题类型：" prop="issueType">
          <el-select v-model="formData.issueType" placeholder="请选择问题类型" clearable>
            <el-option v-for="item in options" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述：" prop="description">
          <el-input v-model="formData.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="问题图片：" prop="pictures">
          <el-upload v-model:file-list="fileList" action="/skyeye-admin-api/issue/uploadPicture"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="handleAvatarSuccess" :headers="getHeaders()" :data="{ bizType: 'PROBLEM_REPORT' }">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="问题地点：" prop="workspaceId">
          <el-cascader v-model="workLocation" :options="locationOptions" :props="location" clearable
            @change="handleCascaderChange" />
        </el-form-item>
        <el-form-item label="问题时间：" prop="issueTime">
          <el-date-picker v-model="formData.issueTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss.SSS"
            placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="问题状态：" prop="issueState">
          <el-select v-model="formData.issueState" placeholder="请选择问题状态">
            <el-option v-for="item in issueStateOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeMount, onMounted, reactive, ref } from 'vue';
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { sourceOptions, issueStateOptions } from './constant.question';
import { useIssueType } from '../../hooks/useIssueType';
import { useWorkLocation } from '../../hooks/useWorkLocation';
import { useUserStore } from '@/store/modules/user';

enum SourceType {
  ai = 1,
  manual = 2
};

interface Props {
  initialData?: FormModel
};

interface FormModel {
  id?: number,
  source?: number,         // 来源
  issueType?: number,      // 类型
  description?: string,    // 描述
  pictures?: string[],     // 图片
  workshopId?: number,     // 车间id
  workspaceId?: number,    // 工位id
  issueTime?: string,      // 时间（issueTime为空时填充createdAt）
  issueState?: number,     // 状态
};

const visible = ref(true);
const { aiOptions, manualOptions, getAIOptions, getManualOptions } = useIssueType();
const { locationOptions, getLocationOptions } = useWorkLocation();

const props = defineProps<Props>();
const emits = defineEmits(['saveForm', 'closeForm']);

const formRef = ref<FormInstance>();
const formData = reactive<FormModel>({
  id: undefined,
  source: undefined,
  issueType: undefined,
  description: '',
  pictures: [],
  workshopId: undefined,
  workspaceId: undefined,
  issueTime: '',
  issueState: undefined
});

const location = { expandTrigger: 'hover' as const };
const workLocation = ref<[number | undefined, number | undefined] | []>([]);

const handleSelectChange = () => {
  formData.issueType = undefined;
};
const options = computed(() => {

  if (Number(formData.source) === SourceType.ai && aiOptions.value.length > 0) {
    return aiOptions.value;
  }
  if (Number(formData.source) === SourceType.manual && manualOptions.value.length > 0) {
    return manualOptions.value;
  }
  return []
});
const handleCascaderChange = () => {
  formData.workshopId = workLocation.value[0];
  formData.workspaceId = workLocation.value[1];
};

const handleCopyData = () => {
  formData.id = props.initialData?.id;
  formData.source = props.initialData?.source;
  formData.issueType = props.initialData?.issueType;
  formData.description = props.initialData?.description;
  formData.pictures = props.initialData?.pictures;
  formData.workshopId = props.initialData?.workshopId;
  formData.workspaceId = props.initialData?.workspaceId;
  formData.issueTime = props.initialData?.issueTime;
  formData.issueState = props.initialData?.issueState;

  workLocation.value = [props.initialData?.workshopId, props.initialData?.workspaceId!];
  fileList.value = props.initialData?.pictures?.map(str => ({ name: str, url: str })) || [];
};

// 取消
const handleCancel = () => {
  emits('closeForm');
};

// 保存
const handleSubmit = () => {
  emits('saveForm', formData);
};

// 图片上传
const userStore = useUserStore();
const getHeaders = () => {
  return { Satoken: userStore.getToken, Tenantid: userStore.getTenantId };
};
const handleAvatarSuccess = (res) => {
  if (!formData.pictures) formData.pictures = [];
  formData.pictures.push(res.data.url);
};
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  const index = formData.pictures?.indexOf(uploadFile.url || '')!;
  if (index !== -1) formData.pictures?.splice(index, 1);
};
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

onMounted(() => {
  handleCopyData();
});

onBeforeMount(() => {
  getAIOptions();
  getManualOptions();
  getLocationOptions();
});
</script>

<style scoped></style>