<template>
  <el-form ref="form" label-width="80px" class="share-from">
    <el-form-item label="链接">
      <el-input :modelValue="shareLink" placeholder="请输入项目编号" disabled />
    </el-form-item>
    <el-form-item label="密码">
      <el-input
        :modelValue="randCode"
        @input="(val: string) => filterPSW(val)"
        placeholder="请输入密码"
        style="width: 120px"
      />
    </el-form-item>
    <el-form-item>
      <p class="maker">
        注：链接可发送给有需要的人员，需使用密码访问。有效期
        <b style="color: #26559b">14</b>
        天，过期后不可访问。
      </p>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watchEffect } from "vue";
import { EPSW } from "@/constant/REG";
import { ElMessage } from "element-plus";
import { copyText } from "@/util";
import { getQuery } from "@/view/case/help";
import { Fire, getFire } from "@/app/fire/store/fire";
import { getCaseSharePWD, setCaseSharePWD } from "@/store/case";
import { QuiskExpose } from "@/helper/mount";

const props = defineProps<{ caseId: number }>();
const randCode = ref("");
const oldRandCode = ref("");

const shareLink = computed(() => getQuery(props.caseId));

const filterPSW = (val: string) => {
  if (val.length > 4) {
    return;
  } else if (EPSW.REG.test(val.substr(val.length - 1))) {
    randCode.value = val;
  } else {
    ElMessage.error(EPSW.tip);
  }
};

defineExpose<QuiskExpose>({
  async submit() {
    if (!randCode.value || randCode.value.length !== 4) {
      ElMessage.error("请输入四位数的密码！");
      throw "请输入四位数的密码！";
    }
    if (randCode.value !== oldRandCode.value) {
      await setCaseSharePWD({
        caseId: props.caseId,
        randCode: randCode.value,
      });
    }
    const result = `链接:${shareLink.value} 密码:${randCode.value}`;
    copyText(result);
    ElMessage.success("链接复制成功");
    return result;
  },
});

watchEffect(async () => {
  if (shareLink.value) {
    const code = await getCaseSharePWD({ caseId: props.caseId });
    oldRandCode.value = randCode.value = code;
  }
});
</script>
