<template>
  <div id="Guide">
    <h-modal
      :visible="compile2"
      @ok="handleOk"
      closable
      centered
      @cancel="cancel"
      style="min-width: 915px"
      :title="t('ImpExp.common.Imp')"
      :okText="t('ImpExp.common.ConfirmImp')"
      :destroyOnClose="true"
      :maskClosable="false"
      :footer="false"
      wrapClassName="impexp-guide-modal"
    >
      <h-row :gutter="25">
        <div class="tops list section-title">
          {{ t('ImpExp.common.ImpFile') }}
        </div>
        <h-col :span="12">
          <h-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="false"
            :customRequest="customRequest"
            @drop="handleDrop"
            :maxCount="1"
            :progress="progress"
            @remove="remove"
          >
            <img src="../Picture/tubiao.svg" alt="" style="margin: 6px 0 20px" />
            <p class="ant-upload-text">{{ t('ImpExp.common.ClickUpload') }}</p>
            <p class="ant-upload-hint">{{ t('ImpExp.common.SupportExtend') }}</p>
          </h-upload-dragger>
        </h-col>
        <h-col :span="12" style="padding: 16px 24px">
          <p style="font-size: 16px; margin: 0; color: #333; font-weight: 500">
            {{ t('ImpExp.common.DownloadTemplate') }}
          </p>
          <p class="col">{{ t('ImpExp.common.DownloadUpload') }}</p>
          <h-button @click="downLoad">{{ t('ImpExp.common.DownloadUp') }}</h-button>
        </h-col>
      </h-row>
      <h-row v-if="Number(errCount) >= 0">
        <h-col>
          <div style="font-size: 14px; margin-top: 5px" v-if="Number(errCount) === 0">
            {{ t('ImpExp.common.Hint') }}{{ t('ImpExp.common.Total') }} {{ dataCount }}
            {{ t('ImpExp.common.data') }}
            <span class="succeed">{{ t('ImpExp.common.Succeed') }}</span>
          </div>
          <div style="font-size: 14px; margin-top: 5px" v-if="Number(errCount) > 0">
            {{ t('ImpExp.common.Hint') }}
            <span class="color-red" @click="errShow">
              {{ t('ImpExp.common.Total') }} {{ dataCount }} {{ t('ImpExp.common.data')
              }}{{ t('ImpExp.common.AbnormalData') }} {{ errCount }} {{ t('ImpExp.common.Strip')
              }}{{ t('ImpExp.common.modify') }}
            </span>
          </div>
        </h-col>
      </h-row>
      <h-row :gutter="25">
        <div class="list section-title">
          {{ t('ImpExp.common.DataList') }}
        </div>
        <div class="DataList">
          <div class="import-tip" v-if="!analysis">
            <img src="~@/assets/table-null.png" class="table-null" />
            <div class="null center" style="font-size: 16px; color: #333; font-weight: 500">
              {{ t('ImpExp.common.EmptyData') }}
            </div>
            <div class="col center">{{ t('ImpExp.common.UploadEXCEL') }}</div>
          </div>

          <h-tabs v-model:activeKey="activeKey" @change="handleTabChange" v-if="analysis">
            <h-tab-pane :tab="item.sheetName" v-for="(item, index) in sheetList" :key="index">
              <h-b-table
                id="Guide-queryTable"
                v-bind="tableProps"
                rowKey="ECODE"
                :needRowIndex="true"
                :show-size="false"
                :showExport="false"
                :animateRows="false"
                :rowSelection="false"
                :ref="handleTbaleRef"
                :scroll="{
                  extra: 24,
                  y: 335,
                }"
              ></h-b-table>
            </h-tab-pane>
          </h-tabs>
        </div>
      </h-row>
      <h-row style="margin: 10px -10px -15px">
        <h-col :span="24" style="text-align: right">
          <h-button @click="cancel" style="margin-right: 20px">
            {{ t('ImpExp.common.Cancel') }}
          </h-button>
          <h-button
            @click="handleOk"
            :disabled="startUsing || errOption == 3 ? false : true"
            :style="startUsing || errOption == 3 ? 'background-color: #4a556bff; color: #fff' : ''"
            :loading="loading"
          >
            {{ t('ImpExp.common.ConfirmImp') }}
          </h-button>
          <!-- v-if="startUsing && errOption == 3" -->
          <!-- <h-button disabled v-if="!startUsing || errOption != 3">
            {{ t('ImpExp.common.ConfirmImp') }}
          </h-button> -->
        </h-col>
      </h-row>
    </h-modal>
    <h-modal
      style="min-width: 915px"
      id="Guide-queryModal"
      v-model:visible="modalVisible"
      :title="t('ImpExp.common.DataPrompt')"
      :footer="null"
      :destroyOnClose="true"
      :cancelText="t('ImpExp.common.Cancel')"
      closable
      centered
      wrap-class-name="full"
    >
      <problem-list
        :rowData="rowData"
        @cancelClick="handleCancel"
        :userIds="userIds"
        :dataCaches="dataCaches"
        :dataList="dataList"
        :errOption="errOption"
        @startUsing="closeFun"
      ></problem-list>
    </h-modal>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch, watchEffect } from 'vue';
