<template>
  <div class="maintenance-form">
    <s-header :name="$t('maintenance.title')" :noback="true" />
    <div class="content-container">
      <van-form @submit="onSubmit" class="form-container">
        <!-- 设备信息 -->
        <van-cell-group :title="$t('maintenance.form.deviceInfo')" inset>
          <van-field
            v-model="formData.clientId"
            readonly
            :label="$t('maintenance.form.deviceId')"
            :rules="[
              {
                required: true,
                message: $t('maintenance.validation.deviceIdRequired'),
              },
            ]"
          />
        </van-cell-group>

        <!-- 维护人员信息 -->
        <van-cell-group :title="$t('maintenance.form.staffInfo')" inset>
          <van-field
            v-model="formData.managerId"
            :label="$t('maintenance.form.staffId')"
            :placeholder="$t('maintenance.form.staffIdPlaceholder')"
            type="number"
            required
            :rules="[
              {
                required: true,
                message: $t('maintenance.validation.staffIdRequired'),
              },
            ]"
          />
          <van-field
            v-model="formData.name"
            :label="$t('maintenance.form.name')"
            required
            :placeholder="$t('maintenance.form.namePlaceholder')"
            :rules="[
              {
                required: true,
                message: $t('maintenance.validation.nameRequired'),
              },
            ]"
          />
        </van-cell-group>

        <!-- 维护详情 -->
        <van-cell-group :title="$t('maintenance.form.detail')" inset>
          <van-field
            readonly
            is-link
            required
            v-model="typeText"
            name="maintenanceType"
            :label="$t('maintenance.form.type')"
            :placeholder="$t('maintenance.form.typePlaceholder')"
            :rules="[
              {
                validator: validateType,
                message: $t('maintenance.validation.typeRequired'),
              },
            ]"
            @click="showType = true"
          />
          <van-popup v-model:show="showType" position="bottom" round>
            <van-checkbox-group v-model="typeValue" ref="checkboxGroup">
              <van-cell-group>
                <van-cell
                  v-for="(item, index) in maintenanceTypes"
                  :key="index"
                  clickable
                  :title="item.text"
                  @click="toggle(index)"
                >
                  <template #right-icon>
                    <van-checkbox
                      :name="item.value"
                      @click.stop
                      shape="square"
                    />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
            <div class="popup-footer">
              <van-button size="small" type="primary" @click="confirmType">{{
                $t("maintenance.form.confirm")
              }}</van-button>
            </div>
          </van-popup>

          <van-field
            v-model="dateText"
            required
            is-link
            readonly
            name="datePicker"
            :label="$t('maintenance.form.date')"
            :placeholder="$t('maintenance.form.datePlaceholder')"
            @click="showDate = true"
          />
          <van-popup v-model:show="showDate" destroy-on-close position="bottom">
            <van-date-picker
              v-model="dateValue"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onDateConfirm"
              @cancel="showDate = false"
            />
          </van-popup>

          <van-field readonly required :label="$t('maintenance.form.time')">
            <template #input>
              <van-field
                readonly
                required
                v-model="startTime"
                :placeholder="$t('maintenance.form.startTimePlaceholder')"
                :rules="[
                  {
                    required: true,
                    message: $t('maintenance.validation.startTimeRequired'),
                  },
                ]"
                @click="showStartTime = true"
              />
              <span class="separator">{{ $t("maintenance.form.to") }}</span>
              <van-field
                readonly
                required
                v-model="endTime"
                :placeholder="$t('maintenance.form.endTimePlaceholder')"
                :rules="[
                  {
                    required: true,
                    message: $t('maintenance.validation.endTimeRequired'),
                  },
                ]"
                @click="showEndTime = true"
              />
            </template>
          </van-field>
          <van-popup v-model:show="showStartTime" position="bottom">
            <van-time-picker
              :title="$t('maintenance.form.selectTime')"
              @confirm="confirmStartTime"
              @cancel="showStartTime = false"
            />
          </van-popup>
          <van-popup v-model:show="showEndTime" position="bottom">
            <van-time-picker
              :title="$t('maintenance.form.selectTime')"
              @confirm="confirmEndTime"
              @cancel="showEndTime = false"
            />
          </van-popup>

          <van-field
            v-model="formData.consumption"
            :label="$t('maintenance.form.consumables')"
            type="textarea"
            autosize
            :placeholder="$t('maintenance.form.consumablesPlaceholder')"
            clearable
          />

          <van-field
            v-model="formData.description"
            :label="$t('maintenance.form.description')"
            :placeholder="$t('maintenance.form.descriptionPlaceholder')"
            type="textarea"
            autosize
            clearable
          />
        </van-cell-group>

        <!-- 图片上传 -->
        <van-cell-group :title="$t('maintenance.form.images')" inset>
          <van-uploader
            v-model="fileList"
            multiple
            :max-count="5"
            :after-read="handleFileUpload"
            :before-delete="handleFileDelete"
          />
        </van-cell-group>

        <!-- 问题状态 -->
        <van-cell-group :title="$t('maintenance.form.status')" inset>
          <van-cell>
            <van-radio-group v-model="formData.status" direction="horizontal">
              <van-radio :name="1">{{ $t('maintenance.status.resolved') }}</van-radio>
              <van-radio :name="2">{{ $t('maintenance.status.unresolved') }}</van-radio>
            </van-radio-group>
          </van-cell>
        </van-cell-group>
        <!-- 提交按钮 -->
        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit">
            {{ $t('maintenance.form.submit') }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import sHeader from "@/components/SimpleHeader";
import { uploadPic, save } from "@/service/maintenance/index";
import { showToast, showFailToast } from "vant";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    const { t } = useI18n();
    const formData = reactive({
      clientId: "",
      managerId: "",
      name: "",
      type: "",
      startTime: "",
      endTime: "",
      consumption: "",
      description: "",
      pic: "",
      status: 1,
    });

    const maintenanceTypes = ref([
    { text: t('maintenance.type.cleaning'), value: "1", checked: false },
      { text: t('maintenance.type.refill'), value: "2", checked: false },
      { text: t('maintenance.type.repair'), value: "3", checked: false },
    ]);

    const route = useRoute();
    const router = useRouter();
    const showType = ref(false);
    const typeValue = ref([]);
    const typeText = computed(() => {
      return maintenanceTypes.value
        .filter((item) => typeValue.value.includes(item.value))
        .map((item) => item.text)
        .join("，");
    });
    const pics = ref([]);
    const fileList = ref([]);
    const showDate = ref(false);
    const maxDate = ref(new Date());
    const currentDate = ref(new Date());

    const minDate = ref(
      new Date(currentDate.value.getTime() - 36 * 1000 * 24 * 365)
    );
    const showStartTime = ref(false);
    const showEndTime = ref(false);
    const dateValue = ref([
      currentDate.value.getFullYear(),
      currentDate.value.getMonth() + 1,
      currentDate.value.getDate(),
    ]);
    const dateText = computed(() => {
      const [year, month, day] = dateValue.value;
      return `${year}-${month}-${day}`;
    });
    const startTime = ref("");
    const endTime = ref("");

    onMounted(() => {
      formData.clientId = route.query.clientId;
    });

    const onConfirmType = () => {
      showType.value = false;
    };

    // 处理时间选择
    const onDateConfirm = ({ selectedValues }) => {
      dateValue.value = selectedValues;
      showDate.value = false;
    };

    const confirmStartTime = ({ selectedValues }) => {
      startTime.value = selectedValues.join(":");
      showStartTime.value = false;
    };

    const confirmEndTime = ({ selectedValues }) => {
      endTime.value = selectedValues.join(":");
      showEndTime.value = false;
    };

    // 文件处理
    const handleFileUpload = async (file) => {
      // 此处添加文件上传逻辑
      try {
        const fileData = new FormData();   
        if (file.file.size > 1000 * 1024) {
          // 压缩文件
          const compressedFile = await createCompressedImage(file);
          fileData.append("file", compressedFile)
        } else {
          fileData.append("file", file.file);
        }
        const { data } = await uploadPic(fileData);
        if (data.code === "00000") {
          pics.value.push(data.data);
          const tempFile = data.data.split("/pic/");
          fileList.value[fileList.value.length - 1].tempName = tempFile[1];
        }
      } catch (error) {
        console.log(error);
      }
    };

    // 压缩文件
    const createCompressedImage = (file) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = file.content;
        
        img.onload = () => {
          // 计算新尺寸（保持宽高比）
          const maxSize = 1920;
          let width = img.width;
          let height = img.height;
          
          if (width > maxSize || height > maxSize) {
            const ratio = Math.min(maxSize / width, maxSize / height);
            width = Math.floor(width * ratio);
            height = Math.floor(height * ratio);
          }

          // 创建Canvas进行压缩
          const canvas = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0, width, height);

          // 调整压缩质量（大图用0.7，中等图用0.8）
          // const quality = file.file.size > 1500 * 1024 ? 0.7 : 0.8;
          const quality = 0.95;

          
          canvas.toBlob(
            blob => {
              const compressedFile = new File([blob], file.file.name, {
                type: 'image/jpeg',
                lastModified: Date.now()
              });
              resolve(compressedFile);
            },
            'image/jpeg',
            quality
          );
        };

        img.onerror = reject;
      });
    }

    const handleFileDelete = (file) => {
      pics.value = pics.value.filter(
        (item) => item.split("/pic/")[1] !== file.tempName
      );
      // 删除文件处理
      return true;
    };

    // 提交表单
    const onSubmit = async () => {
      formData.startTime = new Date(dateText.value + " " + startTime.value);
      formData.endTime = new Date(dateText.value + " " + endTime.value);
      if (formData.startTime.getTime() >= formData.endTime.getTime()) {
        showToast(t('maintenance.validation.timeRangeInvalid'));
        return;
      }
      formData.type = JSON.stringify(typeValue.value);
      formData.pic = JSON.stringify(pics.value);
      console.log(formData);
      try {
        const { data } = await save(formData);
        if (data.code === "00000") {
          router.push("/addMaintenanceSuccess");
        } else if (data.code === "A0001" || data.code === "A0002") {
          showFailToast(t('maintenance.validation.staffNotFound'));
        } else {
          showFailToast(data.message);
        }
      } catch (error) {
        console.log(error);
      }
      // 此处添加提交逻辑
    };

    // 切换选择方法
    const toggle = (index) => {
      const value = maintenanceTypes.value[index].value;
      const currentIndex = typeValue.value.indexOf(value);
      currentIndex === -1
        ? typeValue.value.push(value)
        : typeValue.value.splice(currentIndex, 1);
    };

    // 验证方法修改
    const validateType = () => typeValue.value.length > 0;

    // 确认选择
    const confirmType = () => {
      showType.value = false;
    };

    return {
      formData,
      maintenanceTypes,
      fileList,
      currentDate,
      confirmStartTime,
      confirmEndTime,
      handleFileUpload,
      handleFileDelete,
      onSubmit,
      showType,
      typeValue,
      typeText,
      onConfirmType,
      onDateConfirm,
      showDate,
      dateText,
      dateValue,
      showStartTime,
      showEndTime,
      startTime,
      endTime,
      toggle,
      validateType,
      confirmType,
      maxDate,
      minDate,
    };
  },
};
</script>
<style lang="less" scoped>
.maintenance-form {
  //   background: #f7f8fa;

  .content-container {
    background: #f5f6fa;
    height: calc(100% - 50px);
    overflow: auto;
    overflow-x: hidden;
  }

  .form-container {
    .van-cell-group__title {
      padding: 16px 0;
      font-size: 14px;
      color: #969799;
    }

    .time-range {
      display: flex;
      align-items: center;
      width: 100%;

      .van-field {
        flex: 1;
      }

      .separator {
        margin: 0 8px;
        color: #969799;
      }
    }

    .submit-btn {
      margin: 30px 16px;
    }

    .van-uploader {
      padding: 16px;
      width: 100%;
    }
  }
}

:deep(.van-field) {
  /* label文本居中对齐 */
  .van-field__label {
    display: flex;
    align-items: center;
    // justify-content: center;
    font-weight: 500;
    width: 100px;

    /* 小屏幕适配 */
    @media (max-width: 480px) {
      width: 100px;
      font-size: 13px;
    }
  }
}

.popup-footer {
  padding: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  background: #f7f8fa;
}

.van-checkbox__icon--checked .van-checkbox__icon {
  background-color: #4dc294;
  border-color: #4dc294;
}
</style>
