<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="550px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="90px"
        :rules="formRules"
      >
        <el-form-item label="订单编号" prop="order_sn">
          <el-input
            readonly
            v-model="formData.order_sn"
            clearable
            placeholder="请输入订单编号"
          />
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input
            readonly
            v-model="formData.amount"
            clearable
            placeholder="请输入提现金额"
          />
        </el-form-item>
        <el-form-item label="" prop="amount">
          <el-button type="primary" link>
            <router-link
              :to="{
                path: getRoutePath('finance.account_log/lists'),
                query: {
                  company_id: formData.company_id,
                  s_date: formData.s_date,
                  e_date: formData.e_date,
                },
              }"
              >查看明细</router-link
            >
          </el-button>
        </el-form-item>
        <el-form-item label="审核" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.status == 2" label="备注" prop="deny_desc">
          <el-input
            v-model="formData.deny_desc"
            clearable
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item v-else label="转账凭证" prop="transfer_voucher">
          <el-upload
            v-if="mode == 'audit'"
            class="upload-demo"
            style="width: 100%"
            drag
            :headers="{ Token: userStore.token }"
            :action="base_url + '/upload/file'"
            :limit="1"
            :on-success="handleFile"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            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-button v-else type="primary" link @click="openTransfer">
            查看凭证
          </el-button>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
  
<script lang="ts" setup name="withdrawEdit">
import type { FormInstance, UploadRawFile } from "element-plus";
import Popup from "@/components/popup/index.vue";
import {
  apiWithdrawAdd,
  apiWithdrawEdit,
  apiWithdrawDetail,
  withdrawAudit,
} from "@/api/withdraw";
import { timeFormat } from "@/utils/util";
import type { PropType } from "vue";
import { getRoutePath } from "@/router";
import useUserStore from "@/stores/modules/user";
import { genFileId } from "element-plus";
import { inject } from "vue";
const userStore = useUserStore();
const base_url: any = inject("base_url");
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("audit");

// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == "audit" ? "审核提现申请" : "提现申请详情";
});

// 表单数据
const formData = reactive({
  id: "",
  order_sn: "",
  user_id: "",
  admin_id: "",
  amount: "",
  status: "",
  transfer_voucher: "",
  deny_desc: "",
  company_id: "",
  company_name: "",
  s_date: "",
  e_date: "",
});

// 表单验证
const formRules = reactive<any>({
  status: [
    {
      required: true,
      //   message: "请选择审核是否通过",
      validator: (rule: any, value: any, callback: any) => {
        if (value == 1 || value == 2) {
          callback();
        } else {
          callback(new Error("请选择审核是否通过!"));
        }
      },
      trigger: ["blur"],
    },
  ],
  transfer_voucher: [
    {
      required: true,
      message: "请先上传凭证",
      trigger: ["blur"],
    },
  ],
  deny_desc: [
    {
      required: true,
      message: "请填写拒绝原因",
      trigger: ["blur"],
    },
  ],
});

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

const getDetail = async (row: Record<string, any>) => {
  const data = await apiWithdrawDetail({
    id: row.id,
  });
  setFormData(data);
};

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;
  }
};

// 文件选择
const upload = ref(null);
const handleExceed = (files: any) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};

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

// 查看凭证
const openTransfer = () => {
  window.open(formData.transfer_voucher);
};

// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate();
  const data = { ...formData };
  mode.value == (await withdrawAudit(data));
  popupRef.value?.close();
  emit("success");
};

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

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

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