<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #violateType>
        <el-select v-model="ruleFormData.violateType" placeholder="请选择违规类型">
          <el-option
            v-for="item in ACT_VIOLATION_TYPE_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <div v-if="ruleFormData.violateType === ACT_VIOLATION_TYPE.SPEEDING" style="margin-top: 10px; width: 100%">
          <el-form-item
            label-width="auto"
            label="车速："
            prop="speed"
            :rules="[
              {
                required: true,
                validator: (_rule, value, callback) => {
                  if (value == null) return callback(new Error('请输入车速'));
                  if (!(Number.isInteger(value) && value > 0)) return callback(new Error('车速格式错误'));
                  if (value > 999) {
                    callback(new Error('超过车速时速上限'));
                  } else {
                    callback();
                  }
                },
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model.number="ruleFormData.speed"
              placeholder="请输入车速"
              type="number"
              min="0"
              max="999"
              step="1"
            >
              <template #suffix>km/h</template>
            </el-input>
          </el-form-item>
        </div>
      </template>
      <template #captureTime>
        <el-date-picker
          v-model="ruleFormData.captureTime"
          placeholder="请选择抓拍时间"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          dateFormat="MMM DD YYYY"
          timeFormat="HH:mm:ss"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :editable="false"
          :disabledDate="(time) => time.getTime() > Date.now()"
          :disabledHours="
            (role, comparingDate) => {
              if (!role) return [];
              const now = new Date();
              now.setHours(0, 0, 0, 0);
              if (comparingDate.valueOf() < now.getTime()) return [];
              const huors = 23 - new Date().getHours();
              return Array.from({ length: huors }, (_, i) => 23 - i);
            }
          "
          :disabledMinutes="
            (hour, role, comparingDate) => {
              if (!role) return [];
              const now = new Date();
              const nowHour = now.getHours();
              if (hour < nowHour) return [];
              now.setHours(0, 0, 0, 0);
              if (comparingDate.valueOf() < now.getTime()) return [];
              const minutes = 59 - new Date().getMinutes();
              return Array.from({ length: minutes }, (_, i) => 59 - i);
            }
          "
          :disabledSeconds="
            (hour, minute, role, comparingDate) => {
              if (!role) return [];
              const now = new Date();
              const nowHour = now.getHours();
              const nowMinutes = now.getMinutes();
              if (hour < nowHour) return [];
              if (hour === nowHour && minute < nowMinutes) return [];
              now.setHours(0, 0, 0, 0);
              if (comparingDate.valueOf() < now.getTime()) return [];
              const seconds = 59 - new Date().getSeconds();
              return Array.from({ length: seconds }, (_, i) => 59 - i);
            }
          "
          @change="
            (val) => {
              if (new Date(val).getTime() > Date.now()) {
                ElMessage.error('抓拍时间不晚于当前时间，请重新选择');
                ruleFormData.captureTime = '';
              }
            }
          "
        ></el-date-picker>
      </template>
      <template #capturePhotos>
        <UploadImages
          :maxCount="5"
          ref="uploadImagesRef"
          :image-list="imageList"
          @upload-success="handleUploadChange"
        />
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">取消</el-button>
    <el-button type="primary" @click="handleSubmit">提交</el-button>
  </footer>
  <UploadLoading :form-loading="formLoading" v-if="formLoading" />
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import UploadImages from '@/components/UploadImages/UploadImages.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { getActDataDetail, updateActData } from '@/api/traffic-violation/traffic-act';
  import { CreateActRuleForm, UpdateActQuery, ActTableData } from '../types';
  import { ACT_FORM_CONFIG, ACT_FORM_DATA, ACT_FORM_RULES } from '../configs/form';
  import { ACT_VIOLATION_TYPE, ACT_VIOLATION_TYPE_OPTIONS } from '../constants';
  import { unformatImage, formatImageList } from '@/components/UploadImages/utils';

  const props = defineProps<{
    id: number;
  }>();

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<CreateActRuleForm>(ACT_FORM_CONFIG, ACT_FORM_DATA, ACT_FORM_RULES);

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const uploadImagesRef = ref<InstanceType<typeof UploadImages>>();

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const actDetail = ref<ActTableData>();
  const getDetail = async () => {
    actDetail.value = await getActDataDetail(props.id);
    if (!actDetail.value) return;
    ruleFormData.carNumber = actDetail.value.carNumber;
    ruleFormData.violateType = actDetail.value.violateType;
    ruleFormData.speed = actDetail.value.speed;
    ruleFormData.violateLocation = actDetail.value.violateLocation;
    ruleFormData.captureTime = actDetail.value.captureTime;
    ruleFormData.capturePhotos = unformatImage(actDetail.value.capturePhotos)?.map((x) => {
      return { url: x };
    });
    ruleFormData.remark = actDetail.value.remark;
    ruleFormData.creatName = actDetail.value.creatName;

    imageList.value = unformatImage(actDetail.value.capturePhotos)!;
    cloneRuleFormData();
  };

  const imageList = ref<string[]>([]);

  const getFormData = async () => {
    if (ruleFormData.violateType !== ACT_VIOLATION_TYPE.SPEEDING) {
      ruleFormData.speed = null;
    }
    cloneRuleFormData();
    const res: UpdateActQuery = {
      id: props.id,
      createSource: 1,
      ...ruleFormData,
      violateType: ruleFormData.violateType!,
      capturePhotos: JSON.stringify(await formatImageList(ruleFormData.capturePhotos)),
    };

    return res;
  };

  const formLoading = ref(false);
  const router = useRouter();
  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      formLoading.value = true;
      const params = await getFormData();
      await updateActData(params);
      ElMessage.success('编辑成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };

  const handleUploadChange = () => {
    ruleFormData.capturePhotos = uploadImagesRef.value!.getUploadedImages();
  };

  onMounted(() => {
    beforeRouteLeave();
    getDetail();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
</style>
