<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="580px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="甲方公司名称">
          <el-input
            readonly
            v-model="partyA.company_name"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="甲方对公账号">
          <el-input
            readonly
            v-model="partyA.qualification.corporate_account"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="公司名称" prop="company_name">
          <el-input
            readonly
            v-model="formData.company_name"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="主要联系人" prop="master_name">
          <el-input
            readonly
            v-model="formData.master_name"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="master_phone">
          <el-input
            readonly
            v-model="formData.master_phone"
            clearable
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="押金金额" prop="deposit">
          <el-input
            v-model="formData.deposit"
            type="number"
            :maxlength="10"
            clearable
            placeholder="请输入押金金额"
          />
        </el-form-item>
        <el-form-item label="上传凭证" prop="voucher">
          <el-upload
            class="upload-demo"
            style="width: 100%"
            drag
            :accept="fileTypeList.join(', ')"
            :headers="{ Token: userStore.token }"
            :action="actionUrl"
            :limit="1"
            :on-success="handleFile"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :before-remove="removeFile"
            :on-preview="onPreview"
            ref="upload"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">文件拖入或点击上传</div>
            <template #tip>
              <div class="el-upload__tip">请上传JPG/JPEG/PNG/GIF/PDF文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
  
  <script lang="ts" setup name="withdrawEdit">
import type {
  FormInstance,
  UploadRawFile,
  UploadFile,
  UploadFiles,
} from "element-plus";
import { genFileId } from "element-plus";
import Popup from "@/components/popup/index.vue";
import { getPartyAbyCompanyId } from "@/api/company";
import { timeFormat } from "@/utils/util";
import type { PropType } from "vue";
import { depositRechargeTransferVoucher } from "@/api/company.ts";
import { inject } from "vue";
const base_url: any = inject("base_url");
import useUserStore from "@/stores/modules/user";
import { rules } from "@/views/channel/wx_oa/menu_com/useMenuOa";
const userStore = useUserStore();
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({}),
  },
});
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");

// 弹窗标题
const popupTitle = computed(() => {
  return "凭证录入";
});

// 表单数据
const formData = reactive({
  id: "",
  company_name: "",
  master_name: "",
  master_phone: "",
  deposit: "", // 钱
  voucher: "", // 凭证
});

// 表单验证
const formRules = reactive<any>({
  deposit: [
    {
      required: true,
      message: "请输入押金金额",
      trigger: ["blur"],
    },
  ],
  voucher: [
    {
      required: true,
      message: "请上传凭证",
      trigger: ["blur", "change"],
    },
  ],
});

// 文件选择
const upload = ref(null);
// 文件上传地址
const actionUrl = ref("");
const fileTypeList = [
  "application/pdf",
  "image/jpeg",
  "image/gif",
  "image/png",
];
// 限制上传类型
const beforeUpload = (rawFile: UploadRawFile) => {
  if (!fileTypeList.includes(rawFile.type)) {
    ElMessage.error("请上传JPG/JPEG/PNG/GIF/PDF文件");
    return false;
  }
  if (rawFile.type != "application/pdf") {
    actionUrl.value = base_url + "/upload/image";
  } else {
    actionUrl.value = base_url + "/upload/file";
  }
  return true;
};

const handleExceed = (files: any) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};

const removeFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  formData.voucher = "";
  return true;
};

const onPreview = (event: any) => {
  if (event?.response?.data?.uri) openTransfer(event?.response?.data?.uri);
  else ElMessage("文件错误");
};

// 查看凭证
const openTransfer = (uri: any) => {
  window.open(uri);
};

// 上传文件
const handleFile = (e: any) => {
  if (e.code == 0 && e.show == 1) {
    formData.voucher = "";
    upload.value!.clearFiles();
    return ElMessage.error(e.msg || "上传失败");
  }
  formData.voucher = e.data.uri;
};

// 获取详情
const setFormData = async (data: Record<any, any>) => {
  let obj = {
    id: "",
    company_name: "",
    master_name: "",
    master_phone: "",
  };
  for (const key in obj) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key];
    }
  }
  getDetail();
};

// 甲方公司信息
const partyA = reactive({
  company_name: "",
  qualification: {
    corporate_account: "",
  },
});
const getDetail = async () => {
  getPartyAbyCompanyId({
    company_id: formData.id,
  }).then((data) => {
    partyA["company_name"] = data["company_name"];
    if (typeof data.qualification == "string") {
      data.qualification = JSON.parse(data.qualification);
      partyA.qualification.corporate_account =
        data.qualification.corporate_account;
    } else {
      partyA.qualification.corporate_account =
        data.qualification.corporate_account;
    }
    if (!partyA.qualification.corporate_account) {
      ElMessage.error("甲方公司没有对公账号,请补充账号后再试");
    }
  });
};

// 提交按钮
const handleSubmit = async () => {
  if (!partyA.company_name) return ElMessage.error("甲方公司不可为空");
  if (!partyA.qualification.corporate_account)
    return ElMessage.error("甲方公司对公账户不可为空");
  if (!formData.id) return ElMessage.error("请先选择公司");
  await formRef.value?.validate();
  const data = { ...formData };
  await depositRechargeTransferVoucher({
    company_id: data.id,
    deposit: data.deposit,
    voucher: data.voucher,
  });
  ElMessage.success("录入成功");
  popupRef.value?.close();
  emit("success");
};

//打开弹窗
const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

// 关闭回调
const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  setFormData,
});
</script>
  