<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';

const base_url = '/sgsafe/TaskManifestReceipt';
const { proxy } = getCurrentInstance();

/* 返回上一级页面 */
const router = useRouter();
const route = useRoute();

const reportingForm = ref({
  taskManifestId: '',
  completionReporting: '',
  completionCount: '1',
  completionTime: ''
});

/**
 * 获取日期
 */
const timeVisible = ref(false);
const timeArr = ref([]);
const formattedTime = computed(() => {
  if (timeArr.value.length === 0) {
    return '';
  }
  const date = timeArr.value;
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
});
const onConfirmTime = () => {
  timeVisible.value = false;
  reportingForm.value.completionTime = formattedTime.value;
};


const lowerReportForm = ref({
  associateMasterId: ''
})
const dataList = ref([])
const queryLowerReporting = () => {
  const url = '/sgsafe/TaskManifestReceipt/queryByManifestId'
  const param = {
    json: JSON.stringify(lowerReportForm.value)
  }
  proxy.$axios.post(url, param).then(res => {
    if (res.data.code === 0) {
      dataList.value = res.data.data;
    } else {
      showFailToast('查询下级部门汇报失败')
    }
  })
}

const onSubmit = async (values) => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  });
  const url = base_url + '/save';
  const params = {
    json: JSON.stringify(reportingForm.value)
  };
  proxy.$axios.post(url, params).then(res => {
    if (res.data.code === 0) {
      loadingToast.close();
      showSuccessToast('保存成功');
      router.go(-1)
    } else {
      loadingToast.close();
      showFailToast('操作失败!' + res.data.msg);
    }
  });
};

const manifest = ref({});
const isQuantified = ref(false);
onMounted(() => {
  manifest.value = JSON.parse(route.query.manifest);
  console.log('manifest', manifest.value);
  if (!manifest.value.id) {
    showFailToast('数据错误，请联系管理员');
    router.go(-1)
  }
  lowerReceiptForm.value.associateMasterId = manifest.value.id
  reportingForm.value.taskManifestId = manifest.value.id;
  isQuantified.value = manifest.value.isQuantified;
  queryLowerReporting();
});

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="计划任务汇报">
      </van-nav-bar>
    </van-sticky>

    <div
      v-for="(report, index) in dataList"
      :key="index"
      class="mobile-report-card"
    >
      <div class="card-header">
        <h4>汇报部门: {{ report.reportingDeptName }}</h4>
      </div>
      <p><strong>汇报内容:</strong> {{ report.completionReporting }}</p>
      <p><strong>完成次数:</strong> {{ report.completionCount }}</p>
      <p><strong>完成时间:</strong> {{ report.completionTime }}</p>
    </div>

    <van-form @submit="onSubmit">
      <van-field
        v-model="reportingForm.completionReporting"
        label="汇报内容"
        type="textarea"
        name="completionReporting"
        required
        placeholder="请输入汇报内容"
        :rules="[{required: true, message: '请输入汇报内容'}]"
      />

      <van-field
        v-if="isQuantified"
        v-model="reportingForm.completionCount"
        type="number"
        label="完成次数"
        name="completionCount"
        required
        :rules="[{required: true, message: '请输入完成次数'},
           { pattern: /^[1-9]\d*$/, message: '必须为正整数' }]"
      />

      <van-field
        readonly
        v-model="formattedTime"
        label="完成时间"
        name="formattedTime"
        placeholder="请选择完成时间"
        required
        :rules="[{required: true, message: '请选择完成时间'}]"
        @click="timeVisible = true"
      />

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">提交</van-button>
      </div>
    </van-form>

    <van-popup
      :close-on-click-overlay="false"
      v-model:show="timeVisible"
      position="bottom"
      :teleport="false"
    >
      <van-date-picker
        v-model="timeArr"
        type="date"
        @confirm="onConfirmTime"
        @cancel="timeVisible = false"
      />
    </van-popup>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;
}

/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.reports-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
}

.report-card .report-header h4 {
  margin-top: 0;
  font-size: 16px;
  color: #333;
}

.report-card p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

</style>
