<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
        <a-upload
          :max-count="1"
          :show-upload-list="false"
          :customRequest="handleCustomRequest"
        >
          <a-button type="warning">导入</a-button>
        </a-upload>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '土地占用贡献',
                color: 'warning',
                onClick: () => {
                  viewLandGX(record)
                },
              },
              {
                label: '查看',
                onClick: () => {
                  viewAccount(record)
                },
              },
              {
                label: '删除',
                color: 'error',
                onClick: () => {
                  handleDelete(record)
                },
              },
              {
                label: '编辑',
                color: 'warning',
                onClick: () => {
                  editAccount(record)
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <a-modal
      v-model:open="open"
      :title="modalTitle"
      width="100%"
      wrap-class-name="full-modal"
      :destroyOnClose="true"
      @ok="submit"
    >
      <InsertModal :showInfoData="showInfoData" :isRead="isRead" />
    </a-modal>
    <a-modal
      v-model:open="landGXVisible"
      title="土地占用贡献"
      width="60%"
      :destroyOnClose="true"
    >
      <LandGongXianModal :zdbm="zdbm" />
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, watch, createVNode } from 'vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema, defaultValue } from './data';
  import { PageWrapper } from '@/components/Page';
  import { message, Modal } from 'ant-design-vue';
  import InsertModal from './InsertModal.vue';
  import LandGongXianModal from './landgongxian.vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { GetListDataInfo,GetConpanyInfoById,AddCompany,UpdateCompany,DeleteCompany,ImportCompanyInfo,ExportBuilds } from '@/api/housedata/index';

  defineOptions({ name: 'RoleManagement' });
  const showInfoData = ref();
  const isRead = ref(false)
  const modalTitle = ref('')
  const landGXVisible = ref(false)
  const zdbm = ref()
  const [registerTable, { reload, getForm,getSelectRows,clearSelectedRowKeys }] = useTable({
    title: '用房信息',
    api: GetListDataInfo,
    columns,
    rowSelection: {
      type: 'checkbox',
    },
    formConfig: {
      labelWidth: 120,
      showAdvancedButton: false,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showIndexColumn: false,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    // 搜索
    handleSearchInfoFn(info) {
      return info;
    },
    actionColumn: {
      width: 260,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    },
  });
  const open = ref<boolean>(false);
  async function onBtnClicked(domId) {
    const rows = getSelectRows();
    switch (domId) {
      case 'add':
        modalTitle.value = '新增'
        isRead.value = false
        showInfoData.value = JSON.parse(JSON.stringify(defaultValue))
        open.value = true;
        break;
      case 'delete':
        if (rows.length == 0) {
          return message.warn('请至少选择一条数据删除');
        }     
        console.log('rows',rows)
        let arr = ref([])
        rows.forEach(item =>{
          arr.value.push(item.gid)
        })
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content: '确定要删除数据吗',
          onOk() {
            return DeleteCompany(arr.value).then(res => {
              message.success('删除成功')
              reload()
              clearSelectedRowKeys()
            })
          },
          onCancel() {},
        })
        break;
      case 'upload':
           
        break;
      case 'export':
        let params = {
          page: 1,
          limit: 9999
        };

        ExportBuilds(params).then((res) => {
          const content = res;
          const blob = new Blob([content]);
          const fileName = '用房信息' + getToday() + '.xlsx';
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        });
        break;
      default:
        break;
    }
  }
  function getToday() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var dates = date.getDate();
    var time = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();

    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (dates >= 0 && dates <= 9) {
      dates = '0' + dates;
    }
    let datatime = year + '0' + month + '0' + dates + time + '0' + minutes + '0' + seconds;
    return datatime;
  }
  const viewLandGX = (record) => {
    zdbm.value = record.jzwbm
    landGXVisible.value = true
  }
  const viewAccount = (record) => {
    modalTitle.value = '查看'
    isRead.value = true
    let id = record.gid
    GetConpanyDataById(id)
  }
  const editAccount = (record) => {
    modalTitle.value = '编辑'
    isRead.value = false
    let id = record.gid
    GetConpanyDataById(id)
  }
  const handleDelete = (record) => {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除该数据吗',
      onOk() {
        return DeleteCompany([record.gid]).then(res => {
          message.success('删除成功')
          reload()
        })
      },
      onCancel() {},
    })
  }
  const GetConpanyDataById = (id) =>{
    GetConpanyInfoById({gid:id}).then(res =>{
      showInfoData.value = res
      open.value = true;
    })
  }
  const submit = () => {
    if(modalTitle.value == '新增'){
      AddCompany(showInfoData.value).then(res =>{
        message.success(`${modalTitle.value}成功`)
        open.value = false
        reload()
      })
    }
    if(modalTitle.value == '编辑'){
      UpdateCompany(showInfoData.value).then(res =>{
        message.success(`${modalTitle.value}成功`)
        open.value = false
        reload()
      })
    }
  }
  const handleCustomRequest = (file) => {
    const formData = new FormData();
    formData.append('formFiles', file.file);
    ImportCompanyInfo(formData).then(res => {
      console.log('upload',res)
      if(res){
        message.success('操作成功');
      }   
    }).catch(err => {
      message.error(err);
    })
  }
</script>
<style lang="less" scoped>

</style>
