<template>
  <div class="container row justify-center">
    <n-form
      :model="formValue"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      label-width="150px"
      label-align="left"
      v-nloading="loading"
      require-mark-placement="left"
    >
    <!-- :disabled="props.artistCertData.artistCertEditStatus === 1" -->
      <n-form-item label="中美协会编号" path="caaCertNum" >
        <n-input
          clearable          
          v-model:value="formValue.caaCertNum"
          placeholder="请输入中美协会编号"
          style="width:406px"
          @input="handleCaaCertNumInput"
        />
      </n-form-item>

      <n-form-item label="加入中美协会日期" path="caaJoinTime">
        <n-date-picker
          v-model:formatted-value="formValue.caaJoinTime"
          type="date"
          formatted-value="YYYY-MM-DD"
          clearable
          placeholder="请选择加入中美协会日期"
          style="width:406px"
        />
      </n-form-item>
      <n-form-item label="美协证/官网截图：" path="resumeFile">
        <n-upload
            v-model:file-list="state.resumeFile"
            directory-dnd
            list-type="image-card"
            :show-preview-button="true"
            show-file-list
            :custom-request="customResumeFileRequest"
            @remove="handleRemoveFile"
            accept="image/*"
            :max="1"
            >
        </n-upload>
        <!-- <fln-form-item
          ref="uploadRef"
          type="upload"
          title="图片上传"
          
          :config="{

            field: 'bankFrontImg',
            placeholder: '请上传美协证/官网截图',
            width: '120px',
          }"
          :val="form.bankFrontImg"
          :otherParams="{
            source: 'artwork',
            mask: '',
            type: 'image',
          }"
          @upLoadFile="handleUploadFile"
          @triggerValChange="handleValChange"
        /> -->
      </n-form-item>
    </n-form>

    <div
      v-if="state.editStatus !== 3"
      class="absolute bottom-[20px] left-1/2 -translate-x-1/2"
    >
      <n-button class="w-[160px] h-[36px]" type="primary" @click="doneSet()" >
        保存
      </n-button>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  h,
  reactive,
  onBeforeMount,
  defineProps,
  defineEmits,
  onMounted,
  getCurrentInstance,
  computed,
} from "vue";
import { NImage, NButton, NInput, useMessage } from "naive-ui";
import {

  updateArtistCert,
} from "@/api/personManage.js";
import flnFormItem from "@/components/flnlayout/form/flnformItem.vue";
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;

const message = useMessage();
const props = defineProps({
  artistUid: {
    type: String,
    required: true,
  },
  artistName: {
    type: String,
    required: true,
  },
  artistCertData:{
    type: Object,
    required: true,
  },
});
const formValue = ref({
  resumeFile:[],
  caaCertNum: null,
  caaJoinTime: null,
});
const state = reactive({
  resumeFile:[],
  caaCertNum: null,
  caaJoinTime: null,
  editStatus: 0,
  operationManualUrl: null,
})
const rules = {
  resumeFile: [
    {
      required: true,
      message: "请上传美协证/官网截图",
      trigger: "blur",
    },
  ],
  caaCertNum: [
    {
      required: true,
      message: "请输入中美协会编号",
      trigger: "blur",
    },
  ],
  caaJoinTime: [
    {
      required: true,
      message: "请选择加入中美协会日期",
      trigger: ["blur", "change"]
    },
  ],
};

//上传文件
const customResumeFileRequest = (e) => {
  const maxSize = 10 * 1024 * 1024;
  if (e.file.file.size > maxSize) {
    message.error("文件大小超过10MB，已阻止上传！");
    state.resumeFile = state.resumeFile.filter(f => f.id !== e.file.id);
    return;
  }
  message.info("上传文件中。。。");
  const params = {
    file: e.file.file,
    source: "caaCert",
    mask: "",
    type: e.file.file?.type,
  };
  $request.HTTP.components.uploadFormData("upload/img", params).then(
    (res) => {
      if (res.status === 0) {
        message.success("上传成功");
        e.file.url = res.data.ori_url;
        e.file.status = "finished";
        state.operationManualUrl = e.file.url;
        e.onFinish();
        console.log('1234',state.resumeFile[0].url)
      } else {
        e.onError();
        message.error(res.msg || "操作失败!");
      }
    },
    (err) => {
      message.error(err.message);
    }
  );
};

const doneSet = async () => {
  if(!formValue.value.caaCertNum){
    message.error('请输入中美协会编号')
    return;
  }
  if(!formValue.value.caaJoinTime){
    message.error('请选择加入中美协会日期')
    return;
  }
  if(!state.operationManualUrl){
    message.error('请上传美协证/官网截图')
    return;
  }
  const res = await updateArtistCert({ 
    artistUid:props.artistUid,
    caaCertNum:formValue.value.caaCertNum,
    caaCertImg:state.operationManualUrl,
    caaJoinTime:formValue.value.caaJoinTime,
    artistName:props.artistName,
  });
  if (res.status === 0) {
    message.success('更新成功');
  } else {
    message.error(res.msg);
  }
};
const handleCaaCertNumInput = (value) => {
  // 过滤所有空格（包括中间空格）
  formValue.value.caaCertNum = value.replace(/\s+/g, '');
};

// watch(
//   () => props.artistUid,
//   (newVal) => {
//     if (newVal) {
//       loadData(newVal);
//     }
//   },
//   { immediate: true }
// );


// const handleClick = async () => {
//   const valid = await formRef.value.validate();
//   if (valid) {
//     const bankArea = [form.province, form.city];
//     /*   form.lBankName = branchOptions.value.find((item) => item.value === form.bankCode)?.label;*/
//     console.log(form.lBankName, "form.lBankName");
//     const params = {
//       artistUid: props.artistUid,
//       bankArea: bankArea,
//       bankName: form.bankName,
//       lBankName: form.lBankName,
//       bankNum: form.bankNum,
//       bankCode: form.bankCode,
//       bankFrontImg: form.bankFrontImg,
//       bankBackImg: form.bankBackImg,
//     };
//     try {
//       const res = await updateBankInfoList(params);
//       if (res.code == 200) {
//         processSuccess("更新成功");
//       }
//     } catch (e) {
//       /*   processError(e.message || "更新失败");*/
//     }
//   } else {
//     processError("请填写完整表单");
//   }
// };
// const handleUploadFile = (val) => {
//   console.log('val:', val);
//   const fileSize = val.val?.file?.file?.size;
//   console.log("fileSize", fileSize);
  
//   const maxSize = 10 * 1024 * 1024; // 10MB
  
//   if (fileSize !== undefined && fileSize > maxSize) {
//     const fileSizeMB = (fileSize / (1024 * 1024)).toFixed(2);
//     message.error(`图片大小为${fileSizeMB}MB，不能超过10MB！`);
//     return false;    
//   }
//   return true; // 允许上传
// };


// const handleValChange = ({ val, config }) => {
//   form[config.field] = val;
//   console.log('config', config);
// };
watch(
  () => props.artistCertData,
  (newVal) => {
    if (newVal) {
      formValue.value.caaCertNum = newVal.caaCertNum || null;
      formValue.value.caaJoinTime = newVal.caaJoinTime || null;
      if (newVal.caaCertImg) {
        state.resumeFile = [{
          id: 'existing-file',
          name: '美协证截图',
          url: newVal.caaCertImg,
          status: 'finished'
        }];
        state.operationManualUrl = newVal.caaCertImg;
      } else {
        state.resumeFile = [];
        state.operationManualUrl = null;
      }
      state.editStatus = 2;
    }
  },
  { immediate: true }
);


</script>

<style scoped>
.custom-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
</style>
