<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" @change-data="updateData" />
  </div>
  <!-- 新增报告弹窗 -->
  <a-drawer
    :width="500"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    :footer-style="{ textAlign: 'right' }"
    destroyOnClose
    @close="onClose">
    <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" 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" placeholder="请输入适用标准" />
      </a-form-item>
      <a-form-item label="报告周期" name="reportPeriod">
        <a-select v-model:value="formState.reportPeriod" placeholder="请选择排放类型">
          <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"
          valueFormat="YYYY-MM" />
      </a-form-item>
    </a-form>
    <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 }) => {
    return http.post(api, params);
  };
  // 判断展示哪个页面
  const isMainPage = ref(true);
  const fillInPage = ref(false);
  // 新增相关数据
  const visible = ref(false);
  const formState = ref({});
  const formRef = ref();
  const labelCol = { span: 5 };
  const wrapperCol = { span: 19 };
  // 定义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 onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        console.log('values', formState, toRaw(formState));
        formState.value.enterpriseOrgId = 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();
        });
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
  // 表格相关数据
  const data = ref([]);
  const mainRef = ref();
  const reportId = ref();
  const year = ref();
  const tableConfig = ref({
    title: '数据库',
    api: carbonInventoryCheck.carbonInventoryList,
    params: {
      orgId,
    },
    headerActions: [
      {
        label: '新增',
        name: 'userAdd',
        type: 'primary',
        handle: () => {
          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) => {
            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;
          },
        },
        {
          label: '下载',
          name: 'download',
          handle: (record: any) => {},
        },
        {
          label: '删除',
          name: 'userDelete',
          dynamicParams: { id: 'id' },
          confirm: true,
          isReload: true,
          api: carbonInventoryCheck.delete,
        },
      ],
    },
    formConfig: {
      schemas: [
        {
          field: 'reportName',
          label: '报告名称',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入报告名称',
            maxLength: 30,
          },
        },
        {
          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></style>
