<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
        <a-button preIcon="ant-design:cloud-upload-outlined" type="primary" @click="handleExtract">提取</a-button>
        <a-button preIcon="ant-design:vertical-align-top-outlined" type="primary" @click="handleUpload">导入</a-button>
        <a-button preIcon="ant-design:vertical-align-bottom-outlined" type="primary" @click="handleDownload">导出</a-button>
      </template>
      <template #action="{ record }">
        <a class="table-action-link" @click="handleEdit(record)">编辑</a>
        <a-popconfirm title="确定删除?" @confirm="handleDelete(record)">
          <a class="table-action-link">删除</a>
        </a-popconfirm>
        <slot name="action" v-bind="{ record }"></slot>
      </template>
      <template #bodyCell="{ column, record }">
        <slot name="filterCell" v-bind="{ column, record }"></slot>
      </template>
    </BasicTable>
    <DeviceModal @register="registerModal" @saveOrUpdate="saveOrUpdateHandler" :showTab="showTab"
      :deviceType="deviceType" />
    <!-- 手动提取弹窗 -->
    <a-modal v-model:visible="visibleTq" width="450px" :footer="null" :title="titleTq" centered destroyOnClose>
      <a-form :model="formStateTq" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" autocomplete="off">
        <a-form-item label="报表类型：">
          <JDictSelectTag v-model:value="formStateTq.reportType" placeholder="请选择报表类型" dictCode="reportType"
            style="width: 240px" />
        </a-form-item>
        <div class="opertion-btn">
          <a-button type="primary" @click="confirmTq">确定</a-button>
          <a-button type="success" style="margin-left:10px" @click="cancelTq">取消</a-button>
        </div>
      </a-form>
    </a-modal>
<!-- 导入弹窗 -->
<a-modal v-model:visible="visibleUpload" width="450px" :footer="null" :title="titleUpload" centered destroyOnClose>
      <a-form :model="formStateUpload" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" autocomplete="off">
        <a-form-item label="报表类型：">
          <JDictSelectTag v-model:value="formStateUpload.reportType" placeholder="请选择报表类型" dictCode="reportType"
            style="width: 240px" />
        </a-form-item>
        <a-form-item label="文件上传">
          <a-upload :before-upload="beforeUpload" @remove="handleRemove" :multiple="false" :file-list="fileList">
            <a-button type="primary" preIcon="ant-design:cloud-upload-outlined">选择文件</a-button>
          </a-upload>
        </a-form-item>
        <div class="opertion-btn">
          <a-button type="primary" @click="confirmUpload">确定</a-button>
          <a-button type="success" style="margin-left:10px" @click="cancelUpload">取消</a-button>
        </div>
      </a-form>
    </a-modal>
    <!-- 导出弹窗 -->
    <a-modal v-model:visible="visibleDown" width="450px" :footer="null" :title="titleDown" centered destroyOnClose>
      <a-form :model="formStateDown" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" autocomplete="off">
        <a-form-item label="报表类型：">
          <JDictSelectTag v-model:value="formStateDown.reportType" placeholder="请选择报表类型" dictCode="reportType"
            style="width: 240px" />
        </a-form-item>
        <div class="opertion-btn">
          <a-button type="primary" @click="confirmDownload">确定</a-button>
          <a-button type="success" style="margin-left:10px" @click="cancelDownload">取消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
//ts语法
import { ref, provide, reactive, toRaw, defineExpose, watch } from 'vue';
import { BasicTable, ActionItem, EditRecordRow, BasicColumn } from '/@/components/Table';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { useModal } from '/@/components/Modal';
import DeviceModal from './DeviceModal.vue';
import { getTableHeaderColumns } from '/@/hooks/web/useWebColumns';
import { useListPage } from '/@/hooks/system/useListPage';
import { useMessage } from '/@/hooks/web/useMessage';