import { FileUploadAPI, downloadUrlAPI } from '@/api/platform/ImpExp/upload';
import {
  analysisTableAPI,
  verifyDataAPI,
  analysisDataAPI,
  getFileId,
  importErrListAPI,
} from '@/api/platform/ImpExp/Import';
import { useTable, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
/* import { commonApi } from '@/api/commonApi/index'; */
import { commonApi } from '@remote/icpx-platform/commonApi';
import { HMessage, HModal, message } from '@crami/ui';
import ProblemList from './ProblemList.vue';
import { cloneDeep, method } from 'lodash-es';
import type { UploadProps } from 'ant-design-vue';
import { useI18n } from '@crami/locale';
import { useHttp } from '@crami/http';

export default defineComponent({
  name: 'Guide',
  props: ['compile2', 'pageParams'],
  components: { ProblemList },
  setup(props, options) {
    // 多语言
    const { t } = useI18n();
    const loading = ref<boolean>(false);
    const modalVisible = ref(false);
    const rowData = ref(null);
    const analysis = ref<boolean>(false);
    const sheetList = ref([]);
    let activeKey = ref(0);
    let tableName = ref();
    let sheetName = ref();

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    // console.log(commonParams);
    const errOption = ref();

    const visible = ref<boolean>(false);
    // 点击确定时保存数据
    const handleOk = () => {
      loading.value = true;
      // 保存上传的文件
      importErrListAPI({
        ...dataList, //编码 导入按钮上默认配置
        dataCache: dataCaches.value, //数据缓存key
        customValid: customValidList.value || [],
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        userId: commonParams.value.user_id,
        lang: commonParams.value.lang,
      }).then(res => {
        if (res.code == 200) {
          message.success(t('ImpExp.common.ImpSucceed'));
          loading.value = false;
          cancel();
          // search([]);
          options.emit('Refresh');
          analysis.value = false;
          startUsing.value = false;
        } else {
          loading.value = false;
          message.warning(res.msg);
        }
      });
    };
    const cancel = () => {
      // 使用options.emit将关闭方法传给父组件
      options.emit('closeModel', (visible.value = false));
    };

    const dataList = JSON.parse(localStorage.getItem('dataImp'));
    const fileList = ref([]);
    let errCount = ref();
    let dataCount = ref('');

    // 文件上传
    const customRequest = file => {
      analysis.value = false;
      errCount.value = -1;
      setTimeout(async () => {
        if (
          file.file.name.indexOf('xls') != -1 ||
          file.file.name.indexOf('xlsx') != -1 ||
          file.file.name.indexOf('csv') != -1 ||
          file.file.name.indexOf('xlsm') != -1
        ) {
          let formData = new FormData();
          formData.append('file', file.file);
          formData.append('fileShowName', file.file.name);
          formData.append('filePath', 'platform');
          const res = await FileUploadAPI(formData);
          if (res.code == 200) {
            fileList.value[0].status = 'done';
            // console.log(fileList.value[0].status);
            analysis.value = true;
            userIds.value = res.data.eid;
            message.success(t('ImpExp.common.FileUpload'));

            // 数据解析
            await analysisDataAPI({
              ...dataList,
              fileId: res.data.eid,
              companyId: commonParams.value.companyId,
              connect: commonParams.value.connect,
              lang: commonParams.value.lang,
              userId: res.data.eid,
            }).then(res2 => {
              if (res2.code == 200) {
                dataCaches.value = res2.data.dataCache;
                // 获取sheet页数据
                analysisTableAPI({
                  ...dataList,
                  dataCache: '', //可以为空
                  companyId: commonParams.value.companyId,
                  objectID: commonParams.value.objectID,
                  connect: commonParams.value.connect,
                  lang: commonParams.value.lang,
                  userId: commonParams.value.userId,
                }).then(res3 => {
                  // console.log(res);
                  if (res3.code == 200) {
                    sheetList.value = res3.data;
                    tableName.value = res3.data[0].previewView;
                    sheetName.value = res3.data[0].sheetName;
                    tableMethods.loadInit();
                  } else {
                    message.warning(res3.msg);
                    return;
                  }
                });
                // 数据校验
                verifyDataAPI({
                  ...dataList,
                  dataCache: res2.data.dataCache,
                  companyId: commonParams.value.companyId,
                  connect: commonParams.value.connect,
                  lang: commonParams.value.lang,
                  userId: res.data.eid,
                }).then(resolve => {
                  // console.log(res);
                  if (resolve.code == 200) {
                    count.value = resolve.data.errCount;
                    if (count.value > 0) {
                      startUsing.value = false;
                    } else {
                      startUsing.value = true;
                    }
                    errCount.value = resolve.data.errCount;
                    dataCount.value = resolve.data.total;
                    errOption.value = resolve.data.errOption;
                    if (resolve.data.errOption == 3) {
                      startCodeApi();
                    }
                  } else {
                    message.warning(resolve.msg);
                    return;
                  }
                });
              } else {
                message.warning(t('ImpExp.common.abnormal'));
                analysis.value = false;
                errCount.value = -1;
                return;
              }
            });
          } else {
            message.warning(t('ImpExp.common.uploadFailing'));
            return;
          }
        } else {
          message.warning(t('ImpExp.common.SupportExtend'));
          analysis.value = false;
          errCount.value = -1;
          return;
        }
      }, 1500);
    };
    let customValidList = ref();
    const startCodeApi = async () => {
      const data = await useHttp({
        url: '/api/importservice/import/getCheckData',
        method: 'post',
        params: {
          dataCache: dataCaches.value,
        },
      });

      data.data.data.forEach(item => {
        item.option = 2;
      });
      console.log(data);
      customValidList.value = data.data.data;
    };

    const dataCaches = ref();
    const userIds = ref();

    // 监听tab页的变化
    const handleTabChange = e => {
      tableName.value = sheetList.value[e].previewView;
      sheetName.value = sheetList.value[e].sheetName;
      tableMethods.loadInit();
    };
    //下载模板
    const downLoad = () => {
      getFileId({
        ...dataList,
        dataCache: '', //可以为空
        companyId: commonParams.value.companyId,
        objectID: commonParams.value.objectID,
        connect: commonParams.value.connect,
        lang: commonParams.value.lang,
        userId: commonParams.value.userId,
      }).then(res => {
        // console.log(res, '文件id');
        if (res.code == 200) {
          downloadUrlAPI(res.data.fileId)
            .then(res => {
              var xz = new XMLHttpRequest();
              console.log(xz);
              xz.open('GET', res.data.templateUrl, true);
              xz.responseType = 'blob';
              xz.onload = function (e) {
                // console.log(e);
                var url = window.URL.createObjectURL(xz.response);
                var a = document.createElement('a');
                a.href = url;
                a.download = res.data.fileName;
                a.click();
              };
              xz.send();
            })
            .catch();
        } else {
          message.warning(res.msg);
          return;
        }
      });
    };

    const [gridRef, tableProps, tableMethods] = useTable({
      // initialLoad: false,
      init: false,
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: tableName.value,
          },
        },
      },
      // 列表数据接口
      dataSourceApi: {
        url: '/api/importservice/import/previewData',
        method: 'post',
        timeout: 999999999,
        params: {
          companyId: commonParams.value.companyId,
          connect: commonParams.value.connect,
          lang: commonParams.value.lang,
          userId: userIds.value,
          dataCache: dataCaches.value,
          sheetName: sheetName.value,
          ...dataList,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          let tempData = cloneDeep(params);
          if (typeof params.data == 'string') {
            tempData.data = JSON.parse(params.data);
            params.data = JSON.stringify({ ...tempData.data, viewName: tableName.value });
          } else if (typeof params.data != 'string') {
            tempData.data.viewName = tableName.value;
            tempData.data.userId = userIds.value;
            tempData.data.dataCache = dataCaches.value;
            params.data = JSON.stringify(tempData.data);
          }
          return {
            ...params,
          };
        }
        if (type == 'data') {
          let tempData = cloneDeep(params);
          params.sheetName = sheetName.value;
          params.viewName = tableName.value;
          params.userId = userIds.value;
          params.dataCache = dataCaches.value;
          params.page = tempData.page || 1;
          params.pageNo = tempData.pageNo || 1;
          params.pageSize = tempData.pageSize || 10;
          return {
            ...tempData,
            ...params,
          };
        }
      },
      afterRequest: (type, params: any) => {
        if (type == 'column') {
          params.columns.forEach(item => {
            item.sorter = false;
          });
          // console.log(params.columns);
        }
      },
    });
    const handleTbaleRef = (el: any) => {
      gridRef.value = el;
    };

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      pageName: 'Guide',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'Guide',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };
    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });
    const onReset = () => {
      search([]);
    };

    const errShow = () => {
      modalVisible.value = true;
      let modalData = [];
      modalData['errCount'] = errCount.value;
      modalData['dataCount'] = dataCount.value;
      rowData.value = modalData;
    };

    const handleCancel = () => {
      modalVisible.value = false;
    };
    const count = ref();
    const startUsing = ref<boolean>(false);

    const closeFun = () => {
      options.emit('Refresh');
      startUsing.value = true;
      modalVisible.value = false;
      cancel();
      search([]);
      tableMethods.query({}, true);
    };

    // 文件上传完毕后展示进度条
    const progress: UploadProps['progress'] = {
      strokeColor: {
        '0%': '#36a5f5',
        '100%': '#1890ff',
      },
      strokeWidth: 3,
      format: percent => `${parseFloat(percent.toFixed(2))}%`,
      class: 'test',
    };
    const remove = () => {
      analysis.value = false;
      errCount.value = -1;
    };
    watch(
      () => dataList,
      () => {
        dataList.value = JSON.parse(localStorage.getItem('dataImp'));
      },
      { deep: true },
    );
    return {
      customValidList,
      t,
      loading,
      progress,
      closeFun,
      count,
      startUsing,
      cancel,
      handleCancel,
      downLoad,
      errCount,
      dataCount,
      tableName,
      handleTabChange,
      errShow,
      modalVisible,
      rowData,
      handleTbaleRef,
      visible,
      handleOk,
      remove,
      fileList,
      handleDrop: (e: DragEvent) => {
        console.log(e);
      },

      analysis,
      customRequest,
      activeKey,
      sheetList,

      gridRef,
      tableProps,
      search,
      onReset,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,

      userIds,
      dataCaches,
      dataList,
      errOption,
    };
  },
});
</script>

