<script setup lang="ts">

import { ref , reactive} from 'vue'
import { ElMessage, type FormInstance, type FormProps, type FormRules, type UploadRawFile } from 'element-plus'
import { delImgById, getCompanyDetailByUnicode, saveSelfReport } from '@/views/creditServices/type'
import SmallSearch from '@/components/SmallSearch.vue'
import NewDynamics from '@/components/NewDynamics.vue'
import { downloadFile } from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()

const labelPosition = ref<FormProps['labelPosition']>('left')
const selfReportRef = ref<FormInstance>();
const uploadFilesList = ref<any>([]);
const selfReportForm = ref({
  contactInformation: '',
  contacts: '',
  enterpriseName: '',
  unifiedSocialCreditCode:'',
  complainantIdNumber:'',
  files:uploadFilesList.value
})
const rules = reactive<FormRules<typeof  selfReportForm.value>>({
  contactInformation: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的联系电话', trigger: 'blur' }
  ],
  contacts: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { min: 2, max: 10, message: '请输入正确的联系人', trigger: 'blur' }
  ],
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  complainantIdNumber:[
    { required: true,validator:(rule: any, value: any, callback: any)=>{
        if (value == '') {
          callback(new Error('请输入身份证'))
        }
        if (!/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/.test(value)) {
          callback(new Error('请输入正确的身份证'))
        }
        callback()
      }, trigger: 'blur' }
  ],
  unifiedSocialCreditCode: [
    { required: true,validator:(rule: any, value: any, callback: any)=>{
        if (value == '') {
          callback(new Error('请输入统一社会信用代码'))
        }
        if (!/^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/.test(value)) {
          callback(new Error('请输入正确的统一社会信用代码'))
        }
        callback()
      }, trigger: 'blur' }
  ]
})
const submitReportForm = ()=>{
  selfReportRef.value?.validate( async (valid) => {
    if (valid) {
      const res = await saveSelfReport(selfReportForm.value);
      if(res.code == 200){
        ElMessage.success(res.msg+"即将返回首页");
        setTimeout(()=>{
          router.push('/home')
        },2000)
        canSelfReport.value = false;
        reset()
      }
    }
  })
}
const reset = ()=>{
  selfReportRef.value?.resetFields();
  uploadFilesList.value = [];
  fileList.value = [];
  canSelfReport.value = true;
}
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_URL + '/commonFile/uploadFile',
})
const handleRemove = async (uploadFile:any) => {
  const res = await delImgById(uploadFile.response.data.id);
  if(res.code == 200){
    ElMessage.success('删除成功');
    uploadFilesList.value = uploadFilesList.value.filter((item:any) => item.id != uploadFile.response.data.id);
  }
}

const handleFileSuccess = (q:any)=>{
  isloading.value = false;
  if(q.code == 500){
    ElMessage.error('文件大于了30M')
    return;
  }
  ElMessage.success('上传成功');
  uploadFilesList.value.push(q.data);
}
const fileList = ref([]);
const canSelfReport = ref<boolean>(true);
const BASE_URL = import.meta.env.VITE_APP_BASE_URL;
const isloading = ref<boolean>(false)
const beforeUpload = (q:UploadRawFile)=>{
  if(q.size > 1024*1024*30){
    ElMessage.error('文件大于了30M')
    return false;
  };
  isloading.value = true
}
const checkInformation = async (unicode:string)=>{
  const res = await getCompanyDetailByUnicode(unicode);
  if(res.code == 200){
    res.data.forEach((q:any)=>{
      q.createTime = q.createTime.split('T')[0];
      q.files = q.files.map((w:FileType)=>w.fileOriginalName+"<br>").join("<br>");
      if(!q.files){
        q.files = '没有上传文件';
      }
    })
    companyUploadInformationList.value = res.data;
    dialogVisible.value = true;
  }
}
const dialogVisible = ref(false);
const companyUploadInformationList = ref<any>([]);
</script>

<template>
  <div class="serviceContainer" v-loading="isloading">
    <div class="w-912px ml-auto mr-auto pt-20px mb-20px text-14px">
      你所在的位置：<span class="cursor-pointer">首页</span> > <span class="color-#006eff">企业自主上报</span>
    </div>
    <div class="flex justify-between w-912px mr-a ml-a">
      <div class="w-603px pl-24px pr-24px pt-30px text-black bg-white">
        <div>
          <el-button class="float-right" @click="downloadFile(BASE_URL+'/owSelfReporting/downloadTemplateWord','企业自主上报模版.xlsx')" type="success">下载上报模版</el-button>
          <div>企业自主上报信息</div>
          <div>
<!--            <el-radio-group v-model="labelPosition" aria-label="label position">-->
<!--              <el-radio-button value="left">Left</el-radio-button>-->
<!--              <el-radio-button value="right">Right</el-radio-button>-->
<!--              <el-radio-button value="top">Top</el-radio-button>-->
<!--            </el-radio-group>-->
            <div style="margin: 20px" />
            <el-form
              :label-position="labelPosition"
              label-width="auto"
              :model="selfReportForm"
              ref="selfReportRef"
              style="max-width: 600px"
              :rules="rules"
            >
              <el-form-item label="联系人" prop="contacts">
                <el-input v-model="selfReportForm.contacts" />
              </el-form-item>
              <el-form-item label="联系方式" prop="contactInformation">
                <el-input v-model="selfReportForm.contactInformation" />
              </el-form-item>
              <el-form-item label="身份证号" prop="complainantIdNumber">
                <el-input v-model="selfReportForm.complainantIdNumber" />
              </el-form-item>
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input v-model="selfReportForm.enterpriseName" />
              </el-form-item>
              <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
                <el-input v-model="selfReportForm.unifiedSocialCreditCode" style="width: 290px;" />
                <el-button :disabled="!/^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/.test(selfReportForm.unifiedSocialCreditCode)" type="primary" style="margin-left: 10px" @click="checkInformation(selfReportForm.unifiedSocialCreditCode)">查询上报信息</el-button>
              </el-form-item>
              <el-upload
                ref="uploadRef"
                v-model:file-list="fileList"
                :action="upload.url"
                :on-remove="handleRemove"
                :multiple="true"
                accept=".doc, .docx, .png, .jpg, .pdf, .xls, .xlsx "
                :on-success="handleFileSuccess"
                :data="{moduleName:'上报模块'}"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传附件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    <span style="color: #fd2626">请同时上传信息盖章扫描件和EXCLE电子档</span>
                    <br>
                    <br>
                    只能上传doc docx png jpg pdf xls xlsx文件
                    <br>
                    <br>
                    且大小控制在30M内
                  </div>
                </template>
              </el-upload>
              <el-button @click="submitReportForm" type="primary" :disabled="!canSelfReport">上报</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form>
          </div>
        </div>
      </div>
      <div class="w-294px">
        <SmallSearch />
        <NewDynamics />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="企业上报情况" width="500" draggable>
      <el-table :data="companyUploadInformationList" max-height="300">
        <el-table-column prop="contacts" label="联系人" />
        <el-table-column prop="createTime" label="上报时间" width="150" />
        <el-table-column prop="files" label="上报文件名" width="200">
          <template #default="scope">
            <div v-html="scope.row.files"></div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">
            了解
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.serviceContainer {
  background-color: #ecf0f9;
}
</style>
