<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="CYCLE">
            <el-select v-model="form.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="REMINDER_DAYS">
            <el-select v-model="form.REMINDER_DAYS" @change="getRemiderDate">
              <el-option
                v-for="item in REMIND_DAYS"
                :key="item.NAME"
                :label="item.NAME"
                :value="item.NUM"
              />
            </el-select>
            <!--            <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="OPERATIONSINFO">
            <layout-upload
              v-model:file-list="form.OPERATIONSINFO"
              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 {
  getOperationsView,
  setOperationsAdd,
  setOperationsEdit,
  getTrailerList,
  getOperationTrailerList,
} from "@/request/mechanical_files.js";
import {
  OPERATING_VEHICLE_TYPE_LIST,
  REMIND_DAYS,
} 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 OPERATIONS_ID = route.query.OPERATIONS_ID;
const annualInspectionCycleList = await layoutFnGetAnnualInspectionCycle();
const formRef = ref(null);
const form = ref({
  VEHICLE_MODEL: "",
  VEHICLE: "",
  NUM: "",
  CAR_OWNERS: "",
  TELEPHONE: "",
  REGISTRANT: "",
  PROCESSING_DATE: "",
  CYCLE: "",
  DUE_DATE: "",
  REMINDER_DAYS: "",
  REMINDER_DATE: "",
  REMINDER_STATUS: "",
  OPERATIONSINFO: [],
});
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" }],
  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.CYCLE) {
    const list = annualInspectionCycleList._rawValue;
    let num = 0;
    for (let i = 0; i < list.length; i++) {
      const _item = list[i];
      if (form.value.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) {
      const reminderDateStr = subtractDaysFromDate(form.value.DUE_DATE, val);
      const reminderDate = new Date(reminderDateStr);
      const today = new Date();
      if (reminderDate < today) {
        ElMessage.error("输入的提醒天数错误，提醒日期不能早于当前日期。");
        form.value.REMINDER_DAYS = "";
      } else {
        form.value.REMINDER_DATE = reminderDateStr;
      }
    }
  } else {
    form.value.REMINDER_DATE = "";
  }
};
const getVehicle = async (event) => {
  const resData = await getOperationTrailerList({ 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 getOperationTrailerList({ 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 (!OPERATIONS_ID) return;
  const resData = await getOperationsView({ OPERATIONS_ID });
  form.value = resData.pd;
  form.value.OPERATIONSINFO = [];
  const listData = await getTrailerList({
    TRAFFIC_TYPE: form.value.VEHICLE_MODEL,
  });
  data.vehicleList = listData.list;
  fnBusChange(form.value.VEHICLE);
  form.value.OPERATIONSINFO = addingPrefixToFile(resData.operationsinfoImgs);
};
fnGetData();

const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const resData = !OPERATIONS_ID
      ? await setOperationsAdd({ ...form.value })
      : await setOperationsEdit({
          ...form.value,
          OPERATIONS_ID,
        });
    const currentId = resData.pd.OPERATIONS_ID;
    for (let i = 0; i < form.value.OPERATIONSINFO.length; i++) {
      if (form.value.OPERATIONSINFO[i].raw)
        await fnUploadImage(currentId, form.value.OPERATIONSINFO[i].raw, 126);
    }
    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>
