<template>
  
    <span style="
    font-family: PingFang-SC-Regular;
    font-size: 12px;
    color: #666666;
    font-weight: 400;">联系人信息</span>
    <el-form
    :model="mail" 
    :rules="rules"
    label-width="120px"  
    style="margin-top: 0.9%;display: flex;flex-direction: column;
    flex-wrap: nowrap;min-height: 100vh;" 
    label-position="left"
    ref="formRef"
    v-loading="loading">
      <el-form-item label="联系人姓名" :required="true"  prop="contactName" >
        <el-input v-model="mail.contactName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="称呼" prop="contactSex"   >
        <el-radio-group v-model="mail.contactSex" >
            <el-radio label="M">先生</el-radio>
            <el-radio label="F">女士</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件号码"  prop="contactIdCard" type="text"  >
        <el-input v-model="mail.contactIdCard" placeholder="请输入证件号码" />
      </el-form-item>
      <el-form-item label="联系电话"  prop="contactPhone" >
        <el-input v-model="mail.contactPhone" placeholder="请输入联系电话" />
                        
                            <el-button
                                size="small"
                                type="primary"
                                @click="smsSendCode"
                                :disabled="sendBtnDisabled"
                                class="send-btn"
                                >{{
                                    sendBtnDisabled
                                        ? `${time}秒后重发`
                                        : "发送验证码"
                                }}</el-button>
                        
      </el-form-item>
      <el-form-item label="验证码"  prop="code">
        <el-input v-model="mail.code" placeholder="请输入验证码" oninput="value=value.replace(/[^\d.]/g,'')"/>
      </el-form-item>
      <span style="width: 48px;
            font-family: PingFang-SC-Regular;
            font-size: 12px;
            color: #666666;
            font-weight: 400;
            position: relative;
            top: -8px;
            right: 9px;">信件内容</span>
      <el-form-item label="案件编号"  prop="caseNumber" >
        <el-input v-model="mail.caseNumber" placeholder="如有具体案件编号请输入案件编号"/>
      </el-form-item>
      
        <el-form-item label="被投诉/涉及单位" >
      <el-select
      style="top: -5px;"
        v-model="mail.involvedDeptName"
        placeholder="请选择单位"
        @change="selectMediaId"
        ref="mySelected"
      >
        <el-option v-for="item in depts"
         :key="item.value" 
         :label="item.text"
         :value="item.text"
         ref="select"  />
      </el-select>   
        </el-form-item>   
      
        <div class="redClass"> 
        <el-form-item label="信件内容" prop="content"   class="contentforitem">
            
            <el-input v-model="mail.content" @input="timeEffectInput"  resize="none"   type="textarea" class="content" placeholder="请您尽量完整的描述您的信件内容，如发生事件、涉及单位、涉及对象姓名、警号以及具体事项"  /> 
            <!-- <span ref="contentSpan" style="">{{ mail.content ? mail.content.length : 0 }}/300</span> -->
        </el-form-item>
        </div>
        
        <div style="position: relative; display: flex; flex-direction: column;">
        <span>附件</span>
        
        <el-upload
        
          v-model:file-list="mail.attachments"
          action="/api/file/upload"
          :http-request="uploadAction"
          :headers="headers"
          list-type="picture-card"
          :limit="5"
          :show-file-list="true"
          :auto-upload="true"
          multiple
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          
        </el-upload>
        <span class="uploadSign">最多只能上传9张图片，支持格式为png、jpg、gif、svg</span>
        <el-dialog v-model="previewVisible" title="图片预览">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
        
      
     <el-form-item class="commit">
      <el-button class="button1"  @click="handleSaveDraft">存稿</el-button>
      <el-button class="button2" @click="handleSave">提交</el-button>
    </el-form-item>
  </div>
    </el-form>
  
</template>
<script setup>
import { reactive } from 'vue'
import { ref } from 'vue'
import { validatorIdCard, validatorPhone ,validatorContent,Phone} from "@/util/validator copy";
import { getToken } from "@/util/cookie";
// import UserStore from "@/store/user";
import PageStore from "@/store/page";
import { addMail } from "@/api/mail";
import { depts } from "@/store/dept";
import { send } from "@/api/sms";
import { saveDraft, getDraft } from "@/api/mailDraft";
// const userStore = UserStore();
const pageStore = PageStore();
const mySelected = ref();
const imgurl = ref();
const loading = ref(false);
imgurl.value = "/imgs/FaultUpload.jpg"
const rules= {	
  contactName: [ { type: 'string',required: true,message: "", trigger: 'blur'}, {max: 30,message: "名称长度不能超过30位" }],
      contactPhone: [{ required: true, validator: validatorPhone, trigger: "blur" },
          ],
      contactIdCard: [{ required: true, validator: validatorIdCard, trigger: "blur" },
          ],
      code:[{ required: true, message: "请输入验证码", trigger: "blur" },
          ],
      content:[{ required: true, validator: validatorContent, trigger: "blur" },
      ],
} 

