<script setup>
  import { ref } from 'vue';
  import { createIotRyDailyReport } from '@/api/ruiying';
  import Form from './components/form.vue';

  const formRef = ref(null);

  const formLoading = ref(false);

  const submitForm = async () => {
    if (!formRef.value) return;

    try {
      await formRef.value.formRef.validate();
      const form = formRef.value.form;

      if (form.nonProductionTime && !form.ryNptReason) {
        uni.showToast({
          title: '非生产时间大于 0 时，必须选择非生产时间原因',
          icon: 'none',
        });
        return;
      }

      if (Number(form.productionTime) + Number(form.nonProductionTime) !== Number(form.ratedProductionTime)) {
        uni.showToast({
          title: '生产时间和非生产时间之和必须等于额定生产时间',
          icon: 'none',
        });
      }

      formLoading.value = true;

      const { createTime, ...other } = form;
      const data = { ...other, fillOrderCreateTime: createTime, projectClassification: '2' };

      await createIotRyDailyReport(data);

      formRef.value.loadDetail(form.id);

      uni.showToast({
        title: '修改成功',
        icon: 'success',
      });
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      formLoading.value = false;
    }
  };
</script>

<template>
  <view class="page">
    <scroll-view scroll-y="true" class="segmented-content">
      <Form ref="formRef" type="edit"></Form>
    </scroll-view>
    <view class="segmented-footer">
      <view class="footer-btn">
        <button
          :disabled="formLoading || formRef?.form.status !== 0"
          :loading="formLoading"
          class="mini-btn"
          type="primary"
          @click="submitForm">
          确定
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  @import '@/style/work-order-segmented.scss';
  .page {
    padding-bottom: 0;
  }

  .footer-btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 32px;
    height: 100%;

    gap: 0 32px;

    & > uni-button {
      margin: 0;
    }
  }

  :deep(.mini-btn) {
    height: 38px !important;
    font-size: 16px !important;
  }
</style>
