<template>
  <div class="content">
    <div class="code-title top-title">
      {{ t('code.codeProgramme.importCodeProgram.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.codeProgramme.importCodeProgram.uploadText') }}
            </p>
          </upload-dragger>
        </div>
        <div class="upload-template">
          <p class="tip-upload-text">
            {{ t('code.codeProgramme.importCodeProgram.uploadTextTip') }}
          </p>
          <p class="tip-detail-upload-text">
            {{ t('code.codeProgramme.importCodeProgram.uploadTextTipDetail') }}
          </p>
          <h-button @click="downTemplateClick" class="download-template-btn">
            {{ t('code.codeProgramme.importCodeProgram.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.codeProgramme.importCodeProgram.parseBtn') }}
        </h-button>
      </div>
    </div>
    <div v-if="tipDatas.data.length > 0" class="upload-explain">
      <div class="reminder">{{ t('code.codeProgramme.importCodeProgram.explainTip') }}</div>

      <div class="explain-content">
        <div v-for="(item, index) in tipDatas.data" :key="index">
          <div v-if="item.type" style="color: #999">{{ item.type }}</div>
          <div v-if="item.name && item.name.length > 0" style="color: #666666">
            “{{ item.name }}”
          </div>
          <div
            :style="
              tipDatas.success ? (item.name ? 'color: #666666' : 'color: #3979F9') : 'color: red'
            "
          >
            {{ item.value }}
          </div>
        </div>
      </div>
    </div>
    <h-divider class="import-divider" dashed></h-divider>
    <div class="upload-bottom">
      <div class="tabBox">
        <h-tabs
          v-model:activeKey="tabData.activeKey"
          @change="onTabClick"
          id="CodeSegment-queryTabs"
        >
          <h-tab-pane
            key="CodePrograme-Table-title"
            :tab="t('code.codeProgramme.importCodeProgram.tabProgram')"
          ></h-tab-pane>
          <h-tab-pane
            key="CodeSegment-Table-title"
            :tab="t('code.codeProgramme.importCodeProgram.tabSeg')"
          ></h-tab-pane>
          <h-tab-pane
            key="CodeValue-Table-title"
            :tab="t('code.codeProgramme.importCodeProgram.tabValue')"
          ></h-tab-pane>
        </h-tabs>
      </div>
      <div class="tab-content">
        <div v-if="isShowParse" class="bottom">
          <h-row :gutter="24">
            <h-col :span="24">
              <div id="CodePrograme-Table-title" class="code-title bottom-title">
                {{ t('code.codeProgramme.importCodeProgram.tabProgram') }}
              </div>
            </h-col>
            <h-col :span="24">
              <h-table
                id="CodePrograme-Table-import"
                :columns="proColumns"
                :data-source="proDatas"
                rowKey="EID"
                :pagination="false"
                :needRowIndex="true"
                :show-size="false"
                :showExport="false"
                :animateRows="false"
                show-setting
                :title="t('code.codeProgramme.importCodeProgram.programTitle')"
                :row-selection="{
                  type: 'checkbox',
                  memory: true,
                  clickSelectTrigger: 'row',
                  unSelectable: true,
                }"
                :scroll="{
                  extra: 24,
                  y: true,
                }"
              ></h-table>
            </h-col>
            <h-col :span="24">
              <div id="CodeSegment-Table-title" class="code-title bottom-title">
                {{ t('code.codeProgramme.importCodeProgram.tabSeg') }}
              </div>
            </h-col>
            <h-col :span="24">
              <h-table
                id="CodeSegment-Table-import"
                :columns="segColumns"
                :data-source="segDatas"
                rowKey="EID"
                :pagination="false"
                :needRowIndex="true"
                :show-size="false"
                :showExport="false"
                :animateRows="false"
                show-setting
                :title="t('code.codeProgramme.importCodeProgram.segTitle')"
                :row-selection="{
                  type: 'checkbox',
                  memory: true,
                  clickSelectTrigger: 'row',
                  unSelectable: true,
                }"
                :scroll="{
                  extra: 24,
                  y: true,
                }"
              ></h-table>
            </h-col>
            <h-col :span="24">
              <div id="CodeValue-Table-title" class="code-title bottom-title">
                {{ t('code.codeProgramme.importCodeProgram.tabValue') }}
              </div>
            </h-col>
            <h-col :span="24">
              <h-table
                id="CodeValue-Table-import"
                :columns="valColumns"
                :data-source="valDatas"
                rowKey="EID"
                :pagination="false"
                :needRowIndex="true"
                :show-size="false"
                :showExport="false"
                :animateRows="false"
                show-setting
                :title="t('code.codeProgramme.importCodeProgram.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.codeProgramme.importCodeProgram.importTip') }}</div>
            <div>{{ t('code.codeProgramme.importCodeProgram.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,
  Tabs as HTabs,
  TabPane as HTabPane,
  Divider as HDivider,
} 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: 'ImportCodeProgram',
  props: props,
  components: {
    HRow,
    HCol,
    HTable,
    HIcon,
    HButton,
    UploadDragger,
    HTabs,
    HTabPane,
    HDivider,
    ReloadOutlined,
    CloseOutlined,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const isShowParse = ref(false);
    const proDatas = ref([]);
    const segDatas = ref([]);
    const valDatas = ref([]);
    const uploadFile = ref();
    const uploadData = ref();
    const uploadRef = ref();
    const tipDatas = reactive({
      success: true,
      data: [],
    });

    const proColumns = [
      {
        dataIndex: 'EID',
        ellipsis: true,
        filterMultiple: true,
        fixed: false,
        multiline: false,
        title: t('code.codeProgramme.importCodeProgram.eid'),
        width: '10%',
      },
      {
        dataIndex: 'codeSchemeName',
        title: t('code.codeProgramme.importCodeProgram.proName'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'describes',
        title: t('code.codeProgramme.importCodeProgram.describes'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
    ];

    const segColumns = [
      {
        dataIndex: 'EID',
        ellipsis: true,
        filterMultiple: true,
        fixed: false,
        multiline: false,
        title: t('code.codeProgramme.importCodeProgram.eid'),
        width: '15%',
      },
      {
        dataIndex: 'codeSchemeName',
        title: t('code.codeProgramme.importCodeProgram.proName'),
        ellipsis: true,
        filterMultiple: true,
        width: '20%',
      },
      {
        dataIndex: 'codeSegmentName',
        title: t('code.codeProgramme.importCodeProgram.segName'),
        ellipsis: true,
        filterMultiple: true,
        width: '20%',
      },
      {
        dataIndex: 'codeSegmentDescribes',
        title: t('code.codeProgramme.importCodeProgram.describes'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'length',
        title: t('code.codeProgramme.importCodeProgram.length'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'roughRules',
        title: t('code.codeProgramme.importCodeProgram.roughRules'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'fineRules',
        title: t('code.codeProgramme.importCodeProgram.fineRules'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'codeSeparator',
        title: t('code.codeProgramme.importCodeProgram.codeSeparator'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'parentName',
        title: t('code.codeProgramme.importCodeProgram.parentName'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
    ];

    const valColumns = [
      {
        dataIndex: 'EID',
        ellipsis: true,
        filterMultiple: true,
        fixed: false,
        multiline: false,
        title: t('code.codeProgramme.importCodeProgram.eid'),
        width: '10%',
      },
      {
        dataIndex: 'codeSchemeName',
        title: t('code.codeProgramme.importCodeProgram.proName'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'codeSegmentName',
        title: t('code.codeProgramme.importCodeProgram.segName'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'codeValue',
        title: t('code.codeProgramme.importCodeProgram.valueName'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'codeValueDescribes',
        title: t('code.codeProgramme.importCodeProgram.describes'),
        ellipsis: true,
        filterMultiple: true,
        width: '15%',
      },
      {
        dataIndex: 'parentValue',
        title: t('code.codeProgramme.importCodeProgram.parentValue'),
        ellipsis: true,
        filterMultiple: true,
        multiline: false,
        resizable: true,
        rowSpan: false,
        width: '15%',
      },
    ];

    // tab栏相关
    const tabData = reactive({
      activeKey: 'CodePrograme-Table-title',
      items: [],
    });
    const onTabClick = (activeKey: string) => {
      tabData.activeKey = activeKey;
      if (!isShowParse.value) {
        return;
      }
      document.getElementById(activeKey).scrollIntoView();
    };

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

    const downTemplateClick = async () => {
      const data = await Http.get<any>({
        url: '/api/codemanagement/codeManagement/exportCodeSchemeTemplate',
        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')) {
          // // 非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 {
        message.error(data.msg);
      }
    };

    const beforeUpload = (file: any) => {
      changeButtonEvent(true);
      tipDatas.data.length = 0;
      proDatas.value = [];
      segDatas.value = [];
      valDatas.value = [];
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        message.error(t('code.codeProgramme.importCodeProgram.uploadSize'));
      }
      return isLt1M;
    };

    const parseFile = async (options: any, filename: string) => {
      const data = await Http.uploadFile<any>(
        {
          url: '/api/codemanagement/codeManagement/importCodeSchemeData',
          onUploadProgress: (progressEvent: any) => {
            // console.log('progressEvent', progressEvent);
          },
        },
        { file: options, name: filename },
      );
      if (data.code === 200) {
        isShowParse.value = true;
        proDatas.value = [];
        segDatas.value = [];
        valDatas.value = [];
        proDatas.value = data.data.schemeList.map((item: any, index: number) => {
          return { EID: index + 1, ...item };
        });
        segDatas.value = data.data.segmentList.map((item: any, index: number) => {
          return { EID: index + 1, ...item };
        });
        valDatas.value = data.data.valueList.map((item: any, index: number) => {
          return { EID: index + 1, ...item };
        });
      } else {
        isShowParse.value = false;
        message.error(data.msg);
      }
    };

    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 data = await useHttp({
        url: '/api/codemanagement/codeManagement/checkImportCodeSchemeData',
        method: 'post',
        params: {
          schemeList: proDatas.value.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          segmentList: segDatas.value.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          valueList: valDatas.value.map(item => {
            const { EID: _, ...iItem } = item;
            return { ...iItem };
          }),
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      tipDatas.data.length = 0;
      if (data.code === 200 && data.data.code == 200) {
        tipDatas.success = true;
        if (data.data.msg.length > 0) {
          tipDatas.data.push(...data.data.msg);
        } else {
          tipDatas.data.push({
            type: t('code.codeProgramme.importCodeProgram.dataSizeTip', {
              dataSize: data.data.dataSize,
            }),
            value: t('code.codeProgramme.importCodeProgram.parseSuccessTip'),
          });
        }
        changeButtonEvent(false);
      } else {
        tipDatas.success = false;
        tipDatas.data.push(...data.data.msg);
        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,
      valColumns,
      proColumns,
      segColumns,
      proDatas,
      segDatas,
      valDatas,
      tabData,
      tipDatas,
      uploadFile,
      isShowParse,
      onTabClick,
      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;

        span {
          color: #999;
        }
        .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 {
    display: flex;
    margin-top: 8px;
    color: #999;
    margin-left: 10px;
    .reminder {
      // min-width: 100px;
      width: 80px;
      margin-left: 24px;
    }
    .explain-content {
      // padding: 0 24px;
      padding-right: 24px;
      width: 100%;
      div {
        display: flex;
        div {
          margin-right: 5px;
        }
      }
    }
  }
  .import-divider {
    color: #e9e9e9;
  }
  .upload-bottom {
    margin-top: 15px;
    height: 500px;
    .tabBox {
      #CodeSegment-queryTabs {
        :deep(.ant-tabs-nav) {
          margin-top: 0;
          // border-bottom: 1px dashed #e9e9e9;
          .ant-tabs-nav-list {
            .ant-tabs-tab {
              padding: 0 0 12px 0;
            }
          }
        }
      }
    }
    .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;
      }
    }
  }
}
.table-empty-box {
  padding: 20px 0;
  text-align: center;
  img {
    width: 70px;
    height: 40px;
  }
  h3 {
    color: rgba(0, 0, 0, 0.4);
    font-size: 14px;
  }
}
@import url('../title.less');
</style>