const props = defineProps({
  columnsType: {
    type: String,
    // required: true,
  },
  columns: {
    type: Array,
    // required: true,
    default: () => [],
  },
  searchFormSchema: {
    type: Array,
    default: () => [],
  },
  formSchema: {
    type: Array,
    required: true,
  },
  list: {
    type: Function,
    required: true,
  },
  readReportData: {
    type: Function,
    required: true,
  },
  getImportUrl: {
    type: Function,
    required: true,
  },
  getExportUrl: {
    type: Function,
    required: true,
  },
  deleteById: {
    type: Function,
    required: true,
  },
  saveOrUpdate: {
    type: Function,
    required: true,
  },
  pointList: {
    type: Function,
  },
  showTab: {
    type: Boolean,
    default: false,
  },
  designScope: {
    type: String,
  },
  title: {
    type: String,
  },
  deviceType: {
    type: String,
  },
});

const emit = defineEmits(['submitSuccess', 'editHandler']);
const { createMessage } = useMessage();
let visibleTq = ref(false)//控制手动提取弹窗的显示与隐藏
let titleTq = ref('提取信息')
let formStateTq = reactive({
  reportType: ''
})
const isUpdate = ref(false);
const record = reactive({});
const formSchemaData = ref(props.formSchema);
//导入弹窗信息
const visibleUpload=ref(false)
const titleUpload=ref('导入')
let formStateUpload=reactive({
  reportType:'',
})
let fileList = reactive<any[]>([]); //上传文件列表

//导出弹窗信息
let visibleDown=ref(false)
let titleDown=ref('导出')
let formStateDown=reactive({
  reportType:''
})
watch(
  () => props.formSchema,
  (val) => {
    formSchemaData.value = val;
  }
);

provide('formSchema', formSchemaData);
provide('isUpdate', isUpdate);
provide('formData', record);
provide('deviceType', props.deviceType);
// const glob = useGlobSetting();
const [registerModal, { openModal, closeModal }] = useModal();

const columnList = getTableHeaderColumns(props.columnsType);

// 列表页面公共参数、方法
const { prefixCls, tableContext, doRequest } = useListPage({
  designScope: props.designScope,
  tableProps: {
    title: props.title,
    api: props.list,
    columns: props.columns.length > 0 ? (props.columns as any[]) : columnList,
    showTableSetting: false,
    // size: 'small',
    // bordered: false,
    formConfig: {
      showAdvancedButton: true,
      // labelWidth: 100,
      labelAlign: 'left',
      labelCol: {
        xs: 24,
        sm: 24,
        md: 24,
        lg: 9,
        xl: 7,
        xxl: 5,
      },
      schemas: props.searchFormSchema as any[],
    },
    useSearchForm: props.searchFormSchema.length > 0 ? true : false,
    striped: true,
    actionColumn: {
      width: 180,
    },
    // beforeFetch: (params) => {
    //   return Object.assign(params, { column: 'createTime', devicekind: props.deviceType });
    // },
  },
});

//注册table数据
const [registerTable, { reload, getForm }, { rowSelection, selectedRowKeys }] = tableContext;

const saveOrUpdateHandler = async (params) => {
  try {
    await props.saveOrUpdate(params, isUpdate.value);
    !props.showTab ? closeModal() : '';
    // await doRequest(props.list, { confirm: false });
    reload();
    emit('submitSuccess', params);
  } catch (error) {
    message.error('保存失败，请联系管理员');
  }
};

/**
 * 新增事件
 */
function handleAdd() {
  for (let key in record) {
    delete record[key];
  }
  isUpdate.value = false;
  openModal(true);
}

/**
 * 编辑事件
 */
function handleEdit(data) {
  isUpdate.value = true;
  Object.assign(record, toRaw(data));
  record.deviceId = ''
  openModal(
    true,
    {
      record,
    },
    false
  );
}

/**
 * 删除事件
 */
async function handleDelete(record) {
  await props.deleteById({ id: record.id }, reload);
}

