<template>
  <div class="content">
    <div class="code-title top-title">{{ t('code.codeValue.importCodeValue.codeTitle') }}</div>
    <div class="upload-top">
      <div class="upload-operate">
        <div class="upload-dragger">
          <upload-dragger
            ref="uploadRef"
            name="uploadFile"
            :max-count="1"
            :multiple="false"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :customRequest="doFileUpload"
          >
            <p class="ant-upload-drag-icon">
              <h-icon name="icp-code-import" class="code-import-svg" />
            </p>
            <p class="drag-upload-text">{{ t('code.codeValue.importCodeValue.uploadText') }}</p>
          </upload-dragger>
        </div>
        <div class="upload-template">
          <p class="tip-upload-text">{{ t('code.codeValue.importCodeValue.uploadTextTip') }}</p>
          <p class="tip-detail-upload-text">
            {{ t('code.codeValue.importCodeValue.uploadTextTipDetail') }}
          </p>
          <h-button @click="downTemplateClick" class="download-template-btn">
            {{ t('code.codeValue.importCodeValue.downBtn') }}
          </h-button>
        </div>
      </div>

      <div class="upload-content" v-if="uploadFile">
        <h-icon class="icp-file-identifying" size="small" name="icp-file-identifying"></h-icon>
        <div class="upload-label">
          <span :style="uploadFile.file.status == 'error' ? 'color: red' : ''">
            {{ uploadFile.file.name }}
          </span>
          <reload-outlined class="upload-reload" @click="refreshClick" />
          <close-outlined class="upload-close" @click="removeClick" />
        </div>

        <h-button class="download-template-btn" v-if="isShowParse" @click="parseClick">
          {{ t('code.codeValue.importCodeValue.parseBtn') }}
        </h-button>
      </div>
    </div>
    <div v-if="tipDatas.length > 0" class="upload-explain">
      <div class="reminder">{{ t('code.codeValue.importCodeValue.explainTip') }}</div>
      <div class="explain-content">
        <div v-for="(item, index) in tipDatas" :key="index" :style="item.show ? 'color: red' : ''">
          {{ item.title }}
        </div>
      </div>
    </div>
    <div class="upload-bottom">
      <div class="tab-content">
        <div v-if="isShowParse" class="bottom">
          <h-row :gutter="24">
            <h-col :span="24">
              <div class="code-title bottom-title">
                {{ t('code.codeValue.importCodeValue.valueTitle') }}
              </div>
            </h-col>
            <h-col :span="24">
              <h-table
                id="CodeValue-Table"
                :columns="columns"
                :data-source="dataSource"
                rowKey="EID"
                :needRowIndex="true"
                :show-size="false"
                :showExport="false"
                :animateRows="false"
                show-setting
                :title="t('code.codeValue.importCodeValue.valueTitle')"
                :row-selection="{
                  type: 'checkbox',
                  memory: true,
                  clickSelectTrigger: 'row',
                  unSelectable: true,
                }"
                :scroll="{
                  extra: 24,
                  y: true,
                }"
              ></h-table>
            </h-col>
          </h-row>
        </div>
        <div v-else>
          <div class="import-tip">
            <img src="~@/assets/table-null.png" class="table-null" />
            <div>{{ t('code.codeValue.importCodeValue.importTip') }}</div>
            <div>{{ t('code.codeValue.importCodeValue.importTipDown') }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref } from 'vue';