<style lang="less" scoped>
.section-title {
  color: #333333;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  position: relative;
  text-indent: 16px;
  &::before {
    display: inline-block;
    position: absolute;
    top: 5px;
    left: 4px;
    width: 3px;
    height: 16px;
    margin-right: 5px;
    background: red;
    content: '';
  }
}
.btn {
  color: #898989;
  border: 1px solid rgb(43, 41, 41);
}
.list {
  font-size: 16px;
  width: 100%;
  margin: 24px 0 0;
}
.tops {
  margin-top: -10px;
  // margin-top: 0;
}
.DataList {
  width: 100%;
  padding: 0 12px;
  min-height: 150px;
  > div.center {
    width: 100%;
    text-align: center;
  }
  > div.ant-tabs.ant-tabs-top {
    > div.ant-tabs-holder {
      margin: 10px 12px;
    }
  }
  div.null {
    margin-top: 50px;
  }
}
.col {
  font-size: 14px;
  color: #898989;
  margin: 5px 0;
}
.data {
  transform: translateY(145px);
}
:deep(div.hoteam-b-table-list-toolbar.hoteam-b-table-list-toolbar-show-bottom) {
  display: none;
}
:deep(div.surely-table-fix-left.surely-table-row-wrapper) {
  display: none;
}
:deep(div.ant-upload.ant-upload-drag.ant-upload-drag-uploading),
:deep(div.ant-upload.ant-upload-drag) {
  height: 130px;
  background: rgba(0, 0, 0, 0.02);
}
.succeed {
  color: #4983ff;
  font-size: 14px;
}
.color-red {
  font-size: 14px;
  color: red;
  cursor: pointer;
}
:deep(div.ant-tabs.ant-tabs-top) > div.ant-tabs-nav {
  margin: -2px 8px 10px !important;
}
p.ant-upload-hint {
  margin-bottom: 5px !important;
}

.import-tip {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 500px;
  .table-null {
    width: 535px;
    height: 293px;
  }
  & > div:nth-child(2) {
    color: #333333;
    font-size: 15px;
    font-weight: 600;
  }
  div:nth-child(3) {
    color: #999999;
    font-size: 14px;
  }
}
</style>

<style>
.impexp-guide-modal .ant-modal-body {
  max-height: 90vh;
}
</style>