//提取
function handleExtract() {
  visibleTq.value = true
  formStateTq.reportType = ''
}
//确定提取
async function confirmTq() {
  await props.readReportData({ reportType: formStateTq.reportType })
  visibleTq.value = false
  
}
//取消提取
function cancelTq() {
  formStateTq.reportType = ''
  visibleTq.value = false
}
//打开导入弹窗
function handleUpload(){
visibleUpload.value=true
formStateUpload.reportType=''
fileList.length=0
}
 //上传文件
 let beforeUpload = (file) => {
    fileList.length = 0;
    let index = file.name.indexOf('.');
    let name = file.name.substring(index + 1);
    if (name == 'png' || name == 'jpg' || name == 'gif' || name == 'psd' || name == 'webp') {
      createMessage.warning('禁止上传图片类型的文件!');
    } else {
      fileList.push(file);
    }
  };
  // 文件移除
  let handleRemove = (file) => {
    const index = fileList.indexOf(file);
    const newFileList = fileList.slice();
    newFileList.splice(index, 1);
    fileList.length = 0;
  };
  //确定上传
  async function confirmUpload(){
    const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('reportType', formStateUpload.reportType);
       await props.getImportUrl(formData, reload);
     visibleUpload.value=false
     
  }
  //取消上传
  function cancelUpload(){
visibleUpload.value=false
formStateUpload.reportType=''
  }
  //打开导出弹窗
  function handleDownload(){
    visibleDown.value=true
    formStateDown.reportType=''
  }
  //确定导出
 async function confirmDownload(){
  let res=await props.getExportUrl({reportType:formStateDown.reportType})
  let filename = `${new Date().getTime()}.xlsx`;
  downFilePublic(res, filename);
  visibleDown.value=false
  }
  // 下载公用方法
function downFilePublic(content, fileName) {
  const blob = new Blob([content], { type: 'application/xlsx;charset=UTF-8' }); // 构造一个blob对象来处理数据
  // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
  // IE10以上支持blob但是依然不支持download
  if ('download' in document.createElement('a')) {
    // 支持a标签download的浏览器
    const link = document.createElement('a'); // 创建a标签
    link.download = fileName; // a标签添加属性
    link.style.display = 'none';
    link.href = URL.createObjectURL(blob);
    document.body.appendChild(link);
    link.click(); // 执行下载
    URL.revokeObjectURL(link.href); // 释放url
    document.body.removeChild(link); // 释放标签
  } else {
    // 其他浏览器
    navigator.msSaveBlob(blob, fileName);
  }
}
  //取消导出
  function cancelDownload(){
    visibleDown.value=false
    formStateDown.reportType=''
  }
/**
 * 操作列定义
 * @param record
 */
function getActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record, column),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record, column),
      },
    },
    // {
    //   label: '查看',
    //   onClick: handleDetail.bind(null, record),
    // },
  ];
}

defineExpose({
  doRequest,
  reload,
  getForm,
});
</script>

<style scoped lang="less">
@ventSpace: zxm;
@vent-table-no-hover: #00bfff10;

:deep(.@{ventSpace}-table-cell-row-hover) {
  background: #264d8833 !important;
}

:deep(.@{ventSpace}-table-row-selected) {
  background: #268bc522 !important;
}

:deep(.@{ventSpace}-table-tbody > tr > td) {
  background-color: #0dc3ff05;
}

:deep(.jeecg-basic-table-row__striped) {
  td {
    background-color: @vent-table-no-hover !important;
  }
}

:deep(.@{ventSpace}-select-dropdown) {

  .@{ventSpace}-select-item-option-selected,
  .@{ventSpace}-select-item-option-active {
    background-color: #ffffff33 !important;
  }

  .@{ventSpace}-select-item:hover {
    background-color: #ffffff33 !important;
  }
}

.zxm-form {
  padding: 20px 0px !important;
  box-sizing: border-box;
}

.opertion-btn {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 0px 20px;

}
</style>