import {
  Table as HTable,
  Button as HButton,
  Icon as HIcon,
  Row as HRow,
  Col as HCol,
} from '@crami/ui';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { ReloadOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { message, UploadDragger } from 'ant-design-vue';
import { Http, useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const props = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'ImportCodeValue',
  props: props,
  components: {
    HRow,
    HCol,
    HTable,
    HIcon,
    HButton,
    UploadDragger,
    ReloadOutlined,
    CloseOutlined,
  },
  setup: (props: any) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const isShowParse = ref(false);
    const uploadRef = ref();
    const uploadData = ref();
    const uploadFile = ref();
    const tipDatas = reactive([]);
    const dataSource = ref([]);

    const columns = [
      {
        dataIndex: 'EID',
        ellipsis: true,
        filterMultiple: true,
        fixed: false,
        multiline: false,
        sorter: false,
        title: t('code.codeValue.importCodeValue.eid'),
        width: '15%',
      },
      {
        dataIndex: 'codeValue',
        title: t('code.codeValue.importCodeValue.valueName'),
        ellipsis: true,
        filterMultiple: true,
        sorter: false,
        width: '15%',
      },
      {
        dataIndex: 'codeValueDescribes',
        title: t('code.codeValue.importCodeValue.describes'),
        ellipsis: true,
        filterMultiple: true,
        sorter: false,
        width: '15%',
      },
      {
        dataIndex: 'parentValue',
        title: t('code.codeValue.importCodeValue.parentValue'),
        ellipsis: true,
        filterMultiple: true,
        multiline: false,
        resizable: true,
        rowSpan: false,
        sorter: false,
        width: '15%',
      },
    ];

    const refreshClick = () => {
      changeButtonEvent(true);
      isShowParse.value = false;
      tipDatas.length = 0;
      dataSource.value = [];
      doFileUpload(uploadData.value, true);
    };
    const removeClick = () => {
      changeButtonEvent(true);
      uploadFile.value = null;
      tipDatas.length = 0;
      dataSource.value = [];
      uploadData.value = null;
      isShowParse.value = false;
    };

    const downTemplateClick = async () => {
      const data = await Http.get<any>({
        url: '/api/codemanagement/codeValue/exportCodeValueTemplate',
        responseType: 'blob',
      });
      if (data.code === 200) {
        const content = data.data;
        const blob = new Blob([content]);
        const date = getNowDate();
        const fileName = date + '.xlsx';
        if ('download' in document.createElement('a')) {
          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 {
        message.error(data.msg);
      }
    };

    const beforeUpload = (file: any) => {
      changeButtonEvent(true);
      tipDatas.length = 0;
      dataSource.value = [];

      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        message.error(t('code.codeValue.importCodeValue.uploadSize'));
      }
      return isLt1M;
    };

    const parseFile = async (options: any, filename: string) => {
      const data = await Http.uploadFile<any>(
        {
          url: '/api/codemanagement/codeValue/importCodeValueData',
          onUploadProgress: (progressEvent: any) => {},
        },
        { file: options, name: filename },
      );

      if (data.code === 200) {
        isShowParse.value = true;
        const result = data.data.map((item: any, index: number) => {
          return { EID: index + 1, ...item };
        });
        dataSource.value = [].concat(result);
      } else {
        isShowParse.value = false;
      }
    };

    const doFileUpload = async (options: any, refresh = false) => {
      if (!refresh) {
        uploadFile.value = options;
        const reader = new FileReader();
        reader.readAsDataURL(options.file);
        reader.onload = function () {
          uploadData.value = reader.result;
          parseFile(
            dataURLtoFile(uploadData.value, uploadFile.value.file.name),
            uploadFile.value.filename,
          );
        };
      } else {
        uploadData.value = options;
        parseFile(
          dataURLtoFile(uploadData.value, uploadFile.value.file.name),
          uploadFile.value.filename,
        );
      }
    };

    const dataURLtoFile = (dataurl, filename) => {
      let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    };

    const parseClick = async () => {
      const jsonArr = dataSource.value.map(item => {
        const { EID: _, ...iItem } = item;
        return { ...iItem };
      });
      const jsonData = JSON.stringify(jsonArr);
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/checkImportCodeValueData',
        method: 'post',
        params: {
          codeSegmentId: props.componentProps?.params.codeSegmentId,
          importJsonData: jsonData,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });

      if (data.code === 200) {
        tipDatas.length = 0;
        if (!data.data.errorMsg || data.data.errorMsg.length === 0) {
          tipDatas.push({
            title: t('code.codeValue.importCodeValue.dataSizeTip', { dataSize: data.data.size }),
            show: false,
          });
          changeButtonEvent(false);
        } else {
          tipDatas.push(
            ...data.data.errorMsg.map(item => {
              return { title: item, show: true };
            }),
          );
          changeButtonEvent(true);
        }
      } else {
        changeButtonEvent(true);
      }
    };

    const changeButtonEvent = (isChange: boolean) => {
      bus.emit('changeImportStatus', isChange);
    };

    const getNowDate = () => {
      const date = new Date();
      const Y = date.getFullYear() + '-';
      const M =
        (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '-';
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + '-';
      const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + '-';
      const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    };

    return {
      t,
      uploadRef,
      uploadFile,
      columns,
      dataSource,
      tipDatas,
      isShowParse,
      refreshClick,
      removeClick,
      downTemplateClick,
      doFileUpload,
      beforeUpload,
      parseClick,
    };
  },
});
</script>

<style lang="less" scoped>
@import '@/theme/default/variables.less';

.content {
  height: 100%;
  .upload-top {
    .upload-operate {
      display: flex;

      .upload-dragger {
        // width: 50%;
        width: 338px;
        height: 140px;
        margin-left: 32px;
        margin-right: 39px;
        :deep(.ant-upload-drag) {
          background: rgba(0, 0, 0, 0.02);
        }
        :deep(.ant-upload-btn) {
          padding: 34px 0;
        }
        .ant-upload-drag-icon {
          .code-import-svg {
            :deep(.h-svg-icon) {
              width: 26px !important;
              height: 23px !important;
            }
          }
        }
        .drag-upload-text {
          color: #333333;
          font-weight: 500;
          font-size: 16px;
          font-family: PingFangSC-Medium, PingFang SC;
        }
      }

      .upload-template {
        // margin-left: 25px;
        margin-top: 14px;
        .tip-upload-text {
          font-size: 16px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #333333;
          margin-bottom: 0.5rem;
        }
        .tip-detail-upload-text {
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #999999;
          margin-bottom: 1.7em;
        }
      }
    }
    .download-template-btn {
      border-radius: 4px;
      border: 1px solid #4e5a70;
      > span {
        color: #4e5a70;
      }
    }

    .upload-content {
      display: flex;
      margin-top: 10px;
      margin-left: 20px;
      .icp-file-identifying {
        margin-right: 10px;
        margin-left: 12px;
        padding-top: 13px;
        svg {
          width: 14px;
          height: 14px;
        }
      }
      .upload-label {
        position: relative;
        padding-top: 10px;
        border-bottom-width: 1px;
        border-bottom-color: #3979f9;
        border-bottom-style: solid;
        flex: 1 1;
        margin-right: 20px;
        .upload-reload {
          position: absolute;
          right: 35px;
          color: rgba(0, 0, 0, 0.2);
        }
        .upload-close {
          position: absolute;
          right: 5px;
          color: rgba(0, 0, 0, 0.2);
        }
      }
      width: 100%;
      .download-template-btn {
        margin-right: 56px;
      }
    }
  }
  .upload-explain {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    align-items: start;
    color: #999;
    margin-left: 10px;
    .reminder {
      width: 80px;
      margin-left: 24px;
    }
    .explain-content {
      padding-right: 24px;
      width: 90%;
    }
  }
  .upload-bottom {
    margin-top: 15px;
    height: 300px;
    .import-tip {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 350px;
      .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;
      }
    }
  }
}
@import url('../title.less');
</style>