const headers = reactive({"Authorization": getToken()});
const previewVisible = ref(false);
const dialogImageUrl = ref('');
const select = ref('');
const mail = ref({
    contactName: '',
    contactIdCard: '',
    contactPhone: '',
    contactSex: '',
    smsRequestId: '',
    content: '',
    code:'',
    involvedDeptName:'',
    attachments:''
  })

const mailData = ref({
    contactName: '',
    contactIdCard: '',
    contactPhone: '',
    contactSex: '',
    smsRequestId: '',
    content: '',
    code:'',
    involvedDeptId:'',
    involvedDeptName:'',
    attachments:[]
  })

//预览图片
const handlePictureCardPreview = (filepath) => {
  console.log(filepath)
  dialogImageUrl.value = filepath.url;
  previewVisible.value = true;
};


initMail();
function initMail() {
    mail.value = {
        contactName: '',
        contactIdCard: '',
        contactPhone: '',
        contactSex: 'M',
        content: "",
        attachments: [],
    };
}
const list = ref([])
watch(
    () => pageStore.mailTabActive,
    () => {
      
        if (pageStore.mailDraftId) {
            
            getDraft(pageStore.mailDraftId).then((data) => {
                mail.value = data;
                mailData.value.attachments = JSON.parse(data.attachments);
                console.log( mailData.value.attachments.filepath)
                list.value = []
                for(const i of mailData.value.attachments){   
                  let obj = new Object(); 
                  console.log(i.filepath)
                  obj.url = "/api/file/stream/"+i.filepath;
                  list.value.push(obj);
                }
                
                // mailData.value.attachments = list.value;
                mail.value.attachments = list.value;
                
            });

            pageStore.mailDraftId = "";
        }
    }
);

const filepath = ref();
const  handleSuccess = (obj,response,file) =>{
        console.log(response.response.data.filepath);
        //拼接得到图片信息对象
        filepath.value = response.response.data.filepath;
        //将图片信息对象，push到数组中
        mailData.value.attachments.push({filepath: filepath.value})
        console.log("response.response"+response.response)
        console.log("mailData.value.attachments"+mailData.value.attachments)
}

//移除图片
const handleRemove = (file, fileList) => {
  // console.log('handleRemove', handleRemove);
   console.log('file', file);
   var index =  mailData.value.attachments.findIndex(
            temp => {
                if(file.name == temp.file){
                    return true
                }
            }
        );
   mailData.value.attachments.splice(index,1)
  console.log('fileList', fileList);
};

const emit = defineEmits(['childWriter-msg'])

const handleSaveDraft = () => {
    formRef.value.validate().then(() => {
        mailData.value.code = mail.value.code;
        mailData.value.contactIdCard = mail.value.contactIdCard;
        mailData.value.contactName = mail.value.contactName;
        mailData.value.content = mail.value.content;
        mailData.value.contactPhone = mail.value.contactPhone;
        mailData.value.smsRequestId = mail.value.smsRequestId;
        mailData.value.contactSex = mail.value.contactSex;
        // mailData.value.attachments = mail.value.attachments;
        loading.value = true;
        ElMessageBox.confirm(
        '确定提交草稿内容吗？',
        '提示',
        {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        }
        )
        .then(() => {
          saveDraft(mailData.value).then((data) => {
            loading.value = false;
            mail.value.id = data.id;
            initMail();
            // 刷新我的草稿
            pageStore.mailTabActive = "draft"
            pageStore.myMailDraftRefresh = true
          });
        ElMessage({
        type: 'success',
        message: '提交成功',
        })
        })
        .catch(() => {
          loading.value = false,
        ElMessage({
        type: 'info',
        message: '取消提交',
        })
        
        })
        
    });
};

const handleSave = () => {
    formRef.value.validate().then(() => {
        mailData.value.code = mail.value.code;
        mailData.value.contactIdCard = mail.value.contactIdCard;
        mailData.value.contactName = mail.value.contactName;
        mailData.value.content = mail.value.content;
        mailData.value.contactPhone = mail.value.contactPhone;
        mailData.value.smsRequestId = mail.value.smsRequestId;
        mailData.value.contactSex = mail.value.contactSex;
        loading.value = true;
        ElMessageBox.confirm(
    '确定提交信件吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      addMail(mailData.value)
            .then(() => {
                loading.value = false;
                // showSuccessToast("提交成功");
                // 跳转到我的信件
                pageStore.mailTabActive = "my";
                // 刷新我的信件
                pageStore.myMailRefresh = true
                // 更新用户联系电话
                // userStore.user.phone = mail.value.phone;
                initMail();
                setTimeout(() => {
                emit('childWriter-msg', "my")
                }, 300)
                })
            .catch(() => {
                loading.value = false;
            });
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
    })
    .catch(() => {
      loading.value = false;
      ElMessage({
        type: 'info',
        message: '取消提交',
      })
    })
    });
    

};




function selectMediaId(depart){
      console.log(mySelected.value, 'select值')
      for (const i of depts) {
                if(i.text == depart){
                   mailData.value.involvedDeptId=i.value;
                   mailData.value.involvedDeptName=i.text;
                   
                }
            }
      // console.log(mailData.value.involved_dept_id, 'select值')
      // console.log(depart, '选中的ID值')
}

