<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, onMounted, nextTick } from "vue";
import { dealTask, addUploadFile } from "../../../api/disposal";
import ViewDetail from "../components/viewDetail.vue";
import { detailTask, issueTask } from "../../../api/disposal/notify";
import { ElMessage } from "element-plus";
const uploadRef = ref({});
let formData = reactive({
  comment: "", // 处理结果
  informId: "", // 通报任务ID
  taskId: "", // 流程id
  outcome: "", // 按钮 参数: 通过/驳回
  flag: "", // 结果标识 0 通过 1 驳回
  informFileName: [], // 附件
});
const formColumns = reactive([
  {
    key: "comment",
    type: "textarea",
    label: "审核结果",
    col: 24,
    placeholder: "请输入内容",
    clearable: true,
    rows: 4,
    tooltip: "请输入1-200个字符",
    showWordLimit: true,
    maxlength: "200",
  },
  {
    label: "添加附件",
    tooltip: "这里上传附件",
    col: 24,
    slotName: "fileName",
  },
]);
const rules = reactive<FormRules>({
  comment: [{ required: true, message: "请输入审核结果", trigger: "blur" }],
});

const dialogForm = ref({});
const dialogType = ref("add");
const Info = ref({});
const drawerProps = reactive({
  showDrawer: false,
  title: "通过",
  size: "small",
});
const drawerFormDisabled = ref(false);
const init = (e, title) => {
  console.log(e, "========");
  Info.value = e;
  formData.informId = e.informId;
  formData.taskId = e.taskId;
  formData.comment = "";
  formData.outcome = "";
  formData.informFileName = [];
  drawerProps.title = title;
  // uploadRef.value.fileList = []
  if (title == "通报任务详情") {
    drawerProps.size = "big";
    drawerFormDisabled.value = true;
    viewBtn(e);
  } else if (title == "下发") {
    dialogType.value = "add";
    drawerProps.size = "small";
    drawerFormDisabled.value = false;
    drawerProps.showDrawer = true;
    formColumns[0].label = "研判结果";
    rules.comment[0].message = "请输入研判结果";
  } else if (title == "上报") {
    dialogType.value = "add";
    drawerProps.size = "small";
    drawerFormDisabled.value = false;
    drawerProps.showDrawer = true;
    formColumns[0].label = "处置结果";
    rules.comment[0].message = "请输入处理结果";
  } else {
    dialogType.value = "add";
    drawerProps.size = "small";
    drawerFormDisabled.value = false;
    drawerProps.showDrawer = true;
    formColumns[0].label = "审核结果";
    rules.comment[0].message = "请输入审核结果";
  }
};
defineExpose({ init });
const emit = defineEmits(["onInit"]);
const handleDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  console.log(eventName);
  if (eventName === "success") {
    if (dialogType.value == "add") {
      handleConfirm();
    }
  }
};
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
const handleCloseDrawer = async (done) => {
  done();
};
const handleEvent = (data) => {
  if (data.eventName == "errorSubmit") {
    return;
  }
  if (data.eventName === "successSubmit") {
    handleFormSuccess();
    return;
  }
};
const uploadTime = ref(false);
const handleFormSuccess = async () => {
  if (uploadRef.value.fileList.length > 0) {
    formData.informFileName = uploadRef.value.fileList.map((item) => {
      return item.informFileName;
    });
  } else {
    formData.informFileName = [];
  }
  if (
    drawerProps.title == "通过" ||
    drawerProps.title == "上报" ||
    drawerProps.title == "下发"
  ) {
    formData.outcome = "通过";
    formData.flag = 0;
  } else if (drawerProps.title == "驳回") {
    formData.outcome = "驳回";
    formData.flag = 1;
  }
  let parms = {
    ...formData,
  };
  if (uploadTime.value) return ElMessage.warning("附件上传中,请稍后再试！");
  let res = await dealTask(parms);
  if (res.code == 200) {
    ElMessage.success(drawerProps.title + "成功！");
    drawerProps.showDrawer = false;
    emit("onInit");
  }
};
// 附件上传
let fileList = ref([]);
const removedata = (uploadFile, uploadFiles) => {};
const handleChange = async (uploadFile, uploadFiles) => {
  // uploadRef.value.fileList = uploadFiles;
  console.log(uploadRef.value.fileList);
  let flg = beforeAvatarUpload(uploadFile);
  if (flg) {
    uploadTime.value = true;
    let fd = new FormData();
    fd.append("file", uploadFile.raw);
    let requre = "";
    try {
      let res = await addUploadFile(fd);
      if (res.code == 200) {
        uploadTime.value = false;
        // formData.file = res.data;
        uploadRef.value.fileList[
          uploadRef.value.fileList.length - 1
        ].informFileName = res.data;
        // console.log(uploadRef.value.fileList);
      } else {
        uploadTime.value = false;
        let _data = uploadRef.value.fileList.findIndex((item) => {
          return item.name == uploadFile.name;
        });
        uploadRef.value.fileList.splice(_data, 1);
      }
      setTimeout(() => {
        uploadTime.value = false;
      }, 1000);
    } catch (error) {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == uploadFile.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
      uploadTime.value = false;
      ElMessage.error("文件上传失败，上传文件不符合规范！");
    }
  }
};
const beforeAvatarUpload = (file) => {
  let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension2 =
    testmsg === "xlsx" ||
    testmsg === "jpg" ||
    testmsg === "png" ||
    testmsg === "pdf" ||
    testmsg === "txt" ||
    testmsg === "xls" ||
    testmsg === "doc" ||
    testmsg === "docx" ||
    testmsg === "rar" ||
    testmsg === "zip" ||
    testmsg === "wps" ||
    testmsg === "pptx";
  if (!extension2) {
    ElMessage.error("文件上传格式不正确");
    nextTick(() => {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == file.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
    });
    return false;
  } else if (file.size / 1024 / 1024 > 200) {
    ElMessage.error("单个文件最多只能上传200MB!");
    nextTick(() => {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == file.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
    });

    return false;
  }
  return true;
};
// 详情
const viewObj = ref({});
const viewBtn = (row) => {
  console.log(row, "]][[]]");
  dialogType.value = "view";

  getDetail(row);
};
const getDetail = async (e) => {
  let parms = {
    id: e.informId,
  };
  let res = await detailTask(parms);
  if (res.code == 200 && res.data) {
    let row = res.data;
    let obj = {
      title: e.informName,
      level: e.informLevel,
      creatorName: e.createPersonName, // 创建人
      createTime: e.createTime, // 创建时间
      issueTime: e.issueTime, // 下发时间
      status: row.informStatus,
      enterpriseType: 2,
      desObj: {
        title: "通报描述",
        content: e.informDescribe,
      },
      enterpriseTypeList: [
        e.enterpriseName,
        e.braceName,
        e.isJudge == 0 ? "是" : "否",
      ],
      fileList: e.informFileName,
      dealList: [],
    };
    obj.dealList = res.data.detail;
    viewObj.value = obj;
    drawerProps.showDrawer = true;
    nextTick(() => {});
  }
  console.log(res);
};

