<template>
  <layout-card>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-divider content-position="left">车辆选择</el-divider>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年检车型" prop="VEHICLE_MODEL">
            <el-select v-model="form.VEHICLE_MODEL" @change="getVehicle">
              <el-option
                v-for="item in OPERATING_VEHICLE_TYPE_LIST"
                :key="item.ID"
                :label="item.NAME"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年检车辆" prop="VEHICLE">
            <el-select v-model="form.VEHICLE" @change="getBusInfo">
              <el-option
                v-for="item in data.vehicleList"
                :key="item.ID"
                :label="item.PLATE_NUMBER"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">基本信息</el-divider>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行驶证照片" prop="DRIVING_LICENSE_IMG">
            <layout-upload
              v-model:file-list="data.busInfo.DRIVING_LICENSE_IMG"
              list-type="picture-card"
              accept=".jpg,.jpeg,.png"
              delete-to-server
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车牌号" prop="PLATE_NUMBER">
            <el-input v-model="data.busInfo.PLATE_NUMBER" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车架号" prop="VIN">
            <el-input v-model="data.busInfo.VIN" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆类型" prop="TRAILER_TYPE">
            <el-input v-model="data.busInfo.TRAILER_TYPE" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车主/业户" prop="CAR_OWNERS ">
            <el-input v-model="data.busInfo.CAR_OWNERS" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车主电话" prop="CAR_OWNERS_TEL">
            <el-input v-model="data.busInfo.CAR_OWNERS_TEL" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="初登日期" prop="INITIAL_REGISTRATION_DATE">
            <el-date-picker
              v-model="data.busInfo.INITIAL_REGISTRATION_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="COMPANY_AREA">
            <el-input v-model="data.busInfo.COMPANY_AREA" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">年检信息</el-divider>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编号" prop="NUM">
            <el-input v-model="form.NUM" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车主业户" prop="CAR_OWNERS">
            <el-input
              v-model="form.CAR_OWNERS"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="TELEPHONE">
            <el-input v-model="form.TELEPHONE" maxlength="11" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="登记人" prop="REGISTRANT">
            <el-input
              v-model="form.REGISTRANT"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办理日期" prop="PROCESSING_DATE">
            <el-date-picker
              v-model="form.PROCESSING_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              @change="getDueDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年检周期" prop="ANNUAL_INSPECTION_CYCLE">
            <el-select
              v-model="form.ANNUAL_INSPECTION_CYCLE"
              @change="getDueDate"
            >
              <el-option
                v-for="item in annualInspectionCycleList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到期日期" prop="DUE_DATE">
            <el-date-picker
              v-model="form.DUE_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年检费用" prop="INSPECTFEES">
            <el-input
              v-model="form.INSPECTFEES"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收费用" prop="ACTUAL_COLLECTION">
            <el-input
              v-model="form.ACTUAL_COLLECTION"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年检地址" prop="ADDRESS">
            <el-input v-model="form.ADDRESS" maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提醒天数" prop="REMINDER_DAYS">
            <el-input
              v-model.number="form.REMINDER_DAYS"
              maxlength="50"
              show-word-limit
              @change="getRemiderDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提醒日期" prop="REMINDER_DATE">
            <el-date-picker
              v-model="form.REMINDER_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提醒状态" prop="REMINDER_STATUS">
            <el-switch
              v-model="form.REMINDER_STATUS"
              inline-prompt
              active-text="开"
              inactive-text="关"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车检资料" prop="INSPECTINFO">
            <layout-upload
              v-model:file-list="form.INSPECTINFO"
              list-type="picture-card"
              accept=".jpg,.jpeg,.png"
              :limit="99"
              delete-to-server
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="NOTES">
            <el-input
              v-model="form.NOTES"
              type="textarea"
              :autosize="{ minRows: 3 }"
              maxlength="250"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="mt-10 tc">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
  </layout-card>
</template>