const formRef = ref();

const sendBtnDisabled = ref(false);
let time = ref(30);

function smsSendCode() {
  formRef.value.validateField('contactPhone', (valid) => {  
        if (valid) {  
          sendBtnDisabled.value = true;
        // 发送短信
        send(mail.value.contactPhone).then((data) => {
            mail.value.smsRequestId = data.requestId;
        });
        let timer = setInterval(() => {
            time.value -= 1;
            if (time.value <= 0) {
                sendBtnDisabled.value = false;
                clearInterval(timer);
                time.value = 30;
            }
        }, 1000);
        } else {  
          return;
        }  
      }); 
}
const contentSpan = ref();

function timeEffectInput() {
      console.log(mail.value)
      // contentData = mail.value
      const length = mail.value.content.length  // 先拿到当前输入时文本域文字长度
      if (length > 300) {  // 当长度超过200
      	// 获取文本域计数统计设置字体为红色
        contentSpan.style = 'color:red' 
       	// 防止后续输入溢出截取0-200的字符
         mail.value.content = mail.value.content.substr(0, 300)
      } else {
        contentSpan.style  = 'color:#909399'
      }
    }

</script>



<style lang="scss" scoped>

.wrapper {
    background-color: #fff;
    
}
.commit{
  margin-top: 50px;
}
span{
   
font-family: PingFang-SC-Regular;
font-size: 12px;
color: #666666;
font-weight: 400;   
margin-left: 0.8%;
    }
.content{
  width: 1112px;
  resize:none;
  // height: 64px;
  font-family: PingFangSC-Regular;
  font-size: 14px;
  color: #CCCCCC;
  font-weight: 400;
  position: relative;
  
}

.releative{
  
  .el-button{
    width: 77px;
    height: 24px;
    background: #0E5A98;
    border-radius: 2px;
      span{
        width: 60px;
        height: 17px;
        font-family: PingFang-SC-Regular;
        font-size: 12px;
        color: #FFFFFF;
        letter-spacing: 0;
        text-align: right;
        font-weight: 400;
      }
  }
}    
::v-deep .el-form-item__label {
font-family: PingFang-SC-Regular;
font-size: 14px;
color: #333333;
letter-spacing: 0;
line-height: 20px;
font-weight: 400;
}
::v-deep .el-form-item__content{
  display: flex;
    flex-direction: row;
    justify-content: space-between;
}
.el-form-item{
  position: relative;
  display: flex;
  box-shadow: inset 0px -1px 0px 0px rgba(217,217,217,1);
  align-items:baseline;
  height:5.5vh;
}
::v-deep .el-select__wrapper {
  width: 16vw;
  min-height:unset;
}
.el-input{

    width: 16vw;
height: 2.3vh;
font-family: PingFang-SC-Regular;
font-size: 14px;
color: #999999;
letter-spacing: 0;
font-weight: 400;
}

.el-radio__label{

font-family: PingFang-SC-Regular;
font-size: 14px;
color: #999999;
letter-spacing: 0;
font-weight: 400;
}

::v-deep .el-upload--picture-card{
  background-size: cover; 
background-image: url('/imgs/FaultUpload.jpg');
}
::v-deep .contentforitem{
  display: flex;
  flex-direction: column;
  height: 20vh;
  margin-bottom: 2vh;
  box-shadow:none;
}
// ::v-deep .el-icon::before {
//             content: '';
//             position: absolute;
//             width: 31.25px;
//             border-top: 4.16px solid;
//             color: cornflowerblue;
//         }
//         ::v-deep .el-icon::after {
//             content: '';
//             position: absolute;
//             height: 31.25px;
//             border-left: 4.16px solid;
//             color: cornflowerblue;
//         }
::v-deep .el-select__suffix{
  visibility:hidden;
}        
.uploadSign{
  position: relative;
  top: 10px;
font-family: PingFang-SC-Regular;
font-size: 12px;
color: #333333;
letter-spacing: 0;
line-height: 17px;
font-weight: 400;
}

::v-deep .commit {
  display: flex;
  box-shadow:none;
  .el-form-item__content{
    justify-content: space-evenly
  }
}

::v-deep .button1{
  position: relative;
  left: -50px;
  width: 266px;
height: 44px;
background: #F3FAFF;
border: 0.5px solid rgba(32,119,192,1);
border-radius: 2px;
  span{
    width: 34px;
height: 24px;
font-family: PingFang-SC-Regular;
font-size: 17px;
color: #0E5A98;
text-align: left;
font-weight: 400;
  }
}

::v-deep .button2{
  width: 266px;
height: 44px;
background: #0E5A98;
border-radius: 2px;
  span{
    width: 34px;
height: 24px;
font-family: PingFang-SC-Regular;
font-size: 17px;
color: #FFFFFF;
text-align: left;
font-weight: 400;
  }
}

::v-deep .redClass .el-form-item__content{
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-items: flex-start;
  .el-textarea{
    display: flex;
  flex-direction: column;
  }
  .el-textarea__inner{
    width: 1200px;
     height: 15vh;
  }
}

</style>