<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <a-modal
      style="width: 100vw; top: 0px; left: 0px; margin: 0px; padding: 0px"
      wrap-class-name="full-modal"
      v-model:open="showInfoOpen"
      title="详情"
      :footer="null"
      :maskClosable="true"
      :destroyOnClose="true"
      @cancel="showInfoOpen = false"
    >
      <div class="modal-content">
        <ShowInfoModal :showInfoData="showInfoData" />
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction, EditRecordRow } from '@/components/Table';
  import { loadCaseInfoIllegalList, dealIllegalCaseInfo } from '@/api/demo/system';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { columns, searchFormSchema } from './illegaltreatment.data';
  import { getAppEnvConfig } from '@/utils/env';
  import axios from 'axios';
  import ShowInfoModal from '@/views/demo/tiankongdi/curbspotcity/MapList/ShowInfoModal/index.vue';
  import { getCaseInfoById } from '@/api/tiankongdi/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const { createMessage } = useMessage();
  defineOptions({ name: 'RoleManagement' });

  const searchInfo = reactive<Recordable>({
    countyid: null,
  });
  const showInfoData = ref();
  const showInfoOpen = ref(false);
  const searchParams = ref();
  const [registerTable] = useTable({
    title: '违法处理',
    api: loadCaseInfoIllegalList,
    columns,
    formConfig: {
      labelWidth: 120,
      showAdvancedButton: false,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    // 搜索
    handleSearchInfoFn(info) {
      searchParams.value = info;
      return info;
    },
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    },
  });

  const currentEditKeyRef = ref('');
  function createActions(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.Id : false,
          onClick: handleEdit.bind(null, record),
        },
        {
          // icon: 'ant-design:ellipsis-outlined',
          label: '查看',
          onClick: viewAccount.bind(null, record),
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
      },
    ];
  }
  function handleEdit(record: EditRecordRow) {
    console.log(record);
    currentEditKeyRef.value = record.Id;
    record.onEdit?.(true);
  }

  function handleCancel(record: EditRecordRow) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }

  async function handleSave(record: EditRecordRow) {
    console.log(record);
    // 校验
    createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
    const valid = await record.onValid?.();
    console.log(valid);
    if (valid) {
      try {
        const data = cloneDeep(record.editValueRefs);
        console.log(data);
        let querys = { ...data };
        querys.id = record.Id;
        console.log(querys);
        //TODO 此处将数据提交给服务器保存
        const res = await dealIllegalCaseInfo(querys);
        console.log(res);
        if (res) {
          // 保存之后提交编辑状态
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef.value = '';
          }
          createMessage.success({ content: '数据已保存', key: 'saving' });
        }
      } catch (error) {
        createMessage.error({ content: '保存失败', key: 'saving' });
      }
    } else {
      // const pass = await record.onEdit?.(false, true);
      createMessage.error({ content: '请填写正确的数据', key: 'saving' });
    }
  }

  // 直接下载接口返回的二进制流
  function handleExport() {
    let params = { ...searchParams.value };
    params.countyid = searchInfo?.countyid;
    axios({
      method: 'post',
      url: VITE_GLOB_API_URL + '/api/DroneCaseInfoSingle/ExportCaseInfoIllegalList',
      params: params,
      headers: {
        'X-Token': localStorage.getItem('X-Token'),
      },
      responseType: 'blob',
    }).then((res) => {
      console.log('excel', res);
      let fileName = '违法处理统计报表' + new Date().getTime() + '.xls';
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(res.data);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.body.removeChild(elink);
    });
  }

  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnExport':
        handleExport();
        break;
      default:
        break;
    }
  }
  function viewAccount(record) {
    console.log(record);
    getCaseInfoById({ id: record.Id }).then((res) => {
      showInfoData.value = res;
      showInfoOpen.value = true;
    });
  }
</script>
<style lang="scss" scoped>
  .data-preview-container {
    width: 100%;
    height: calc(100% - 0px);
    position: absolute;
    padding: 30px 10px;
    top: 0px;
    left: 0px;
    background: #fff;
  }
  .data-preview-container-option {
    width: 120px;
    height: 40px;
    position: absolute;
    top: 30px;
    right: 0px;
  }
  .data-preview-container-option div {
    width: 40px;
    height: 40px;
    line-height: 40px;
    float: left;
    text-align: center;
    cursor: pointer;
  }
  .full-modal {
    .ant-modal {
      min-width: 100vw;
      top: 0px;
      padding: 0px;
      margin: 0px;
    }
    .ant-modal-content {
      display: flex;
      flex-direction: column;
    }
    .ant-modal-body {
      flex: 1;
    }
  }
</style>