<script setup>
import LayoutUpload from "@/components/upload/index.vue";
import { ref, reactive } from "vue";
import { debounce } from "throttle-debounce";
import {
  getInspectAnnuallyView,
  setInspectAnnuallyAdd,
  setInspectAnnuallyEdit,
  getTrailerList,
} from "@/request/mechanical_files.js";
import { OPERATING_VEHICLE_TYPE_LIST } from "@/assets/js/constant.js";
import { layoutFnGetAnnualInspectionCycle } from "@/assets/js/data_dictionary.js";
import { setUploadImg } from "@/request/api.js";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import useFormValidate from "@/assets/js/useFormValidate.js";
import {
  addingPrefixToFile,
  timeTransformation,
  subtractDaysFromDate,
} from "@/assets/js/utils.js";
const route = useRoute();
const router = useRouter();
const INSPECTANNUALLY_ID = route.query.INSPECTANNUALLY_ID;
const annualInspectionCycleList = await layoutFnGetAnnualInspectionCycle();
const formRef = ref(null);
const form = ref({
  VEHICLE_MODEL: "",
  VEHICLE: "",
  NUM: "",
  CAR_OWNERS: "",
  TELEPHONE: "",
  REGISTRANT: "",
  PROCESSING_DATE: "",
  ANNUAL_INSPECTION_CYCLE: "",
  DUE_DATE: "",
  INSPECTFEES: "",
  ACTUAL_COLLECTION: "",
  ADDRESS: "",
  REMINDER_DAYS: "",
  REMINDER_DATE: "",
  REMINDER_STATUS: "",
  INSPECTINFO: [],
});
const data = reactive({
  vehicleList: [],
  busInfo: {
    DRIVING_LICENSE_IMG: [],
    PLATE_NUMBER: "",
    VIN: "",
    TRAILER_TYPE: "",
    CAR_OWNERS: "",
    CAR_OWNERS_TEL: "",
    INITIAL_REGISTRATION_DATE: "",
    COMPANY_AREA: "",
  },
});
const rules = {
  VEHICLE_MODEL: [{ required: true, message: "请输入", trigger: "blur" }],
  VEHICLE: [{ required: true, message: "请输入", trigger: "blur" }],
  CAR_OWNERS: [{ required: true, message: "请输入", trigger: "blur" }],
  TELEPHONE: [
    { required: true, message: "请输入", trigger: "blur" },
    { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/,
      message: "请输入正确的手机号码",
    },
  ],
  REGISTRANT: [{ required: true, message: "请输入", trigger: "blur" }],
  PROCESSING_DATE: [{ required: true, message: "请输入", trigger: "blur" }],
  ANNUAL_INSPECTION_CYCLE: [
    { required: true, message: "请输入", trigger: "blur" },
  ],
  DUE_DATE: [{ required: true, message: "请输入", trigger: "blur" }],
  REMINDER_DAYS: [{ required: true, message: "请输入", trigger: "blur" }],
  REMINDER_DATE: [{ required: true, message: "请输入", trigger: "blur" }],
};
const getDueDate = () => {
  if (form.value.PROCESSING_DATE && form.value.ANNUAL_INSPECTION_CYCLE) {
    const list = annualInspectionCycleList._rawValue;
    let num = 0;
    for (let i = 0; i < list.length; i++) {
      const _item = list[i];
      if (form.value.ANNUAL_INSPECTION_CYCLE === _item.DICTIONARIES_ID) {
        num = Number(_item.BIANMA);
      }
    }
    form.value.DUE_DATE = timeTransformation(form.value.PROCESSING_DATE, num);
    if (form.value.REMINDER_DAYS) {
      form.value.REMINDER_DATE = subtractDaysFromDate(
        form.value.DUE_DATE,
        form.value.REMINDER_DAYS
      );
    }
  } else {
    form.value.DUE_DATE = "";
    form.value.REMINDER_DATE = "";
  }
};
const getRemiderDate = (val) => {
  if (val) {
    if (form.value.DUE_DATE) {
      form.value.REMINDER_DATE = subtractDaysFromDate(form.value.DUE_DATE, val);
    }
  } else {
    form.value.REMINDER_DATE = "";
  }
};
const getVehicle = async (event) => {
  const resData = await getTrailerList({ TRAFFIC_TYPE: event });
  data.vehicleList = resData.list;
  form.value.VEHICLE = "";
  data.busInfo.DRIVING_LICENSE_IMG = [];
  data.busInfo.PLATE_NUMBER = "";
  data.busInfo.VIN = "";
  data.busInfo.TRAILER_TYPE = "";
  data.busInfo.CAR_OWNERS = "";
  data.busInfo.CAR_OWNERS_TEL = "";
  data.busInfo.INITIAL_REGISTRATION_DATE = "";
  data.busInfo.DRIVING_LICENSE_IMG = addingPrefixToFile([]);
};
const fnBusChange = async (event) => {
  const resData = await getTrailerList({ ID: event });
  data.busInfo = resData.list[0];
  data.busInfo.DRIVING_LICENSE_IMG = addingPrefixToFile(
    resData.drivingLicenseImgs
  );
};
const getBusInfo = (val) => {
  if (val) {
    fnBusChange(val);
  } else {
    data.busInfo.DRIVING_LICENSE_IMG = [];
    data.busInfo.PLATE_NUMBER = "";
    data.busInfo.VIN = "";
    data.busInfo.TRAILER_TYPE = "";
    data.busInfo.CAR_OWNERS = "";
    data.busInfo.CAR_OWNERS_TEL = "";
    data.busInfo.INITIAL_REGISTRATION_DATE = "";
    data.busInfo.COMPANY_AREA = "";
    data.busInfo.DRIVING_LICENSE_IMG = addingPrefixToFile([]);
  }
};
const fnGetData = async () => {
  if (!INSPECTANNUALLY_ID) return;
  const resData = await getInspectAnnuallyView({ INSPECTANNUALLY_ID });
  form.value = resData.pd;
  const listData = await getTrailerList({
    TRAFFIC_TYPE: form.value.VEHICLE_MODEL,
  });
  data.vehicleList = listData.list;
  fnBusChange(form.value.VEHICLE);
  form.value.INSPECTINFO = addingPrefixToFile(resData.inspectinfoImgs);
};
fnGetData();

const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const resData = !INSPECTANNUALLY_ID
      ? await setInspectAnnuallyAdd({ ...form.value })
      : await setInspectAnnuallyEdit({
          ...form.value,
          INSPECTANNUALLY_ID,
        });
    const currentId = resData.pd.INSPECTANNUALLY_ID;
    for (let i = 0; i < form.value.INSPECTINFO.length; i++) {
      if (form.value.INSPECTINFO[i].raw)
        await fnUploadImage(currentId, form.value.INSPECTINFO[i].raw, 124);
    }
    ElMessage.success("保存成功");
    router.back();
  },
  { atBegin: true }
);
const fnUploadImage = async (HIDDEN_ID, FFILE, TYPE) => {
  const formData = new FormData();
  formData.append("FOREIGN_KEY", HIDDEN_ID);
  formData.append("TYPE", TYPE);
  formData.append("FFILE", FFILE);
  await setUploadImg(formData);
};
</script>

<style scoped lang="scss"></style>
