<template>
  <div>
    <ya-form label-position="top" @handleEvent="handleEvent" :formColumns="formColumns" labelWidth="100px"
      :formData="formData" :rules="rules" :ref="(el) => {
        if (el) dialogForm = el;
      }
        ">
      <template #file="{ item }">
        <YaUpload :auto-upload="false" :limit="10000" :size="10"
          :pass="['xlsx', 'jpg', 'png', 'pdf', 'txt', 'xls', 'doc', 'docx', 'rar', 'zip', 'wps', 'pptx']"
          @handleChangeUpload="handleChange" @handleDeleteFile="handleDeleteFile" :showUploadTip=false
          :uploadInfo="uploadInfo" drag ref="uploadRef">
        </YaUpload>
      </template>
    </ya-form>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  defineExpose,
  defineEmits,
  defineProps,
  watch,
  unref
} from "vue";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import Upload from "../../../components/upload/upload.vue";
import { addUploadFile } from "../../../api/fileAnalysis/filesUpload";
import {
  postJudge,
  getIssuePerson,
  postIssue
} from "../../../api/threatAlarms/threatAlarms";
interface Props {
  type?: number; // 1 研判 2 下发
  info?: Object;
  loading?: Boolean
}
const { type = 1, info = {} } = defineProps<Props>();

let dialogForm = ref();
const formData = ref({});
const formColumns1 = [
  {
    key: "handleResult",
    label: "研判方式",
    type: "select",
    clearable: true,
    col: 24,
    options: [
      {
        label: "确认威胁",
        value: 1,
      },
      {
        label: "标记误报",
        value: 2,
      },
    ],
  },
  {
    tooltip: '请上传文件后缀名(.jpg、.png、.pdf、.txt、.xls、.xlsx、.doc、.docx、.rar、.zip、.wps、.pptx)文件,且单个文件大小不超过10M',
    key: "uploadFile",
    label: "添加附件",
    col: 24,
    slotName: "file",
  },
  {
    key: "remark",
    label: "备注",
    type: "textarea",
    clearable: true,
    col: 24,
    showWordLimit: true,
    maxlength: "200",
    rows: 4,
  },
];
const formColumns2 = [
  {
    key: "issuedPerson",
    label: "负责人",
    type: "select",
    clearable: true,
    col: 24,
    options: [],
    onChange(e) {
      console.log(e);
      console.log(personList.value)
      if (e) {
        personList.value.forEach((item) => {
          if (item.value == e) {
            if (item.mail) {
              // formColumns.value[1].disabled = true;
              formData.value.email = item.mail;
            } else {
              // formColumns.value[1].disabled = false;
              formData.value.email = '';
            }
          }
        })
      } else {
        // formColumns.value[1].disabled = false;
        formData.value.email = '';
      }
    },
  },
  {
    key: "email",
    label: "邮件",
    type: "input",
    clearable: true,
    col: 24,
    disabled: false,
  },
];
let formColumns = ref(type == 1 ? formColumns1 : formColumns2);
/**
 * @description 获取下发负责人
 */
const personList = ref([])
if (unref(type) == 2) {
  getIssuePerson({}).then(res => {
    console.log(res)
    if (res.code == 200) {
      formColumns.value.forEach((item) => {
        if (item.key == 'issuedPerson') {
          item.options = res.data.map((item) => {
            return {
              label: item.realityName,
              value: item.id,
              mail: item.mail
            }
          })
          personList.value = item.options;
        }
      })
    }
  })
}
/**
 * @description form规则
 */
const rules = reactive<FormRules>({
  handleResult: [{ required: true, message: "请选择研判方式", trigger: "change" }],
  issuedPerson: [{ required: true, message: "请选择负责人", trigger: "change" }],
  email: [{ required: true, message: "请输入邮件", trigger: "change" }],
});
/**
 * @description 抽屉事件
 */
const handleEvent = function (data) {
  console.log(data.eventName);
  if (data.eventName == "success") {
    handleConfirm();
    return;
  } else if (data.eventName == "successSubmit") {
    if (unref(type) == 1) {
      submit();
    } else {
      issueSubmit()
    }
    return;
  }
};
// 表单确认
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
const emit = defineEmits(["closeF", "resetLoading"]);
const uploadRef = ref(null);
/**
 * @description 研判
 */
const submit = async () => {
  emit("resetLoading")
  let fd = new FormData();
  let uploadFile = uploadRef.value.fileList.map((item) => {
    return item.raw
  })
  for (let i = 0; i < uploadFile.length; i++) {
    fd.append('uploadFile[]', uploadFile[i]);
  }
  for (let i = 0; i < unref(info).ids.length; i++) {
    fd.append('ids[]', unref(info).ids[i]);
  }
  for (let i = 0; i < unref(info).dates.length; i++) {
    fd.append('dates[]', unref(info).dates[i]);
  }
  fd.append("status", 1);
  fd.append("remark", formData.value.remark ? formData.value.remark : '');
  fd.append("handleResult", formData.value.handleResult);
  try {
    let res = await postJudge(fd);
    emit("resetLoading")
    if (res.code == 200) {
      ElMessage.success(res.message);
      emit("closeF");
    }
  } catch {
    emit("resetLoading")
  }

};
/**
 * @description 下发
 */
const issueSubmit = async () => {
  emit("resetLoading")
  try {
    let res = await postIssue({
      ...unref(info),
      ...formData.value,
      status: 2
    });
    emit("resetLoading")
    if (res.code == 200) {
      ElMessage.success(res.message);
      emit("closeF");
    }
  } catch {
    emit("resetLoading")
  }

}
defineExpose({ handleEvent });
/**
 * @description 文件上传
 */
const uploadInfo = ref({
  text: '',
  type: 'success'
})
const handleChange = async (uploadFile, uploadFiles) => {
  uploadInfo.value.type = 'success'
};
/**
 * @description 删除文件
 */
const handleDeleteFile = () => {
  uploadInfo.value.type = 'success'
}
</script>
<style lang="scss" scoped></style>
