<!-- 应急物资分类表 -->
<template>
  <basic-container>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      :disabled="props.type == 'look'"
    >
      <el-row :gutter="20">
        <el-col :span="19">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="ruleForm.gender" clearable>
                  <el-option v-for="item in gender" :key="item.id" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nationality">
                <el-select v-model="ruleForm.nationality" clearable>
                  <el-option v-for="item in nation" :key="item.id" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="健康状况" prop="healthStatus">
                <el-select v-model="ruleForm.healthStatus" clearable>
                  <el-option v-for="item in health_condition" :key="item.id" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthDate">
                <el-date-picker
                  clearable
                  style="width: 100%"
                  v-model="ruleForm.birthDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledDate"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="age" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="籍贯" prop="originPlace">
                <el-input v-model="ruleForm.originPlace" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文化程度" prop="educationLevel">
                <el-select v-model="ruleForm.educationLevel" clearable>
                  <el-option v-for="item in educational_level" :key="item.id" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="ruleForm.idCard" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phoneNumber">
                <el-input v-model="ruleForm.phoneNumber" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="5">
          <el-upload
            class="avatar-uploader"
            :action="fileUrl"
            :data="paramsData"
            :headers="myHeader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ruleForm.driverPhotoAddress" :src="driverPhotoAddressBlob" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-col>
        
        <el-col :span="24">
          <el-form-item label="联系地址" prop="contactAddress">
            <el-input v-model="ruleForm.contactAddress" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驾照类型" prop="drivingLicenseType">
            <el-select v-model="ruleForm.drivingLicenseType" clearable>
              <el-option v-for="item in driver_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驾驶证号" prop="drivingLicense">
            <el-input v-model="ruleForm.drivingLicense" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="初领时间" prop="firstIssueDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.firstIssueDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="operationbox">
      <el-button v-if="props.type != 'look'" type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="returnPage">返回</el-button>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from "vue";
import type { FormInstance } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import router from "@/router";
import type { UploadProps } from "element-plus";
import { useDict } from "@/hooks/dict";
import { ElMessage } from "element-plus";
import { sysFile } from "@/api/inAndOut/formationFilling/in";
import { addDriverInfo, getDriverDetail, updataDriverInfo } from "@/api/transportationMng";
import { useGetters } from "@/hooks/storeHooks";
const { access_token } = useGetters(["access_token"])
import { getQuery } from "@/hooks/detailQuery/index";
const props = getQuery("/transportationMng/driverMngDetail");

const { gender, nation, health_condition, driver_type, educational_level } = useDict(
  "gender",
  "nation",
  "health_condition",
  "driver_type",
  "educational_level"
); 

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  name: "",
  gender: "",
  nationality: "",
  healthStatus: "",
  birthDate: "",
  originPlace: "",
  educationLevel: "",
  idCard: "",
  phoneNumber: "",
  contactAddress: "",
  drivingLicenseType: "",
  drivingLicense: "",
  firstIssueDate: ""
});
const driverPhotoAddressBlob = ref("")
const age = computed(() => {  
  if (!ruleForm.value.birthDate) return null;  

  const birthDate = new Date(ruleForm.value.birthDate);  
  const today = new Date();  

  let age = today.getFullYear() - birthDate.getFullYear();  
  const m = today.getMonth() - birthDate.getMonth();  
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {  
    age--;  
  }  

  return age;  
}); 
const fileName = ref("");
const rules = reactive({
  name: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  gender: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  nationality: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  birthDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  originPlace: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  idCard: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  phoneNumber: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  contactAddress: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  drivingLicenseType: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  drivingLicense: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  firstIssueDate: [{ required: true, message: "请填写，不能为空", trigger: "change" }]
});
//提交方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let postData = {
        ...ruleForm.value
      };
      console.log(postData);
      if(props.type == "edit"){
        delete postData.age
        updataDriverInfo(postData).then((res: any) => {
          if (res.code === 0) {
            ElMessage({
              message: "修改成功！",
              type: "success"
            });
            returnPage();
          }
        });
      }else{
        addDriverInfo(postData).then((res: any) => {
          if (res.code === 0) {
            ElMessage({
              message: "新增成功！",
              type: "success"
            });
            returnPage();
          }
        });
      }
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
const createdMth = async () => {
  if(props.id){
    let deptData = await getDriverDetail(props.id);
    ruleForm.value = deptData.data;
    handlePreview(deptData.data.driverPhotoAddress)
  }
};
createdMth();
const handlePreview = (filePart) => {
  sysFile(filePart).then((res: any) => {
    const blob = new Blob([res], { type: "image/png" });
    const bFile = URL.createObjectURL(blob);
    fileName.value = filePart;
    driverPhotoAddressBlob.value = bFile;
    ruleForm.value.driverPhotoAddress = filePart;
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  createdMth();
};

/*----------------------头像-----------------*/
//附件部分
const myHeader = { Authorization: "Bearer " + access_token.value };
const fileUrl = "/admin/sysFile/uploadVoucher";
let paramsData = reactive({
  bucket: "bound"
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  handlePreview(response.data.fileName);
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // if (rawFile.type !== "image/jpeg") {
  //   ElMessage.error("Avatar picture must be JPG format!");
  //   return false;
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error("Avatar picture size can not exceed 2MB!");
  //   return false;
  // }
  return true;
};

/** 返回 */
const returnPage = (row: any) => {
  router.push({
    path: "/transportationMng/driverMng"
  });
};
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
