<template>
  <a-modal
    :title="$t('批量导入')"
    :visible="visible"
    :confirm-loading="submitLoading"
    :cancelText="$t('关闭')"
    :okText="$t('确定')"
    @ok="toSubmit"
    @cancel="toCancel"
    wrapClassName="batch_import_list"
  >
    <a-form-model
      ref="formList"
      :model="formList"
      :rules="rules"
      v-bind="{
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
      }"
    >
      <a-form-model-item
        :label="$t('导入文件')"
        prop="file"
      >
        <a-upload
          name="file"
          :show-upload-list="false"
          accept=".js,.json"
          :beforeUpload="beforeUpload"
          :headers="{
            Authorization: `${$storage.getToken()}`,
          }"
        >
          <a-button
            type="primary"
            icon="plus"
            >{{ $t('选择') }}</a-button
          >
        </a-upload>
      </a-form-model-item>
      <a-form-model-item
        :label="$t('类型')"
        prop="type"
      >
        <a-select
          v-model="formList.type"
          :placeholder="$t('请选择类型')"
        >
          <a-select-option
            v-for="item in $winexI18n.languageTypes"
            :value="item.value"
            :key="item.value"
          >{{ item.name }}</a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    
    <div class="table_list">
      <vxe-table
        ref="tableList"
        show-overflow
        show-header-overflow
        border
        resizable
        :row-config="{ isHover: true }"
        :data="tableList"
        height="380"
        :scroll-y="{ gt: 10 }"
      >
        <vxe-column
          type="seq"
          :title="$t('序号')"
          width="60"
          align="center"
        ></vxe-column>
        <vxe-column
          field="code"
          :title="$t('编码')"
        ></vxe-column>
        <vxe-column
          field="content"
          :title="$t('键值')"
        ></vxe-column>
        <template #empty>
          <a-empty
            :image-style="{
              height: '80px',
            }"
          >
            <span slot="description">{{ $t('暂无数据') }}</span>
          </a-empty>
        </template>
      </vxe-table>
    </div>
  </a-modal>
</template>
<script>
  const $appService = require('w-vue-basis/src/api/appService');

  export default {
    name: 'batchImport',
    props: {
      show: [Boolean],
    },
    computed: {
      visible: {
        get() {
          return this.show;
        },
        set(val) {
          this.$emit('update:show', val);
        },
      },
    },
    data() {
      return {
        tableList: [],
        formList: {
          type: undefined,
          file: undefined,
        },
        rules: {
          file: [{ required: true, message: $t('请导入文件'), trigger: 'change' }],
          type: [{ required: true, message: $t('请选择类型'), trigger: 'change' }],
        },
        submitLoading: false,
      };
    },
    watch: {
      visible(val) {
        if (val) {}
      },
    },
    created() {},
    methods: {
      /**
       * @Author: y_zp
       * @description: 提交
       */
      toSubmit() {
        this.$refs.formList.validate((valid) => {
          if (valid) {
            this.submitLoading = true;
            let params = this.tableList.map((item) => {
              return {
                ...item,
                status: '0',
                statusName: $t('未锁定'),
                type: this.formList.type,
                _X_ROW_KEY: undefined,
              };
            });
            $appService
              .batchSaveSysLang(params)
              .then((req) => {
                this.$message.success($t('导入成功'));
                this.toCancel();
                this.$emit('change');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        });
      },
      /**
       * @Author: y_zp
       * @description: 上传
       */
      beforeUpload(e) {
        // 检查文件类型
        if (e.type != 'application/json' && e.type != 'text/javascript') {
          this.$message.warn($t('请上传JSON或JS格式的文件'));
          return;
        }
        this.formList.file = e;
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            if (!e.target.result) {
              this.$message.error($t('导入的文件为空'));
              return;
            }

            let stringVal = e.target.result;
            let firstIndex = stringVal.indexOf("export default");
            if(firstIndex > -1) {
              stringVal = stringVal.replace("export default", "");
            }

            let lastIndex = stringVal.lastIndexOf("};");
            if(lastIndex > -1) {
              stringVal = stringVal.slice(0, lastIndex) + "}" + stringVal.slice(lastIndex + 2);
            }

            let jsonData = {};
            if (e.type == 'application/json') {
              jsonData = JSON.parse(stringVal);
            } else {
              const module = eval('(' + stringVal + ')');
              jsonData = module.default || module;
            }
            this.tableList = [];
            for (let i in jsonData) {
              this.tableList.push({ code: i, content: jsonData[i] });
            }
          } catch (error) {
            this.$message.error($t('文件解析错误') + error.message);
          }
        };

        reader.onerror = () => {
          this.$message.error($t('文件读取出错'));
        };

        if (e.type == 'application/json') {
          reader.readAsText(e);
        } else {
          reader.readAsText(e, 'UTF-8');
        }
      },

      toCancel() {
        this.visible = false;
        this.tableList = [];
        this.formList = {
          type: undefined,
          file: undefined,
        };
      },
    },
  };
</script>
<style lang="less" scoped>
  /deep/.batch_import_list {
    .ant-modal-body {
      padding: 12px 16px;
    }
  }
</style>
