<template>
  <!-- 首页 -->
  <div v-if="isMainPage">
    <ns-view-list-table v-bind="tableConfig" :model="data" ref="mainRef" />
  </div>
  <!-- 填报页 -->
  <div v-if="fillInPage" style="height: 100%">
    <fillIn
      :reportId="reportId"
      :year="year"
      :startTime="startTime"
      :endTime="endTime"
      :standard="standard"
      @change-data="updateData" />
  </div>
  <!-- 新增报告弹窗 -->
  <a-drawer
    :width="500"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    :footer-style="{ textAlign: 'right' }"
    destroyOnClose
    @close="onClose">
    <div class="ns-form-title"
      ><div class="title">{{ text }}</div></div
    >
    <a-spin :spinning="spinning">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-item ref="name" label="报告名称" name="reportName">
          <a-input
            v-model:value="formState.reportName"
            :maxlength="15"
            @keydown="handleKeyDown"
            placeholder="请输入报告名称" />
        </a-form-item>
        <a-form-item ref="name" label="报告年度" name="reportYear">
          <a-date-picker v-model:value="formState.reportYear" picker="year" valueFormat="YYYY" />
        </a-form-item>
        <a-form-item ref="name" label="适用标准" name="genericStandard">
          <a-input
            v-model:value="formState.genericStandard"
            :maxlength="20"
            @keydown="handleKeyDown"
            placeholder="请输入适用标准" />
        </a-form-item>
        <a-form-item label="报告周期" name="reportPeriod">
          <a-select
            v-model:value="formState.reportPeriod"
            placeholder="请选择报告周期"
            @change="selectChange">
            <a-select-option value="1">年度</a-select-option>
            <a-select-option value="2">月度</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item ref="name" label="报告范围" name="reportScope">
          <a-range-picker
            v-model:value="formState.reportScope"
            picker="month"
            :disabledDate="disabledDate"
            valueFormat="YYYY-MM" />
        </a-form-item>
      </a-form>
    </a-spin>
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="onSubmit">确定</a-button>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, toRaw } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { carbonInventoryCheck } from '/@/api/carbonEmissionFactorLibrary';
  import fillIn from './fillInPage/index.vue';
  defineOptions({ name: 'CarbonInventoryCheck' });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  const fetch = (api, params = { orgId }, config) => {
    return http.post(api, params, config);
  };
  // 判断展示哪个页面
  const isMainPage = ref(true);
  const fillInPage = ref(false);
  // 新增相关数据
  const visible = ref(false);
  const formState = ref({});
  const formRef = ref();
  const labelCol = { span: 4 };
  const wrapperCol = { span: 20 };
  const text = ref('新增报告');
  const disabledDate = (current: moment.Moment | null) => {
    if (formState.value.reportPeriod === '2') {
      const year = current.year();
      return year === Number(formState.value.reportYear) ? false : true;
    }
  };
  const selectChange = (value) => {
    formState.value.reportScope = '';
  };
  // 定义form表单的必填
  const rules: Record<string, Rule[]> = {
    reportName: [{ required: true, message: '请输入报告名称', trigger: 'change' }],
    reportYear: [{ required: true, message: '请选择报告年度', trigger: 'change' }],
    genericStandard: [{ required: true, message: '请输入适用标准', trigger: 'change' }],
    reportPeriod: [{ required: true, message: '请选择排放类型', trigger: 'change' }],
    reportScope: [{ required: true, message: '请选择报告范围', trigger: 'change' }],
  };
  // 关闭新增抽屉
  const onClose = () => {
    visible.value = false;
    formState.value = {};
    formRef.value.resetFields();
  };
  const handleKeyDown = (event: KeyboardEvent) => {
    // Check if the pressed key is a space
    if (event.code === 'Space') {
      event.preventDefault();
    }
  };
  const spinning = ref(false);
  // 点击确定提交
  const onSubmit = () => {
    spinning.value = true;
    formRef.value
      .validate()
      .then(() => {
        console.log('values', formState, toRaw(formState));
        formState.value.orgId = orgId.value;
        formState.value.startTime = formState.value.reportScope[0];
        formState.value.endTime = formState.value.reportScope[1];
        fetch(carbonInventoryCheck.createOrUpdate, formState.value).then((res) => {
          visible.value = false;
          mainRef.value?.nsTableRef.reload();
          spinning.value = false;
        });
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
  // 表格相关数据
  const data = ref([]);
  const mainRef = ref();
  const reportId = ref();
  const startTime = ref();
  const endTime = ref();
  const standard = ref();
  const year = ref();
  const tableConfig = ref({
    title: '数据库',
    api: carbonInventoryCheck.carbonInventoryList,
    params: {
      orgId,
    },
    headerActions: [
      {
        label: '新增',
        name: 'userAdd',
        type: 'primary',
        handle: () => {
          text.value = '新增报告';
          visible.value = true;
        },
      },
    ],
    columns: [
      {
        title: '序号',
        customRender: (text: any) => {
          return text.index + 1;
        },
      },
      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
      },
      {
        title: '报告名称',
        dataIndex: 'reportName',
      },
      {
        title: '报告年度',
        dataIndex: 'reportYear',
      },
      {
        title: '适用标准',
        dataIndex: 'genericStandard',
      },
      {
        title: '更新人',
        dataIndex: 'updateUser',
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
      },
    ],
    columnActions: {
      title: '操作',
      actions: [
        {
          label: '编辑',
          name: 'userEdit',
          handle: (record: any) => {
            text.value = '编辑报告';
            visible.value = true;
            fetch(carbonInventoryCheck.findById, { id: record.id }).then((res) => {
              formState.value = res.data;
              formState.value.reportScope = [res.data.startTime, res.data.endTime];
            });
          },
        },
        {
          label: '填报',
          name: 'fillIn',
          handle: (record: any) => {
            isMainPage.value = false;
            fillInPage.value = true;
            reportId.value = record.id;
            year.value = record.reportYear;
            startTime.value = record.startTime;
            endTime.value = record.endTime;
            standard.value = record.genericStandard;
          },
        },
        {
          label: '下载',
          name: 'download',
          handle: (record: any) => {
            const deleteId = ref(new FormData());
            deleteId.value.append('id', record.id);
            const config = {
              responseType: 'blob',
            };
            fetch(carbonInventoryCheck.downloadZip, deleteId.value, config)
              .then((res) => {
                // 创建一个 URL 对象，指向图片数据的 blob
                const url = window.URL.createObjectURL(new Blob([res]));
                // 创建一个 <a> 标签，用于触发下载
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', '碳盘查凭证.zip'); // 设置下载的文件名
                document.body.appendChild(link);
                link.click();

                // 清理 URL 对象
                window.URL.revokeObjectURL(url);
              })
              .catch((error) => {
                console.error('下载图片失败：', error);
              });
          },
        },
        {
          label: '删除',
          name: 'userDelete',
          dynamicParams: { id: 'id' },
          confirm: true,
          isReload: true,
          api: carbonInventoryCheck.delete,
        },
      ],
    },
    formConfig: {
      schemas: [
        {
          field: 'reportName',
          label: '报告名称',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入报告名称',
            maxLength: 20,
          },
        },
        {
          field: 'reportYear',
          label: '报告年度',
          component: 'NsRangePicker',
          fieldMap: ['startYear', 'endYear'],
          componentProps: {
            valueFormat: 'YYYY',
            placeholder: ['报告年度', '报告年度'],
            picker: 'year',
          },
        },
      ],
      params: {},
    },
    rowKey: 'id',
  });
  // 填报页点击返回
  const updateData = (newDataOne, newDataTwo) => {
    isMainPage.value = newDataOne;
    fillInPage.value = newDataTwo;
  };
</script>

<style lang="less" scoped>
  .ns-form-title {
    font-weight: bold;
    user-select: text;
    margin-bottom: 16px;
  }
  .title {
    text-align: left;
    height: 32px;
    line-height: 32px;
    font-weight: bold;
    user-select: text;
    position: relative;
    padding-left: 9px;
  }
  .title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 13px;
    width: 3px;
    border-radius: 1px;
    background-color: #2778ff;
  }
</style>
