<template>
  <a-modal
    :title="$t('批量设置')"
    :visible="visible"
    :confirm-loading="submitLoading"
    :cancelText="$t('关闭')"
    :okText="$t('确定')"
    :maskClosable="false"
    @ok="toSubmit"
    @cancel="toCancel"
    wrapClassName="batch_translate_list"
  >
    <a-form-model
      ref="formList"
      :model="formList"
      :rules="rules"
      v-bind="{
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      }"
    >
      <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="sourceType"
      >
        <a-select
          v-model="formList.sourceType"
          :placeholder="$t('请选择类型')"
          :options="typeList"
        >
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        :label="$t('目标类型')"
        prop="targetType"
      >
        <a-select
          v-model="formList.targetType"
          :placeholder="$t('请选择类型')"
          :options="typeList"
        >
        </a-select>
      </a-form-model-item>
    </a-form-model>
    <div class="progress_bar">
      <a-row :gutter="12">
        <a-col :span="20">
          <a-progress
            v-if="tLoading"
            :percent="progressVal"
            status="active"
            :format="percent => `${percent}%`"
          />
        </a-col>
        <a-col :span="4" align="right">
          <a-button size="small" type="primary" @click="toTranslate">翻译</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="table_list">
      <vxe-table
        ref="tableList"
        show-overflow
        show-header-overflow
        border
        resizable
        :row-config="{ isHover: true }"
        :data="dataList"
        height="300"
        :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');
  const $translateService = require('w-vue-basis/src/api/translateService');
  import md5 from 'md5';

  export default {
    name: 'batchTranslate',
    props: {
      show: [Boolean],
    },
    computed: {
      visible: {
        get() {
          return this.show;
        },
        set(val) {
          this.$emit('update:show', val);
        },
      },
    },
    data() {
      return {
        translateConfig: {},
        typeList: [],
        formList: {
          file: undefined,
          sourceType: undefined,
          targetType: undefined,
        },
        rules: {
          sourceType: [{ required: true, message: $t('请选择源类型'), trigger: 'change' }],
          targetType: [{ required: true, message: $t('请选择目标类型'), trigger: 'change' }],
        },
        dataList: [],
        submitLoading: false,
        tLoading: false,
        progressVal: 0,
      };
    },
    watch: {
      visible(val) {
        if (val) {
          this.typeList = [{
            label: "简体中文",
            value: "zh_CN",
            code: "zh",
          }, {
            label: "繁體中文",
            value: "zh_HK",
            code: "cht",
          }, {
            label: "English",
            value: "en_US",
            code: "en",
          }, {
            label: "Português",
            value: "pt_PT",
            code: "pt",
          }, {
            label: "Español",
            value: "es_ES",
            code: "spa"
          }];
          this.getTranslateConfig();
        }
      },
    },
    created() {},
    methods: {
      /**
       * @Author: y_zp
       * @description: 获取数据
       */
      // getList() {
      //   $appService
      //     .getSysLangList({
      //       pageNum: 1,
      //       pageSize: 100000,
      //       queryParams: {
      //         F_type_eq: this.type,
      //       },
      //     })
      //     .then((req) => {
      //       this.dataList = req.data.filter((item) => {
      //         return item.status == 0;
      //       });
      //     })
      //     .finally(() => {
      //       this.loading = 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 {
            debugger
            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.dataList = [];
            for (let i in jsonData) {
              this.dataList.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');
        }
      },
      /**
       * @Author: y_zp
       * @description: 翻译
       */
      toTranslate() {
        this.$refs.formList.validate(async (valid) => {
          if(!valid) {
            return;
          }
          if (this.dataList.length == 0) {
            this.$message.warn($t('请先新增数据'));
            return;
          } else if (this.formList.sourceType == this.formList.targetType) {
            this.$message.warn($t('源类型和目标类型不能相同'));
            return;
          };

          let sourceTypeItem = this.typeList.find((item) => {
            return item.value == this.formList.sourceType;
          });
          let targetTypeItem = this.typeList.find((item) => {
            return item.value == this.formList.targetType;
          });

          let dataArray = this.getArray(this.dataList, 50);

          this.tLoading = true;
          let tNum = 0;
          let newList = [];

          for(let item of dataArray) {
            let contentList = item.map((v) => {
              return v.content;
            });
            // 百度翻译
            if (this.translateConfig.type == 'baidu') {
              const salt = new Date().getTime(); //随机数
              const signData =
                this.translateConfig.appId +
                contentList.join('\n') +
                salt +
                this.translateConfig.secretKey;
              let param = {
                q: contentList.join('\n'),
                from: sourceTypeItem.code,
                to: targetTypeItem.code,
                appid: this.translateConfig.appId,
                salt: salt,
                sign: md5(signData),
              };
              // 百度翻译，每秒请求量为1，否则会报错：54003
              const translateResult = await this.translateWithDelay(param);
              if(translateResult.status == 200) {
                let tList = translateResult.data.trans_result;
                let newItem = item.map((v, i) => {
                  return {
                    code: v.code,
                    content: tList[i].dst,
                    type: targetTypeItem.value,
                    status: 0,
                    statusName: $t('未锁定'),
                  };
                });
                tNum++;
                this.progressVal = Math.round((tNum / dataArray.length) * 100);
                newList = newList.concat(newItem);

                if(tNum == dataArray.length) {
                  this.dataList = newList;
                }
              } else {
                this.$message.error($t('翻译异常，请稍后重试'));
              }
            }
          }
        })
      },

      async toSubmit() {
        if (this.dataList.length == 0) {
          this.$message.warn($t('请先新增数据'));
          return;
        } else if (this.formList.sourceType == this.formList.targetType) {
          this.$message.warn($t('源类型和目标类型不能相同'));
          return;
        } else if(!this.tLoading) {
          this.$message.warn($t('请先翻译'));
          return;
        } else if(this.tLoading && this.progressVal != 100) {
          this.$message.warn($t('正在翻译中，请稍后'));
          return;
        }
        this.submitLoading = true;
        let dataArray = this.getArray(this.dataList, 50);
        let sNum = 0;
        for(let item of dataArray) {
          const { data } = await $appService.batchSaveSysLang(item);
          sNum++;
          if (sNum == dataArray.length) {
            this.submitLoading = false;
            this.$message.success($t('批量设置成功'));
            this.toCancel();
            this.$emit('change');
          }
        }
      },

      /**
       * @Author: y_zp
       * @description: 翻译并提交
       */
      async toSubmit1() {
        this.$refs.formList.validate(async (valid) => {
          if (valid) {
            if (this.dataList.length == 0) {
              this.$message.warn($t('请先新增数据'));
              return;
            } else if (this.formList.sourceType == this.formList.targetType) {
              this.$message.warn($t('源类型和目标类型不能相同'));
              return;
            }

            let sourceTypeItem = this.typeList.find((item) => {
              return item.value == this.formList.sourceType;
            });
            let targetTypeItem = this.typeList.find((item) => {
              return item.value == this.formList.targetType;
            });

            let dataArray = this.getArray(this.dataList, 50);

            this.tLoading = true;
            this.submitLoading = true;
            let tNum = 0;

            for(let item of dataArray) {
              let contentList = item.map((v) => {
                return v.content;
              });
              // 百度翻译
              if (this.translateConfig.type == 'baidu') {
                const salt = new Date().getTime(); //随机数
                const signData =
                  this.translateConfig.appId +
                  contentList.join('\n') +
                  salt +
                  this.translateConfig.secretKey;
                let param = {
                  q: contentList.join('\n'),
                  from: sourceTypeItem.code,
                  to: targetTypeItem.code,
                  appid: this.translateConfig.appId,
                  salt: salt,
                  sign: md5(signData),
                };
                // 百度翻译，每秒请求量为1，否则会报错：54003
                const translateResult = await this.translateWithDelay(param);
                if(translateResult.status == 200) {
                  let tList = translateResult.data.trans_result;
                  let newItem = item.map((v, i) => {
                    return {
                      code: v.code,
                      content: tList[i].dst,
                      type: targetTypeItem.value,
                      status: 0,
                      statusName: $t('未锁定'),
                    };
                  });
                  tNum++;
                  this.progressVal = Math.round((tNum / dataArray.length) * 100);
                  if (tNum == dataArray.length) {
                    this.tLoading = false;
                  }
                  console.log(newItem)
                  // 保存
                  const { data: saveData } = await $appService.batchSaveSysLang(newItem);

                  if (tNum == dataArray.length) {
                    this.submitLoading = false;
                    this.$message.success($t('批量设置成功'));
                    this.toCancel();
                    this.$emit('change');
                  }
                } else {
                  this.$message.error($t('翻译异常，请稍后重试'));
                }
              }
            }
          }
        });
      },
      /**
       * @Author: y_zp
       * @description: 数据处理分组
       */
      getArray(data, numSize) {
        let result = [];
        for (let i = 0; i < data.length; i += numSize) {
          result.push(data.slice(i, i + numSize));
        }
        return result;
      },
      /**
       * @Author: y_zp
       * @description: 百度翻译接口
       */
      async translateWithDelay(param) {
        return new Promise((resolve) => {
          setTimeout(() => {
            $translateService.sysLangTranslate(param).then(result => {
              resolve(result);
            }).catch(error => {
              resolve(error);
            });
          }, 1000);
      });
      },
      /**
       * @Author: y_zp
       * @description: 获取appId和密钥
       */
      getTranslateConfig() {
        // $appService.sysConfigByKey('system.translate.config').then((req) => {
        //   let info = req.data || {};
        //   this.translateConfig = eval('(' + info + ')');
        // });
        this.translateConfig = {
          type: "baidu",
          appId: "20250219002278238",
          secretKey: "Hjar7Ll6Za5jq5_SKBaC"
        }
      },

      toCancel() {
        this.visible = false;
        this.formList = {
          file: undefined,
          sourceType: undefined,
          targetType: undefined,
        };
        this.progressVal = 0;
        this.tLoading = false;
        this.submitLoading = false;
        this.dataList = [];
      },
    },
  };
</script>
<style lang="less" scoped>
  /deep/.batch_translate_list {
    .ant-modal-body {
      padding: 12px 16px;
    }
    .progress_bar {
      margin-top: 12px;
      margin-left: 12px;
    }
    .ant-progress-show-info .ant-progress-outer {
      margin-right: calc(-2em - 8px);
      padding-right: calc(2em + 8px);
    }
    .ant-progress-text {
      width: 2em;
      font-size: 13px;
    }
    .table_list {
      margin-top: 12px;
    }
  }
</style>
