<!-- 应急物资分类表 -->
<template>
  <basic-container>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="105px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      :disabled="props.type == 'look'"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <h4>基本信息</h4>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车牌号" prop="licensePlateNumber">
            <el-input v-model="ruleForm.licensePlateNumber" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆类型" prop="vehicleType">
            <el-select v-model="ruleForm.vehicleType" clearable>
              <el-option v-for="item in vehicle_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="驾驶员" prop="driver">
            <el-input v-model="ruleForm.driver" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆品牌" prop="vehicleBrand">
            <el-input v-model="ruleForm.vehicleBrand" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出厂日期" prop="manufactureDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.manufactureDate"
              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="6">
          <el-form-item label="购入日期" prop="purchaseDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.purchaseDate"
              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="6">
          <el-form-item label="购入单位" prop="purchaseUnit">
            <el-input v-model="ruleForm.purchaseUnit" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="购买价格(元)" prop="purchasePrice">
            <el-input v-model="ruleForm.purchasePrice" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="初始公里数" prop="initialKilometers">
            <el-input v-model="ruleForm.initialKilometers" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆状态" prop="vehicleStatus">
            <el-select v-model="ruleForm.vehicleStatus" clearable>
              <el-option v-for="item in vehicle_status" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <h4>详细信息</h4>
        </el-col>
        <el-col :span="6">
          <el-form-item label="耗油量(L/百公里)" prop="fuelConsumption" label-width="auto">
            <el-input v-model="ruleForm.fuelConsumption" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发动机号" prop="engineNumber">
            <el-input v-model="ruleForm.engineNumber" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="载重(kg)" prop="loadCapacity">
            <el-input v-model="ruleForm.loadCapacity" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="座位数" prop="seatCount">
            <el-input v-model="ruleForm.seatCount" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <h4>年检情况</h4>
        </el-col>
        <el-col :span="6">
          <el-form-item label="年审日期" prop="annualInspectionDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.annualInspectionDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="年审项目" prop="annualInspectionItems">
            <el-input v-model="ruleForm.annualInspectionItems" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="年审情况" prop="annualInspectionStatus">
            <el-select v-model="ruleForm.annualInspectionStatus" clearable>
              <el-option v-for="item in annual_review_status" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="下次年审日期" prop="nextAnnualInspectionDate" label-width="auto">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.nextAnnualInspectionDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <h4>保险情况</h4>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入保时间" prop="insuranceStartDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.insuranceStartDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="保险公司" prop="insuranceCompany">
            <el-input v-model="ruleForm.insuranceCompany" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="投保情况" prop="insuranceStatus">
            <el-select v-model="ruleForm.insuranceStatus" clearable>
              <el-option v-for="item in Insurance_situation" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出保日期" prop="insuranceEndDate">
            <el-date-picker
              clearable
              style="width: 100%"
              v-model="ruleForm.insuranceEndDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="正面照片">
            <el-upload
              class="avatar-uploader"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess1"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.frontPhotoUrl" :src="frontPhotoUrlBlob" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="侧面照片">
            <el-upload
              class="avatar-uploader"
              :action="fileUrl"
              :data="paramsData"
              :headers="myHeader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.sidePhotoUrl" :src="sidePhotoUrlBlob" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </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 } 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 { addVehicleInfo, getVehicleDetail, updataVehicleInfo } from "@/api/transportationMng";
import { useGetters } from "@/hooks/storeHooks";
const { access_token } = useGetters(["access_token"]);
import { getQuery } from "@/hooks/detailQuery/index";
const props = getQuery("/transportationMng/vehicleMngDetail");

const { vehicle_type, vehicle_status, annual_review_status, Insurance_situation } = useDict(
  "vehicle_type",
  "vehicle_status",
  "annual_review_status",
  "Insurance_situation"
);

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

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  licensePlateNumber: "",
  vehicleType: "",
  driver: "",
  vehicleBrand: "",
  manufactureDate: "",
  purchaseDate: "",
  purchaseUnit: "",
  purchasePrice: "",
  initialKilometers: "",
  vehicleStatus: "",
  fuelConsumption: "",
  engineNumber: "",
  loadCapacity: "",
  seatCount: "",
  annualInspectionDate: "",
  annualInspectionItems: "",
  annualInspectionStatus: "",
  nextAnnualInspectionDate: "",
  insuranceStartDate: "",
  insuranceCompany: "",
  insuranceStatus: "",
  insuranceEndDate: ""
});
const frontPhotoUrlBlob = ref("");
const sidePhotoUrlBlob = ref("");
const fileName = ref("");
const rules = reactive({
  licensePlateNumber: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  vehicleType: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  driver: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  vehicleBrand: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  manufactureDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  purchaseDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  purchaseUnit: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  purchasePrice: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  initialKilometers: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  vehicleStatus: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  annualInspectionDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  annualInspectionItems: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  annualInspectionStatus: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  nextAnnualInspectionDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  insuranceStartDate: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  insuranceCompany: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  insuranceStatus: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  insuranceEndDate: [{ 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;
        updataVehicleInfo(postData).then((res: any) => {
          if (res.code === 0) {
            ElMessage({
              message: "修改成功！",
              type: "success"
            });
            returnPage();
          }
        });
      } else {
        addVehicleInfo(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 getVehicleDetail(props.id);
    ruleForm.value = deptData.data;
    handlePreview(deptData.data.frontPhotoUrl, "frontPhotoUrl");
    handlePreview(deptData.data.sidePhotoUrl, "sidePhotoUrl");
  }
};
createdMth();
const handlePreview = (filePart, viewType) => {
  sysFile(filePart).then((res: any) => {
    const blob = new Blob([res], { type: "image/png" });
    const bFile = URL.createObjectURL(blob);
    fileName.value = filePart;
    if (viewType == "frontPhotoUrl") {
      frontPhotoUrlBlob.value = bFile;
    } else {
      sidePhotoUrlBlob.value = bFile;
    }
    ruleForm.value[viewType] = 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 handleAvatarSuccess1: UploadProps["onSuccess"] = (response, uploadFile) => {
  handlePreview(response.data.fileName, "frontPhotoUrl");
};
const handleAvatarSuccess2: UploadProps["onSuccess"] = (response, uploadFile) => {
  handlePreview(response.data.fileName, "sidePhotoUrl");
};
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/vehicleMng"
  });
};
</script>

<style lang="scss" scoped>
.basic-container {
  height: auto;
}
.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>