let dialogProps = reactive({
  showDialog: false,
  size: "",
  title: "",
  noHeader: true,
});
// 下发
const issueBtn = (row) => {
  dialogProps.showDialog = true;
  formData = row;
};
const sendHandleConfirm = async () => {
  let parms = {
    informId: formData.informId,
    taskId: formData.taskId,
    outcome: "通过",
    flag: 0,
    comment: "",
    informFileName: [],
  };
  let res = await dealTask(parms);
  if (res.code == 200) {
    dialogProps.showDialog = false;
    ElMessage.success("下发成功");
    emit("onInit");
  }
};
</script>
<template>
  <!-- 新增/编辑 -->
  <ya-drawer
    :drawerProps="drawerProps"
    :showConfirm="!drawerFormDisabled"
    @handleEvent="handleDrawerEvent"
    destroy-on-close
    :before-close="handleCloseDrawer"
  >
    <template #content>
      <ya-form
        v-if="dialogType == 'add'"
        label-position="top"
        @handleEvent="handleEvent"
        :formColumns="formColumns"
        labelWidth="100px"
        :formData="formData"
        :rules="rules"
        :ref="
          (el) => {
            if (el) dialogForm = el;
          }
        "
      >
        <template #fileName>
          <YaUpload
            :before-remove="removedata"
            :before-upload="beforeAvatarUpload"
            accept=".xlsx,.png,.jpg,.pdf,.txt,.xls,.doc,.docx,.rar,.zip,.wps,.pptx"
            :showUploadTip="false"
            :limit="0"
            @handleChangeUpload="handleChange"
            :auto-upload="false"
            drag
            ref="uploadRef"
            :action="''"
          >
          </YaUpload>
        </template>
      </ya-form>
      <div v-if="dialogType == 'view'">
        <ViewDetail :viewObj="viewObj" />
      </div>
    </template>
  </ya-drawer>
  <div class="dialog-content">
    <ya-dialog :dialogProps="dialogProps">
      <template #title>
        <div><i class="iconfont icon-tishi ya-primary-color"></i> 下发任务</div>
      </template>
      <template #content>是否确认下发?</template>
      <template #footer>
        <ya-button @click="dialogProps.showDialog = false">取消</ya-button>
        <ya-button type="primary" @click="sendHandleConfirm">确定</ya-button>
      </template>
    </ya-dialog>
  </div>
</template>
<style lang="scss" scoped></style>
